context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
namespace Common
{
/// <summary>
/// MemoryTributary is a re-implementation of MemoryStream that uses a dynamic list of byte arrays as a backing store, instead of a single byte array, the allocation
/// of which will fail for relatively small streams as it requires contiguous memory.
/// </summary>
public class MemoryTributary : Stream /* http://msdn.microsoft.com/en-us/library/system.io.stream.aspx */
{
#region Constructors
public MemoryTributary()
{
Position = 0;
}
public MemoryTributary(byte[] source)
{
this.Write(source, 0, source.Length);
Position = 0;
}
/* length is ignored because capacity has no meaning unless we implement an artifical limit */
public MemoryTributary(int length)
{
SetLength(length);
Position = length;
byte[] d = block; //access block to prompt the allocation of memory
Position = 0;
}
#endregion
#region Status Properties
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
#endregion
#region Public Properties
public override long Length
{
get { return length; }
}
public override long Position { get; set; }
#endregion
#region Members
protected long length = 0;
protected long blockSize = 65536;
protected List<byte[]> blocks = new List<byte[]>();
#endregion
#region Internal Properties
/* Use these properties to gain access to the appropriate block of memory for the current Position */
/// <summary>
/// The block of memory currently addressed by Position
/// </summary>
protected byte[] block
{
get
{
while (blocks.Count <= blockId)
blocks.Add(new byte[blockSize]);
return blocks[(int)blockId];
}
}
/// <summary>
/// The id of the block currently addressed by Position
/// </summary>
protected long blockId
{
get { return Position / blockSize; }
}
/// <summary>
/// The offset of the byte currently addressed by Position, into the block that contains it
/// </summary>
protected long blockOffset
{
get { return Position % blockSize; }
}
#endregion
#region Public Stream Methods
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
long lcount = (long)count;
if (lcount < 0)
{
throw new ArgumentOutOfRangeException("count", lcount, "Number of bytes to copy cannot be negative.");
}
long remaining = (length - Position);
if (lcount > remaining)
lcount = remaining;
if (buffer == null)
{
throw new ArgumentNullException("buffer", "Buffer cannot be null.");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset",offset,"Destination offset cannot be negative.");
}
int read = 0;
long copysize = 0;
do
{
copysize = Math.Min(lcount, (blockSize - blockOffset));
Buffer.BlockCopy(block, (int)blockOffset, buffer, offset, (int)copysize);
lcount -= copysize;
offset += (int)copysize;
read += (int)copysize;
Position += copysize;
} while (lcount > 0);
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
Position = offset;
break;
case SeekOrigin.Current:
Position += offset;
break;
case SeekOrigin.End:
Position = Length - offset;
break;
}
return Position;
}
public override void SetLength(long value)
{
length = value;
}
public override void Write(byte[] buffer, int offset, int count)
{
long initialPosition = Position;
int copysize;
try
{
do
{
copysize = Math.Min(count, (int)(blockSize - blockOffset));
EnsureCapacity(Position + copysize);
Buffer.BlockCopy(buffer, (int)offset, block, (int)blockOffset, copysize);
count -= copysize;
offset += copysize;
Position += copysize;
} while (count > 0);
}
catch (Exception e)
{
Position = initialPosition;
throw e;
}
}
public override int ReadByte()
{
if (Position >= length)
return -1;
byte b = block[blockOffset];
Position++;
return b;
}
public override void WriteByte(byte value)
{
EnsureCapacity(Position + 1);
block[blockOffset] = value;
Position++;
}
protected void EnsureCapacity(long intended_length)
{
if (intended_length > length)
length = (intended_length);
}
#endregion
#region IDispose
/* http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx */
protected override void Dispose(bool disposing)
{
/* We do not currently use unmanaged resources */
base.Dispose(disposing);
}
#endregion
#region Public Additional Helper Methods
/// <summary>
/// Returns the entire content of the stream as a byte array. This is not safe because the call to new byte[] may
/// fail if the stream is large enough. Where possible use methods which operate on streams directly instead.
/// </summary>
/// <returns>A byte[] containing the current data in the stream</returns>
public byte[] ToArray()
{
long firstposition = Position;
Position = 0;
byte[] destination = new byte[Length];
Read(destination, 0, (int)Length);
Position = firstposition;
return destination;
}
/// <summary>
/// Reads length bytes from source into the this instance at the current position.
/// </summary>
/// <param name="source">The stream containing the data to copy</param>
/// <param name="length">The number of bytes to copy</param>
public void ReadFrom(Stream source, long length)
{
byte[] buffer = new byte[4096];
int read;
do
{
read = source.Read(buffer, 0, (int)Math.Min(4096, length));
length -= read;
this.Write(buffer, 0, read);
} while (length > 0);
}
/// <summary>
/// Writes the entire stream into destination, regardless of Position, which remains unchanged.
/// </summary>
/// <param name="destination">The stream to write the content of this stream to</param>
public void WriteTo(Stream destination)
{
long initialpos = Position;
Position = 0;
this.CopyTo(destination);
Position = initialpos;
}
#endregion
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.
// If defined, verifies that the assembly is in the GAC (which is slow).
// Otherwise just assumes it is installed.
//#define STRICT_GAC_CHECKS
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Gallio.Common.Collections;
using Gallio.Common.Reflection;
using Gallio.Runtime.Extensibility.Schema;
using Gallio.Common;
namespace Gallio.Runtime.Extensibility
{
/// <summary>
/// A plugin catalog implementation that verifies plugin dependencies and assembly references.
/// </summary>
public class PluginCatalog : IPluginCatalog
{
private readonly List<PluginData> plugins;
/// <summary>
/// Creates an empty plugin catalog.
/// </summary>
public PluginCatalog()
{
plugins = new List<PluginData>();
}
/// <inheritodc />
public void AddPlugin(Plugin plugin, DirectoryInfo baseDirectory)
{
if (plugin == null)
throw new ArgumentNullException("plugin");
if (baseDirectory == null)
throw new ArgumentNullException("baseDirectory");
plugins.Add(new PluginData(plugin, baseDirectory));
}
/// <inheritodc />
public void ApplyTo(IRegistry registry)
{
if (registry == null)
throw new ArgumentNullException("registry");
var topologicallySortedPlugins = TopologicalSortByDependencies(plugins);
IList<IPluginDescriptor> pluginDescriptors = RegisterPlugins(registry,
topologicallySortedPlugins);
RegisterServices(registry, topologicallySortedPlugins, pluginDescriptors);
RegisterComponents(registry, topologicallySortedPlugins, pluginDescriptors);
}
private static IList<IPluginDescriptor> RegisterPlugins(IRegistry registry, IList<PluginData> topologicallySortedPlugins)
{
IPluginDescriptor[] pluginDescriptors = new IPluginDescriptor[topologicallySortedPlugins.Count];
for (int i = 0; i < topologicallySortedPlugins.Count; i++)
{
Plugin plugin = topologicallySortedPlugins[i].Plugin;
DirectoryInfo baseDirectory = topologicallySortedPlugins[i].BaseDirectory;
try
{
var pluginType = plugin.PluginType != null
? new TypeName(plugin.PluginType)
: new TypeName(typeof(DefaultPlugin));
List<string> disabledReasons = new List<string>();
var pluginRegistration = new PluginRegistration(plugin.PluginId,
pluginType, baseDirectory);
if (plugin.Parameters != null)
pluginRegistration.PluginProperties = plugin.Parameters.PropertySet;
if (plugin.Traits != null)
pluginRegistration.TraitsProperties = plugin.Traits.PropertySet;
pluginRegistration.ProbingPaths = plugin.ProbingPaths;
pluginRegistration.RecommendedInstallationPath = plugin.RecommendedInstallationPath;
if (plugin.EnableCondition != null)
pluginRegistration.EnableCondition = Condition.Parse(plugin.EnableCondition);
foreach (var file in plugin.Files)
pluginRegistration.FilePaths.Add(file.Path);
foreach (var dependency in plugin.Dependencies)
{
string pluginDependencyId = dependency.PluginId;
IPluginDescriptor pluginDependency = registry.Plugins[pluginDependencyId];
if (pluginDependency == null)
{
disabledReasons.Add(string.Format("Could not find plugin '{0}' upon which this plugin depends.", pluginDependencyId));
}
else
{
pluginRegistration.PluginDependencies.Add(pluginDependency);
}
}
foreach (var assembly in plugin.Assemblies)
{
Uri absoluteCodeBase;
if (assembly.CodeBase != null)
{
List<string> attemptedPaths = new List<string>();
string foundCodeBasePath = ProbeForCodeBase(baseDirectory, plugin.ProbingPaths, assembly.CodeBase, attemptedPaths);
if (foundCodeBasePath == null)
{
StringBuilder formattedPaths = new StringBuilder();
foreach (string path in attemptedPaths)
{
if (formattedPaths.Length != 0)
formattedPaths.Append(", ");
formattedPaths.Append("'").Append(path).Append("'");
}
disabledReasons.Add(string.Format("Could not find assembly '{0}' after probing for its code base in {1}.",
assembly.FullName, formattedPaths));
absoluteCodeBase = null;
}
else
{
absoluteCodeBase = new Uri(foundCodeBasePath);
}
}
else
{
#if STRICT_GAC_CHECKS
if (!IsAssemblyRegisteredInGAC(assembly.FullName))
{
disabledReasons.Add(
string.Format("Could not find assembly '{0}' in the global assembly cache.",
assembly.FullName));
}
#endif
absoluteCodeBase = null;
}
var assemblyBinding = new AssemblyBinding(new AssemblyName(assembly.FullName))
{
CodeBase = absoluteCodeBase,
QualifyPartialName = assembly.QualifyPartialName,
ApplyPublisherPolicy = assembly.ApplyPublisherPolicy
};
foreach (BindingRedirect redirect in assembly.BindingRedirects)
assemblyBinding.AddBindingRedirect(new AssemblyBinding.BindingRedirect(redirect.OldVersion));
pluginRegistration.AssemblyBindings.Add(assemblyBinding);
}
IPluginDescriptor pluginDescriptor = registry.RegisterPlugin(pluginRegistration);
pluginDescriptors[i] = pluginDescriptor;
if (disabledReasons.Count != 0)
pluginDescriptor.Disable(disabledReasons[0]);
}
catch (Exception ex)
{
throw new RuntimeException(string.Format("Could not register plugin '{0}'.",
plugin.PluginId), ex);
}
}
return pluginDescriptors;
}
private static void RegisterServices(IRegistry registry, IList<PluginData> topologicallySortedPlugins, IList<IPluginDescriptor> pluginDescriptors)
{
for (int i = 0; i < topologicallySortedPlugins.Count; i++)
{
Plugin plugin = topologicallySortedPlugins[i].Plugin;
IPluginDescriptor pluginDescriptor = pluginDescriptors[i];
foreach (Service service in plugin.Services)
{
try
{
var serviceRegistration = new ServiceRegistration(pluginDescriptor,
service.ServiceId, new TypeName(service.ServiceType));
if (service.DefaultComponentType != null)
serviceRegistration.DefaultComponentTypeName = new TypeName(service.DefaultComponentType);
registry.RegisterService(serviceRegistration);
}
catch (Exception ex)
{
throw new RuntimeException(string.Format("Could not register service '{0}' of plugin '{1}'.",
service.ServiceId, plugin.PluginId), ex);
}
}
}
}
private static void RegisterComponents(IRegistry registry, IList<PluginData> topologicallySortedPlugins, IList<IPluginDescriptor> pluginDescriptors)
{
for (int i = 0; i < topologicallySortedPlugins.Count; i++)
{
Plugin plugin = topologicallySortedPlugins[i].Plugin;
IPluginDescriptor pluginDescriptor = pluginDescriptors[i];
foreach (Component component in plugin.Components)
{
var serviceDescriptor = registry.Services[component.ServiceId];
if (serviceDescriptor == null)
throw new RuntimeException(string.Format("Could not register component '{0}' of plugin '{1}' because it implements service '{2}' which was not found in the registry.",
component.ComponentId, plugin.PluginId, component.ServiceId));
try
{
var componentRegistration = new ComponentRegistration(pluginDescriptor,
serviceDescriptor, component.ComponentId,
component.ComponentType != null ? new TypeName(component.ComponentType) : null);
if (component.Parameters != null)
componentRegistration.ComponentProperties = component.Parameters.PropertySet;
if (component.Traits != null)
componentRegistration.TraitsProperties = component.Traits.PropertySet;
registry.RegisterComponent(componentRegistration);
}
catch (Exception ex)
{
throw new RuntimeException(string.Format("Could not register component '{0}' of plugin '{1}'.",
component.ComponentId, plugin.PluginId), ex);
}
}
}
}
private static string ProbeForCodeBase(DirectoryInfo baseDirectory, IList<string> probingPaths, string codeBase, ICollection<string> attemptedPaths)
{
foreach (string searchPath in ResourceSearchRules.GetSearchPaths(baseDirectory, probingPaths, codeBase))
{
attemptedPaths.Add(searchPath);
if (System.IO.File.Exists(searchPath))
return searchPath;
}
return null;
}
#if STRICT_GAC_CHECKS
private static bool IsAssemblyRegisteredInGAC(string assemblyName)
{
try
{
System.Reflection.Assembly.ReflectionOnlyLoad(assemblyName);
return true;
}
catch (FileNotFoundException)
{
return false;
}
}
#endif
private static IList<PluginData> TopologicalSortByDependencies(IList<PluginData> plugins)
{
Dictionary<string, PluginData> pluginsById = new Dictionary<string, PluginData>();
Dictionary<PluginData, int> outgoingDependencyCounts = new Dictionary<PluginData, int>();
MultiMap<PluginData, PluginData> incomingPluginDependencies = new MultiMap<PluginData, PluginData>();
Queue<PluginData> isolatedPlugins = new Queue<PluginData>();
foreach (PluginData plugin in plugins)
{
pluginsById[plugin.Plugin.PluginId] = plugin;
outgoingDependencyCounts[plugin] = 0;
}
foreach (PluginData plugin in plugins)
{
foreach (Dependency dependency in plugin.Plugin.Dependencies)
{
PluginData pluginDependency;
if (pluginsById.TryGetValue(dependency.PluginId, out pluginDependency))
{
incomingPluginDependencies.Add(pluginDependency, plugin);
outgoingDependencyCounts[plugin] += 1;
}
}
}
foreach (var pair in outgoingDependencyCounts)
{
if (pair.Value == 0)
isolatedPlugins.Enqueue(pair.Key);
}
List<PluginData> result = new List<PluginData>(plugins.Count);
while (isolatedPlugins.Count != 0)
{
PluginData plugin = isolatedPlugins.Dequeue();
result.Add(plugin);
foreach (PluginData incomingPluginDependency in incomingPluginDependencies[plugin])
{
int newCount = outgoingDependencyCounts[incomingPluginDependency] -= 1;
if (newCount == 0)
isolatedPlugins.Enqueue(incomingPluginDependency);
}
}
if (result.Count != plugins.Count)
{
StringBuilder message = new StringBuilder();
message.Append("Could not topologically sort the following plugins either due to dependency cycles or duplicate dependencies: ");
bool first = true;
foreach (var pair in outgoingDependencyCounts)
{
if (pair.Value != 0)
{
if (first)
first = false;
else
message.Append(", ");
message.Append("'").Append(pair.Key.Plugin.PluginId).Append("'");
}
}
message.Append(".");
throw new RuntimeException(message.ToString());
}
return result;
}
private sealed class PluginData
{
public readonly Plugin Plugin;
public readonly DirectoryInfo BaseDirectory;
public PluginData(Plugin plugin, DirectoryInfo baseDirectory)
{
Plugin = plugin;
BaseDirectory = baseDirectory;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using WizardsChessApp.Game.Pieces;
// To control the motions
namespace WizardsChessApp.Game {
class GameManager
{
// Global variables
private static ChessTeam Turn = ChessTeam.White;
// To play the game
public void playGame(){
System.Diagnostics.Debug.WriteLine("Blue Goes first");
bool execute = false;
while(true){
System.Diagnostics.Debug.WriteLine("Enter Start Location");
string Start = System.Diagnostics.Debug.ReadLine();
System.Diagnostics.Debug.WriteLine("Enter End Location");
string End = System.Diagnostics.Debug.ReadLine();
int[] startCoordinates = getFormattedCoordinate(Start);
int[] endCoordinates = getFormattedCoordinate(End);
// Get team of piece to check if it's their turn
String teamName = grid[startCoordinates[0],startCoordinates[1]].getTeamName();
if(teamName=="Team1" && team1Turn){
execute=true;
}else if(teamName=="Team2" && !team1Turn){
execute=true;
}
if(execute){
bool status = checkMoveValidity(startCoordinates,endCoordinates);
System.Diagnostics.Debug.WriteLine("Move from "+Start+" to "+End+" is: ");
if(status){
System.Diagnostics.Debug.WriteLine("Valid!");
movePiece(startCoordinates[0],startCoordinates[1],endCoordinates[0],endCoordinates[1]);
printNodes();
if(team1Turn){
team1Turn=false;
}else{
team1Turn=true;
}
}else{
System.Diagnostics.Debug.WriteLine("Invalid!");
printNodes();
}
// reset variables
execute=false;
}else{
System.Diagnostics.Debug.Write("You cannot move. It is ");
if(team1Turn){
System.Diagnostics.Debug.Write(" Blues Turn\n");
}else{
System.Diagnostics.Debug.Write(" Reds Turn\n");
}
printNodes();
}
}
}
// To see if move valid
public bool CheckMoveValidity(Position startCoordinates, int[] endCoordinates){
bool isValidMove = false;
// Get piece at input location
ChessPiece startPiece = grid[startCoordinates[0],startCoordinates[1]];
ChessPiece endPiece = grid[endCoordinates[0],endCoordinates[1]];
// To hold object values
string startPieceName;
string startPieceTeam;
string endPieceTeam;
bool attemptMoveCheck = false;
// To break if objects in the way
bool objectsInWay = false;
// // check if valid move then check if anything blocking seperatly
if (startPiece != null){
startPieceName = startPiece.getName();
System.Diagnostics.Debug.WriteLine(startPieceName);
startPieceTeam = startPiece.getTeamName();
// If there is a piece there we need to check if friendly or not
if(endPiece != null){
// if is not a friently piece can move there
endPieceTeam = endPiece.getTeamName();
if(endPieceTeam!=startPieceTeam){
attemptMoveCheck = true;
}
}else{
attemptMoveCheck = true;
}
if(attemptMoveCheck){
// This tile is empty, we can look into moving here
List<int[]> allowedMoveVectors = startPiece.getAllowedMotionVector();
// given start and end coordinates, let us subtract to get vector
int xVector = endCoordinates[0]-startCoordinates[0];
int yVector = endCoordinates[1]-startCoordinates[1];
// Check to see if move is possible in constraints of piece movement allowment
foreach (int[] allocatedMoveSet in allowedMoveVectors){
// if pawn, knight, king, need exact
if(startPieceName=="Pawn" || startPieceName=="Knight" || startPieceName=="King"){
foreach (int[] vector in allowedMoveVectors){
if(vector[0]==xVector && vector[1]==yVector){
isValidMove = true;
}
}
}else{
// All of these can have variants of allowed movement vectors
foreach (int[] vector in allowedMoveVectors){
if(startPieceName=="Bishop"){
if(xVector!=0 && yVector !=0){
if(xVector%vector[0]==yVector%vector[1]){
// Check for collisions here
if(checkCollisions(startCoordinates,endCoordinates,vector)){
isValidMove=true;
break;
}
}
}
}
if(startPieceName=="Queen"){
System.Diagnostics.Debug.WriteLine(xVector);
System.Diagnostics.Debug.WriteLine(yVector);
if(xVector!= 0 && yVector!=0){
//System.Diagnostics.Debug.WriteLine("Diag");
if(Math.Abs(xVector) == Math.Abs(yVector)){
// Check for collisions here
if(checkCollisions(startCoordinates,endCoordinates,vector)){
isValidMove=true;
break;
}
}
}else if((xVector==0 && yVector!=0)||(yVector==0 && xVector!=0)){
//System.Diagnostics.Debug.WriteLine("X Dir");
if(checkCollisions(startCoordinates,endCoordinates,vector)){
isValidMove = true;
break;
}
}
}
if(startPieceName=="Rook"){
if((xVector==0 && yVector!=0)||(yVector==0 && xVector!=0)){
// Only run if relevant to this particular search
if(checkCollisions(startCoordinates,endCoordinates,vector)){
isValidMove = true;
break;
}
/*
else{
objectsInWay=true;
break;
}
*/
}
}
}
}
if(isValidMove){
break;
}else if(objectsInWay){
break;
}
}
}
}else{
System.Diagnostics.Debug.WriteLine("Piece 1 doesn't exist. Valid input needed to proceed");
}
return isValidMove;
}
// To check whether there will be collisions
// Input Start coordinate, end coordinates, vector
// output if any collisions. True if okay to move
public bool checkCollisions(int[] startCoordinates,int[] endCoordinates,int[] vector){
bool ableToMove = true;
int xIncrementer=0;
int yIncrementer=0;
int incrementsNeededToCheck = 0;
if(vector[0]>0){
xIncrementer=1;
}else if(vector[0]<0){
xIncrementer=-1;
}else{
xIncrementer=0;
}
if(vector[1]>0){
yIncrementer = -1;
}else if(vector[1]<0){
yIncrementer=1;
}else{
yIncrementer=0;
}
if(Math.Abs(endCoordinates[0]-startCoordinates[0])>Math.Abs(endCoordinates[1]-startCoordinates[1])){
incrementsNeededToCheck=Math.Abs(endCoordinates[0]-startCoordinates[0]);
}else{
incrementsNeededToCheck=Math.Abs(endCoordinates[1]-startCoordinates[1]);
}
int X = startCoordinates[0];
int Y = startCoordinates[1];
for(int i=0; i< incrementsNeededToCheck;i++){
X += xIncrementer;
Y += yIncrementer;
// ensure values in grid()
if(X<0 || X>7 || Y<0 || Y>7){
ableToMove=false;
break;
}
if(grid[X,Y]!=null){
System.Diagnostics.Debug.WriteLine("Stuff in WAY!");
ableToMove=false;
break;
}
}
return ableToMove;
}
// to move the piece once verified
// input: start, and end coordinates
// output: void
public void movePiece(int startX, int startY, int endX, int endY){
grid[endX,endY] = grid[startX,startY];
grid[endX,endY].setMoved();
grid[startX,startY] = null;
}
// To take a coordinate input and turn into something readable
// Returns an array where val[0]=x, val[1]=y
// Depreciated. Morgan will be parsing inputs
public int[] getFormattedCoordinate(string coordinate){
int[] returnable = new int[2];
string XRaw;
string YRaw;
XRaw = coordinate[1].ToString();
YRaw = coordinate[0].ToString();
int XFinal=0;
int YFinal=0;
switch(YRaw){
case "A":
YFinal = 1;
break;
case "B":
YFinal = 2;
break;
case "C":
YFinal = 3;
break;
case "D":
YFinal = 4;
break;
case "E":
YFinal = 5;
break;
case "F":
YFinal = 6;
break;
case "G":
YFinal = 7;
break;
case "H":
YFinal = 8;
break;
default:
System.Diagnostics.Debug.WriteLine("Invalid move was given");
break;
}
XFinal = Int32.Parse(XRaw);
// We need to subtract by 1 for the matrix locations
returnable[0] = XFinal-1;
returnable[1] = YFinal-1;
return returnable;
}
public void printNodes(){
int ASCIIA = 64;
for(int k=-1; k< grid.GetLength(0);k++){
for(int j=-1; j < grid.GetLength(1);j++){
if (k==-1){
if(j==-1){
//output+= " | | ";
System.Diagnostics.Debug.Write(" | | ");
}else{
//output+=" | "+(char)ASCIIA+" | ";
System.Diagnostics.Debug.Write(" | "+(char)ASCIIA+" | ");
}
ASCIIA++;
}else{
if(j ==-1 && k ==-1){
System.Diagnostics.Debug.Write(" | | ");
}else if(j==-1){
System.Diagnostics.Debug.Write(" | "+(k+1)+" | ");
}else{
if(grid[k,j] ==null){
//output+=" | | ";
System.Diagnostics.Debug.Write(" | | ");
}else{
string spacer = grid[k,j].getName();
int spacerIndex = 0;
spacerIndex = 10 - grid[k,j].getName().Length;
for(int i=0; i< spacerIndex; i++){
spacer+=" ";
}
//output+= " |"+spacer+"| ";
System.Diagnostics.Debug.Write(" |");
string team = grid[k,j].getTeamName();
if(team=="Team1"){
System.Diagnostics.Debug.ForegroundColor = ConsoleColor.Blue;
}else{
System.Diagnostics.Debug.ForegroundColor = ConsoleColor.Red;
}
System.Diagnostics.Debug.Write(spacer);
System.Diagnostics.Debug.ResetColor();
System.Diagnostics.Debug.Write("| ");
}
}
}
}
//System.Diagnostics.Debug.WriteLine(output);
System.Diagnostics.Debug.Write("\n");
}
}
}
}
| |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Courier
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Contracts;
using InternalMessages;
using MassTransit.Serialization;
using Newtonsoft.Json;
using Serialization;
using Util;
public class RoutingSlipEventPublisher :
IRoutingSlipEventPublisher
{
readonly HostInfo _host;
readonly IPublishEndpoint _publishEndpoint;
readonly RoutingSlip _routingSlip;
readonly ISendEndpointProvider _sendEndpointProvider;
readonly string _activityName;
static RoutingSlipEventPublisher()
{
RoutingSlipEventCorrelation.ConfigureCorrelationIds();
}
public RoutingSlipEventPublisher(CompensateContext compensateContext, RoutingSlip routingSlip)
: this(compensateContext, compensateContext, routingSlip)
{
_sendEndpointProvider = compensateContext;
_publishEndpoint = compensateContext;
_routingSlip = routingSlip;
_activityName = compensateContext.ActivityName;
_host = compensateContext.Host;
}
public RoutingSlipEventPublisher(ExecuteContext executeContext, RoutingSlip routingSlip)
: this(executeContext, executeContext, routingSlip)
{
_sendEndpointProvider = executeContext;
_publishEndpoint = executeContext;
_routingSlip = routingSlip;
_activityName = executeContext.ActivityName;
_host = executeContext.Host;
}
public RoutingSlipEventPublisher(ISendEndpointProvider sendEndpointProvider, IPublishEndpoint publishEndpoint, RoutingSlip routingSlip)
{
_sendEndpointProvider = sendEndpointProvider;
_publishEndpoint = publishEndpoint;
_routingSlip = routingSlip;
_host = HostMetadataCache.Host;
}
public Task PublishRoutingSlipCompleted(DateTime timestamp, TimeSpan duration, IDictionary<string, object> variables)
{
return PublishEvent<RoutingSlipCompleted>(RoutingSlipEvents.Completed, contents => new RoutingSlipCompletedMessage(
_routingSlip.TrackingNumber,
timestamp,
duration,
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)
? variables
: GetEmptyObject()
));
}
public Task PublishRoutingSlipFaulted(DateTime timestamp, TimeSpan duration, IDictionary<string, object> variables,
params ActivityException[] exceptions)
{
return PublishEvent<RoutingSlipFaulted>(RoutingSlipEvents.Faulted, contents => new RoutingSlipFaultedMessage(
_routingSlip.TrackingNumber,
timestamp,
duration,
exceptions,
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)
? variables
: GetEmptyObject()
));
}
public Task PublishRoutingSlipActivityCompleted(string activityName, Guid executionId,
DateTime timestamp, TimeSpan duration, IDictionary<string, object> variables, IDictionary<string, object> arguments,
IDictionary<string, object> data)
{
return PublishEvent<RoutingSlipActivityCompleted>(RoutingSlipEvents.ActivityCompleted, contents => new RoutingSlipActivityCompletedMessage(
_host,
_routingSlip.TrackingNumber,
activityName,
executionId,
timestamp,
duration,
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)
? variables
: GetEmptyObject(),
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Arguments)
? arguments
: GetEmptyObject(),
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Data)
? data
: GetEmptyObject()));
}
public Task PublishRoutingSlipActivityFaulted(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration, ExceptionInfo exceptionInfo,
IDictionary<string, object> variables, IDictionary<string, object> arguments)
{
return PublishEvent<RoutingSlipActivityFaulted>(RoutingSlipEvents.ActivityFaulted, contents => new RoutingSlipActivityFaultedMessage(
_host,
_routingSlip.TrackingNumber,
activityName,
executionId,
timestamp,
duration,
exceptionInfo,
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)
? variables
: GetEmptyObject(),
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Arguments)
? arguments
: GetEmptyObject()));
}
public Task PublishRoutingSlipActivityCompensated(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration,
IDictionary<string, object> variables, IDictionary<string, object> data)
{
return PublishEvent<RoutingSlipActivityCompensated>(RoutingSlipEvents.ActivityCompensated, contents => new RoutingSlipActivityCompensatedMessage(
_host,
_routingSlip.TrackingNumber,
activityName,
executionId,
timestamp,
duration,
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)
? variables
: GetEmptyObject(),
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Arguments)
? data
: GetEmptyObject()));
}
public Task PublishRoutingSlipRevised(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration,
IDictionary<string, object> variables,
IList<Activity> itinerary, IList<Activity> previousItinerary)
{
return PublishEvent<RoutingSlipRevised>(RoutingSlipEvents.Revised, contents => new RoutingSlipRevisedMessage(
_host,
_routingSlip.TrackingNumber,
activityName,
executionId,
timestamp,
duration,
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)
? variables
: GetEmptyObject(),
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Itinerary)
? itinerary
: Enumerable.Empty<Activity>(),
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Itinerary)
? previousItinerary
: Enumerable.Empty<Activity>()));
}
public Task PublishRoutingSlipTerminated(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration,
IDictionary<string, object> variables,
IList<Activity> previousItinerary)
{
return PublishEvent<RoutingSlipTerminated>(RoutingSlipEvents.Terminated, contents => new RoutingSlipTerminatedMessage(
_host,
_routingSlip.TrackingNumber,
activityName,
executionId,
timestamp,
duration,
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)
? variables
: GetEmptyObject(),
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Itinerary)
? previousItinerary
: Enumerable.Empty<Activity>()));
}
public Task PublishRoutingSlipActivityCompensationFailed(string activityName, Guid executionId,
DateTime timestamp, TimeSpan duration, DateTime failureTimestamp, TimeSpan routingSlipDuration,
ExceptionInfo exceptionInfo, IDictionary<string, object> variables, IDictionary<string, object> data)
{
return PublishEvent(RoutingSlipEvents.ActivityCompensationFailed | RoutingSlipEvents.CompensationFailed, contents => new CompensationFailed(
_host,
_routingSlip.TrackingNumber,
activityName,
executionId,
timestamp,
duration,
failureTimestamp,
routingSlipDuration,
exceptionInfo,
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)
? variables
: GetEmptyObject(),
contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Data)
? data
: GetEmptyObject()));
}
static IDictionary<string, object> GetEmptyObject()
{
return JsonConvert.DeserializeObject<IDictionary<string, object>>("{}");
}
async Task PublishEvent<T>(RoutingSlipEvents eventFlag, Func<RoutingSlipEventContents, T> messageFactory)
where T : class
{
foreach (var subscription in _routingSlip.Subscriptions)
{
await PublishSubscriptionEvent(eventFlag, messageFactory, subscription).ConfigureAwait(false);
}
if (_routingSlip.Subscriptions.All(sub => sub.Events.HasFlag(RoutingSlipEvents.Supplemental)))
{
await _publishEndpoint.Publish(messageFactory(RoutingSlipEventContents.All)).ConfigureAwait(false);
}
}
async Task PublishSubscriptionEvent<T>(RoutingSlipEvents eventFlag, Func<RoutingSlipEventContents, T> messageFactory, Subscription subscription)
where T : class
{
if ((subscription.Events & RoutingSlipEvents.EventMask) == RoutingSlipEvents.All || subscription.Events.HasFlag(eventFlag))
{
if (string.IsNullOrWhiteSpace(_activityName) || string.IsNullOrWhiteSpace(subscription.ActivityName)
|| _activityName.Equals(subscription.ActivityName, StringComparison.OrdinalIgnoreCase))
{
var endpoint = await _sendEndpointProvider.GetSendEndpoint(subscription.Address).ConfigureAwait(false);
var message = messageFactory(subscription.Include);
if (subscription.Message != null)
{
var adapter = new MessageEnvelopeContextAdapter(null, subscription.Message, JsonMessageSerializer.ContentTypeHeaderValue, message);
await endpoint.Send(message, adapter).ConfigureAwait(false);
}
else
await endpoint.Send(message).ConfigureAwait(false);
}
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="DataServiceRequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// query request object
// </summary>
//---------------------------------------------------------------------
namespace System.Data.Services.Client
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
#if !ASTORIA_LIGHT // Data.Services http stack
using System.Net;
#else
using System.Data.Services.Http;
#endif
using System.Xml;
/// <summary>non-generic placeholder for generic implementation</summary>
public abstract class DataServiceRequest
{
/// <summary>internal constructor so that only our assembly can provide an implementation</summary>
internal DataServiceRequest()
{
}
/// <summary>Element Type</summary>
public abstract Type ElementType
{
get;
}
/// <summary>Gets the URI for a the query</summary>
public abstract Uri RequestUri
{
get;
}
/// <summary>The ProjectionPlan for the request, if precompiled in a previous page; null otherwise.</summary>
internal abstract ProjectionPlan Plan
{
get;
}
/// <summary>The TranslateResult associated with this request</summary>
internal abstract QueryComponents QueryComponents
{
get;
}
/// <summary>Gets the URI for a the query</summary>
/// <returns>a string with the URI</returns>
public override string ToString()
{
return this.QueryComponents.Uri.ToString();
}
/// <summary>
/// get an enumerable materializes the objects the response
/// </summary>
/// <param name="context">context</param>
/// <param name="queryComponents">query components</param>
/// <param name="plan">Projection plan (if compiled in an earlier query).</param>
/// <param name="contentType">contentType</param>
/// <param name="response">method to get http response stream</param>
/// <returns>atom materializer</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Returning MaterializeAtom, caller will dispose")]
internal static MaterializeAtom Materialize(DataServiceContext context, QueryComponents queryComponents, ProjectionPlan plan, string contentType, Stream response)
{
Debug.Assert(null != queryComponents, "querycomponents");
string mime = null;
Encoding encoding = null;
if (!String.IsNullOrEmpty(contentType))
{
HttpProcessUtility.ReadContentType(contentType, out mime, out encoding);
}
if (String.Equals(mime, XmlConstants.MimeApplicationAtom, StringComparison.OrdinalIgnoreCase) ||
String.Equals(mime, XmlConstants.MimeApplicationXml, StringComparison.OrdinalIgnoreCase))
{
if (null != response)
{
XmlReader reader = XmlUtil.CreateXmlReader(response, encoding);
return new MaterializeAtom(context, reader, queryComponents, plan, context.MergeOption);
}
}
return MaterializeAtom.EmptyResults;
}
/// <summary>
/// Creates a instance of strongly typed DataServiceRequest with the given element type.
/// </summary>
/// <param name="elementType">element type for the DataServiceRequest.</param>
/// <param name="requestUri">constructor parameter.</param>
/// <returns>returns the strongly typed DataServiceRequest instance.</returns>
internal static DataServiceRequest GetInstance(Type elementType, Uri requestUri)
{
Type genericType = typeof(DataServiceRequest<>).MakeGenericType(elementType);
return (DataServiceRequest)Activator.CreateInstance(genericType, new object[] { requestUri });
}
/// <summary>
/// Ends an asynchronous request to an Internet resource.
/// </summary>
/// <typeparam name="TElement">Element type of the result.</typeparam>
/// <param name="source">Source object of async request.</param>
/// <param name="context">The data service context.</param>
/// <param name="asyncResult">The asyncResult being ended.</param>
/// <returns>The response - result of the request.</returns>
internal static IEnumerable<TElement> EndExecute<TElement>(object source, DataServiceContext context, IAsyncResult asyncResult)
{
QueryResult result = null;
try
{
result = QueryResult.EndExecute<TElement>(source, asyncResult);
return result.ProcessResult<TElement>(context, result.ServiceRequest.Plan);
}
catch (DataServiceQueryException ex)
{
Exception inEx = ex;
while (inEx.InnerException != null)
{
inEx = inEx.InnerException;
}
DataServiceClientException serviceEx = inEx as DataServiceClientException;
if (context.IgnoreResourceNotFoundException && serviceEx != null && serviceEx.StatusCode == (int)HttpStatusCode.NotFound)
{
QueryOperationResponse qor = new QueryOperationResponse<TElement>(new Dictionary<string, string>(ex.Response.Headers), ex.Response.Query, MaterializeAtom.EmptyResults);
qor.StatusCode = (int)HttpStatusCode.NotFound;
return (IEnumerable<TElement>)qor;
}
throw;
}
}
#if !ASTORIA_LIGHT // Synchronous methods not available
/// <summary>
/// execute uri and materialize result
/// </summary>
/// <typeparam name="TElement">element type</typeparam>
/// <param name="context">context</param>
/// <param name="queryComponents">query components for request to execute</param>
/// <returns>enumerable of results</returns>
internal QueryOperationResponse<TElement> Execute<TElement>(DataServiceContext context, QueryComponents queryComponents)
{
QueryResult result = null;
try
{
DataServiceRequest<TElement> serviceRequest = new DataServiceRequest<TElement>(queryComponents, this.Plan);
result = serviceRequest.CreateResult(this, context, null, null);
result.Execute();
return result.ProcessResult<TElement>(context, this.Plan);
}
catch (InvalidOperationException ex)
{
QueryOperationResponse operationResponse = result.GetResponse<TElement>(MaterializeAtom.EmptyResults);
if (null != operationResponse)
{
if (context.IgnoreResourceNotFoundException)
{
DataServiceClientException cex = ex as DataServiceClientException;
if (cex != null && cex.StatusCode == (int)HttpStatusCode.NotFound)
{
// don't throw
return (QueryOperationResponse<TElement>)operationResponse;
}
}
operationResponse.Error = ex;
throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
}
throw;
}
}
/// <summary>
/// Synchronizely get the query set count from the server by executing the $count=value query
/// </summary>
/// <param name="context">The context</param>
/// <returns>The server side count of the query set</returns>
internal long GetQuerySetCount(DataServiceContext context)
{
Debug.Assert(null != context, "context is null");
this.QueryComponents.Version = Util.DataServiceVersion2;
QueryResult response = null;
DataServiceRequest<long> serviceRequest = new DataServiceRequest<long>(this.QueryComponents, null);
HttpWebRequest request = context.CreateRequest(this.QueryComponents.Uri, XmlConstants.HttpMethodGet, false, null, this.QueryComponents.Version, false);
request.Accept = "text/plain";
response = new QueryResult(this, "Execute", serviceRequest, request, null, null);
try
{
response.Execute();
if (HttpStatusCode.NoContent != response.StatusCode)
{
StreamReader sr = new StreamReader(response.GetResponseStream());
long r = -1;
try
{
r = XmlConvert.ToInt64(sr.ReadToEnd());
}
finally
{
sr.Close();
}
return r;
}
else
{
throw new DataServiceQueryException(Strings.DataServiceRequest_FailGetCount, response.Failure);
}
}
catch (InvalidOperationException ex)
{
QueryOperationResponse operationResponse = null;
operationResponse = response.GetResponse<long>(MaterializeAtom.EmptyResults);
if (null != operationResponse)
{
operationResponse.Error = ex;
throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
}
throw;
}
}
#endif
/// <summary>
/// Begins an asynchronous request to an Internet resource.
/// </summary>
/// <param name="source">source of execute (DataServiceQuery or DataServiceContext</param>
/// <param name="context">context</param>
/// <param name="callback">The AsyncCallback delegate.</param>
/// <param name="state">The state object for this request.</param>
/// <returns>An IAsyncResult that references the asynchronous request for a response.</returns>
internal IAsyncResult BeginExecute(object source, DataServiceContext context, AsyncCallback callback, object state)
{
QueryResult result = this.CreateResult(source, context, callback, state);
result.BeginExecute();
return result;
}
/// <summary>
/// Creates the result object for the specified query parameters.
/// </summary>
/// <param name="source">The source object for the request.</param>
/// <param name="context">The data service context.</param>
/// <param name="callback">The AsyncCallback delegate.</param>
/// <param name="state">The state object for the callback.</param>
/// <returns>Result representing the create request. The request has not been initiated yet.</returns>
private QueryResult CreateResult(object source, DataServiceContext context, AsyncCallback callback, object state)
{
Debug.Assert(null != context, "context is null");
HttpWebRequest request = context.CreateRequest(this.QueryComponents.Uri, XmlConstants.HttpMethodGet, false, null, this.QueryComponents.Version, false);
return new QueryResult(source, "Execute", this, request, callback, state);
}
}
}
| |
//
// Authors:
// Atsushi Enomoto
//
// Copyright 2007 Novell (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.IO;
using System.Text;
using System.Xml;
using XPI = System.Xml.Linq.XProcessingInstruction;
namespace System.Xml.Linq
{
internal abstract class XNode : XObject
{
public static int CompareDocumentOrder (XNode n1, XNode n2)
{
return order_comparer.Compare (n1, n2);
}
public static bool DeepEquals (XNode n1, XNode n2)
{
return eq_comparer.Equals (n1, n2);
}
static XNodeEqualityComparer eq_comparer =
new XNodeEqualityComparer ();
static XNodeDocumentOrderComparer order_comparer =
new XNodeDocumentOrderComparer ();
XNode previous;
XNode next;
internal XNode ()
{
}
public static XNodeDocumentOrderComparer DocumentOrderComparer {
get { return order_comparer; }
}
public static XNodeEqualityComparer EqualityComparer {
get { return eq_comparer; }
}
public XNode PreviousNode {
get { return previous; }
internal set { previous = value; }
}
public XNode NextNode {
get { return next; }
internal set { next = value; }
}
public string ToString (SaveOptions options)
{
StringWriter sw = new StringWriter ();
XmlWriterSettings s = new XmlWriterSettings ();
s.ConformanceLevel = ConformanceLevel.Auto;
s.Indent = options != SaveOptions.DisableFormatting;
XmlWriter xw = XmlWriter.Create (sw, s);
WriteTo (xw);
xw.Close ();
return sw.ToString ();
}
public void AddAfterSelf (object content)
{
if (Owner == null)
throw new InvalidOperationException ();
XNode here = this;
XNode orgNext = next;
foreach (object o in XUtil.ExpandArray (content)) {
if (o == null || Owner.OnAddingObject (o, true, here, false))
continue;
XNode n = XUtil.ToNode (o);
Owner.OnAddingObject (n);
n = (XNode) XUtil.GetDetachedObject (n);
n.SetOwner (Owner);
n.previous = here;
here.next = n;
n.next = orgNext;
if (orgNext != null)
orgNext.previous = n;
else
Owner.LastNode = n;
here = n;
Owner.OnAddedObject (n);
}
}
public void AddAfterSelf (params object [] content)
{
if (Owner == null)
throw new InvalidOperationException ();
AddAfterSelf ((object) content);
}
public void AddBeforeSelf (object content)
{
if (Owner == null)
throw new InvalidOperationException ();
foreach (object o in XUtil.ExpandArray (content)) {
if (o == null || Owner.OnAddingObject (o, true, previous, true))
continue;
XNode n = XUtil.ToNode (o);
Owner.OnAddingObject (n);
n = (XNode) XUtil.GetDetachedObject (n);
n.SetOwner (Owner);
n.previous = previous;
n.next = this;
if (previous != null)
previous.next = n;
previous = n;
if (Owner.FirstNode == this)
Owner.FirstNode = n;
Owner.OnAddedObject (n);
}
}
public void AddBeforeSelf (params object [] content)
{
if (Owner == null)
throw new InvalidOperationException ();
AddBeforeSelf ((object) content);
}
public static XNode ReadFrom (XmlReader reader)
{
return ReadFrom (reader, LoadOptions.None);
}
internal static XNode ReadFrom (XmlReader r, LoadOptions options)
{
switch (r.NodeType) {
case XmlNodeType.Element:
return XElement.LoadCore (r, options);
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Text:
XText t = new XText (r.Value);
t.FillLineInfoAndBaseUri (r, options);
r.Read ();
return t;
case XmlNodeType.CDATA:
XCData c = new XCData (r.Value);
c.FillLineInfoAndBaseUri (r, options);
r.Read ();
return c;
case XmlNodeType.ProcessingInstruction:
XPI pi = new XPI (r.Name, r.Value);
pi.FillLineInfoAndBaseUri (r, options);
r.Read ();
return pi;
case XmlNodeType.Comment:
XComment cm = new XComment (r.Value);
cm.FillLineInfoAndBaseUri (r, options);
r.Read ();
return cm;
case XmlNodeType.DocumentType:
XDocumentType d = new XDocumentType (r.Name,
r.GetAttribute ("PUBLIC"),
r.GetAttribute ("SYSTEM"),
r.Value);
d.FillLineInfoAndBaseUri (r, options);
r.Read ();
return d;
default:
throw new InvalidOperationException (String.Format ("Node type {0} is not supported", r.NodeType));
}
}
public void Remove ()
{
if (Owner == null)
throw new InvalidOperationException ("Owner is missing");
var owner = Owner;
owner.OnRemovingObject (this);
if (Owner.FirstNode == this)
Owner.FirstNode = next;
if (Owner.LastNode == this)
Owner.LastNode = previous;
if (previous != null)
previous.next = next;
if (next != null)
next.previous = previous;
previous = null;
next = null;
SetOwner (null);
owner.OnRemovedObject (this);
}
public override string ToString ()
{
return ToString (SaveOptions.None);
}
public abstract void WriteTo (XmlWriter writer);
public IEnumerable<XElement> Ancestors ()
{
for (XElement el = Parent; el != null; el = el.Parent)
yield return el;
}
public IEnumerable<XElement> Ancestors (XName name)
{
foreach (XElement el in Ancestors ())
if (el.Name == name)
yield return el;
}
public XmlReader CreateReader ()
{
return new XNodeReader (this);
}
#if NET_4_0
public XmlReader CreateReader (ReaderOptions readerOptions)
{
var r = new XNodeReader (this);
if ((readerOptions & ReaderOptions.OmitDuplicateNamespaces) != 0)
r.OmitDuplicateNamespaces = true;
return r;
}
#endif
public IEnumerable<XElement> ElementsAfterSelf ()
{
foreach (XNode n in NodesAfterSelf ())
if (n is XElement)
yield return (XElement) n;
}
public IEnumerable<XElement> ElementsAfterSelf (XName name)
{
foreach (XElement el in ElementsAfterSelf ())
if (el.Name == name)
yield return el;
}
public IEnumerable<XElement> ElementsBeforeSelf ()
{
foreach (XNode n in NodesBeforeSelf ())
if (n is XElement)
yield return (XElement) n;
}
public IEnumerable<XElement> ElementsBeforeSelf (XName name)
{
foreach (XElement el in ElementsBeforeSelf ())
if (el.Name == name)
yield return el;
}
public bool IsAfter (XNode node)
{
return XNode.DocumentOrderComparer.Compare (this, node) > 0;
}
public bool IsBefore (XNode node)
{
return XNode.DocumentOrderComparer.Compare (this, node) < 0;
}
public IEnumerable<XNode> NodesAfterSelf ()
{
if (Owner == null)
yield break;
for (XNode n = NextNode; n != null; n = n.NextNode)
yield return n;
}
public IEnumerable<XNode> NodesBeforeSelf ()
{
if (Owner == null)
yield break;
for (XNode n = Owner.FirstNode; n != this; n = n.NextNode)
yield return n;
}
public void ReplaceWith (object content)
{
if (Owner == null)
throw new InvalidOperationException ();
XNode here = previous;
XNode orgNext = next;
XContainer orgOwner = Owner;
Remove();
foreach (object o in XUtil.ExpandArray (content)) {
if (o == null || orgOwner.OnAddingObject (o, true, here, false))
continue;
XNode n = XUtil.ToNode (o);
n = (XNode) XUtil.GetDetachedObject (n);
n.SetOwner (orgOwner);
n.previous = here;
if (here != null)
here.next = n;
else
orgOwner.FirstNode = n;
n.next = orgNext;
if (orgNext != null)
orgNext.previous = n;
else
orgOwner.LastNode = n;
here = n;
}
}
public void ReplaceWith (params object [] content)
{
if (Owner == null)
throw new InvalidOperationException ();
ReplaceWith ((object) content);
}
}
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Box2
{
Demo demo;
PhysicsScene scene;
string instanceIndexName;
public Box2(Demo demo, int instanceIndex)
{
this.demo = demo;
instanceIndexName = " " + instanceIndex.ToString();
}
public void Initialize(PhysicsScene scene)
{
this.scene = scene;
}
public static void CreateShapes(Demo demo, PhysicsScene scene)
{
ShapePrimitive shapePrimitive = null;
Shape shape = null;
Vector3[] convexTab = new Vector3[8];
convexTab[0] = new Vector3(-1.0f, -1.0f, 1.0f);
convexTab[1] = new Vector3(-1.0f, 1.0f, 1.0f);
convexTab[2] = new Vector3(1.0f, 0.752f, 1.0f);
convexTab[3] = new Vector3(1.0f, -0.752f, 1.0f);
convexTab[4] = new Vector3(-1.0f, -1.0f, -1.0f);
convexTab[5] = new Vector3(-1.0f, 1.0f, -1.0f);
convexTab[6] = new Vector3(1.0f, 0.752f, -1.0f);
convexTab[7] = new Vector3(1.0f, -0.752f, -1.0f);
shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("Box2Convex1");
shapePrimitive.CreateConvex(convexTab);
shape = scene.Factory.ShapeManager.Create("Box2Convex1");
shape.Set(shapePrimitive, Matrix4.Identity, 0.0f);
shape.CreateMesh(0.0f);
if (!demo.Meshes.ContainsKey("Box2Convex1"))
demo.Meshes.Add("Box2Convex1", new DemoMesh(demo, shape, demo.Textures["Default"], Vector2.One, false, false, false, false, false, CullFaceMode.Back, false, false));
}
public void Create(Vector3 objectPosition, Vector3 objectScale, Quaternion objectOrientation, int maxPlank, Vector3 plankScale, float plankDistance)
{
Shape box = scene.Factory.ShapeManager.Find("Box");
Shape box2Convex1 = scene.Factory.ShapeManager.Find("Box2Convex1");
PhysicsObject objectRoot = null;
PhysicsObject objectBase = null;
objectRoot = scene.Factory.PhysicsObjectManager.Create("Box 2" + instanceIndexName);
Vector3 plankScale1 = plankScale;
Vector3 plankScale2 = plankScale;
plankScale2.X *= 0.5f;
for (int i = 0; i < maxPlank; i++)
{
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Plank Up " + i.ToString() + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(i * 2.0f * (plankScale1.X + plankDistance) - maxPlank * (plankScale1.X + plankDistance) + (plankScale1.X + plankDistance), 0.0f, maxPlank * (plankScale1.X + plankDistance) - plankScale1.Z - plankDistance);
objectBase.InitLocalTransform.SetScale(plankScale1);
objectBase.Integral.SetDensity(1.0f);
}
for (int i = 0; i < maxPlank; i++)
{
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Plank Down " + i.ToString() + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(i * 2.0f * (plankScale1.X + plankDistance) - maxPlank * (plankScale1.X + plankDistance) + (plankScale1.X + plankDistance), 0.0f, -maxPlank * (plankScale1.X + plankDistance) + plankScale1.Z + plankDistance);
objectBase.InitLocalTransform.SetScale(plankScale1);
objectBase.Integral.SetDensity(1.0f);
}
for (int i = 0; i < maxPlank; i++)
{
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Plank Right " + i.ToString() + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(maxPlank * (plankScale1.X + plankDistance) + plankScale1.Z - plankDistance, 0.0f, i * 2.0f * (plankScale1.X + plankDistance) - maxPlank * (plankScale1.X + plankDistance) + (plankScale1.X + plankDistance));
objectBase.InitLocalTransform.SetScale(plankScale1.Z, plankScale1.Y, plankScale1.X);
objectBase.Integral.SetDensity(1.0f);
}
for (int i = 0; i < maxPlank; i++)
{
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Plank Left " + i.ToString() + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(-maxPlank * (plankScale1.X + plankDistance) - plankScale1.Z + plankDistance, 0.0f, i * 2.0f * (plankScale1.X + plankDistance) - maxPlank * (plankScale1.X + plankDistance) + (plankScale1.X + plankDistance));
objectBase.InitLocalTransform.SetScale(plankScale1.Z, plankScale1.Y, plankScale1.X);
objectBase.Integral.SetDensity(1.0f);
}
for (int i = 0; i < maxPlank; i++)
{
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Plank Top " + i.ToString() + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(i * 2.0f * (plankScale1.X + plankDistance) - maxPlank * (plankScale1.X + plankDistance) + (plankScale1.X + plankDistance), plankScale1.Y - plankScale1.Z - plankDistance, 0.0f);
objectBase.InitLocalTransform.SetScale(plankScale1.X, plankScale1.Z, maxPlank * (plankScale1.X + plankDistance) - plankDistance);
objectBase.Integral.SetDensity(1.0f);
}
for (int i = 0; i < maxPlank; i++)
{
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Plank Bottom " + i.ToString() + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(i * 2.0f * (plankScale1.X + plankDistance) - maxPlank * (plankScale1.X + plankDistance) + (plankScale1.X + plankDistance), -plankScale1.Y + plankScale1.Z + plankDistance, 0.0f);
objectBase.InitLocalTransform.SetScale(plankScale1.X, plankScale1.Z, maxPlank * (plankScale1.X + plankDistance) - plankDistance);
objectBase.Integral.SetDensity(1.0f);
}
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Up 1" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(-maxPlank * (plankScale1.X + plankDistance) + plankScale2.X + plankDistance, 0.0f, maxPlank * (plankScale1.X + plankDistance) + plankScale2.Z - plankDistance);
objectBase.InitLocalTransform.SetScale(ref plankScale2);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Up 2" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(maxPlank * (plankScale1.X + plankDistance) - plankScale2.X - plankDistance, 0.0f, maxPlank * (plankScale1.X + plankDistance) + plankScale2.Z - plankDistance);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(180.0f)));
objectBase.InitLocalTransform.SetScale(ref plankScale2);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Up 3" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(0.0f, plankScale1.Y - plankScale2.X, maxPlank * (plankScale1.X + plankDistance) + plankScale2.Z - plankDistance);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(90.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Up 4" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(0.0f, -plankScale1.Y + plankScale2.X, maxPlank * (plankScale1.X + plankDistance) + plankScale2.Z - plankDistance);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(-90.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Down 1" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(-maxPlank * (plankScale1.X + plankDistance) + plankScale2.X + plankDistance, 0.0f, -maxPlank * (plankScale1.X + plankDistance) - plankScale2.Z + plankDistance);
objectBase.InitLocalTransform.SetScale(ref plankScale2);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Down 2" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(maxPlank * (plankScale1.X + plankDistance) - plankScale2.X - plankDistance, 0.0f, -maxPlank * (plankScale1.X + plankDistance) - plankScale2.Z + plankDistance);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(180.0f)));
objectBase.InitLocalTransform.SetScale(ref plankScale2);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Down 3" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(0.0f, plankScale1.Y - plankScale2.X, -maxPlank * (plankScale1.X + plankDistance) - plankScale2.Z + plankDistance);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(90.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Down 4" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(0.0f, -plankScale1.Y + plankScale2.X, -maxPlank * (plankScale1.X + plankDistance) - plankScale2.Z + plankDistance);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(-90.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Top 1" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(-maxPlank * (plankScale1.X + plankDistance) + plankScale2.X + plankDistance, plankScale1.Y + plankScale2.Z, 0.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Top 2" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(maxPlank * (plankScale1.X + plankDistance) - plankScale2.X - plankDistance, plankScale1.Y + plankScale2.Z, 0.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)) * Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(180.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Top 3" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(0.0f, plankScale1.Y + plankScale2.Z, maxPlank * (plankScale1.X + plankDistance) - plankScale2.X - plankDistance);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)) * Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(-90.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Top 4" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(0.0f, plankScale1.Y + plankScale2.Z, -maxPlank * (plankScale1.X + plankDistance) + plankScale2.X + plankDistance);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)) * Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(90.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Bottom 1" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(-maxPlank * (plankScale1.X + plankDistance) + plankScale2.X + plankDistance, -plankScale1.Y - plankScale2.Z, 0.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Bottom 2" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(maxPlank * (plankScale1.X + plankDistance) - plankScale2.X - plankDistance, -plankScale1.Y - plankScale2.Z, 0.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)) * Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(180.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Bottom 3" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(0.0f, -plankScale1.Y - plankScale2.Z, maxPlank * (plankScale1.X + plankDistance) - plankScale2.X - plankDistance);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)) * Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(-90.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Box 2 Convex Plank Bottom 4" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box2Convex1;
objectBase.UserDataStr = "Box2Convex1";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 50.0f;
objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f);
objectBase.CreateSound(true);
objectBase.InitLocalTransform.SetPosition(0.0f, -plankScale1.Y - plankScale2.Z, -maxPlank * (plankScale1.X + plankDistance) + plankScale2.X + plankDistance);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)) * Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(90.0f)));
objectBase.InitLocalTransform.SetScale(plankScale2.X, maxPlank * (plankScale1.X + plankDistance) - plankDistance, plankScale2.Z);
objectBase.Integral.SetDensity(1.0f);
objectRoot.InitLocalTransform.SetOrientation(ref objectOrientation);
objectRoot.InitLocalTransform.SetScale(ref objectScale);
objectRoot.InitLocalTransform.SetPosition(ref objectPosition);
scene.UpdateFromInitLocalTransform(objectRoot);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System
{
public partial class String
{
//
// Search/Query methods
//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool EqualsHelper(string strA, string strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(strA.Length == strB.Length);
return SpanHelpers.SequenceEqual(
ref Unsafe.As<char, byte>(ref strA.GetRawStringData()),
ref Unsafe.As<char, byte>(ref strB.GetRawStringData()),
((nuint)strA.Length) * 2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(indexA >= 0 && indexB >= 0);
Debug.Assert(countA >= 0 && countB >= 0);
Debug.Assert(indexA + countA <= strA.Length && indexB + countB <= strB.Length);
return SpanHelpers.SequenceCompareTo(ref Unsafe.Add(ref strA.GetRawStringData(), indexA), countA, ref Unsafe.Add(ref strB.GetRawStringData(), indexB), countB);
}
private static bool EqualsOrdinalIgnoreCase(string strA, string strB)
{
Debug.Assert(strA.Length == strB.Length);
return CompareInfo.EqualsOrdinalIgnoreCase(ref strA.GetRawStringData(), ref strB.GetRawStringData(), strB.Length);
}
private static unsafe int CompareOrdinalHelper(string strA, string strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
// NOTE: This may be subject to change if eliminating the check
// in the callers makes them small enough to be inlined
Debug.Assert(strA._firstChar == strB._firstChar,
"For performance reasons, callers of this method should " +
"check/short-circuit beforehand if the first char is the same.");
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
// Check if the second chars are different here
// The reason we check if _firstChar is different is because
// it's the most common case and allows us to avoid a method call
// to here.
// The reason we check if the second char is different is because
// if the first two chars the same we can increment by 4 bytes,
// leaving us word-aligned on both 32-bit (12 bytes into the string)
// and 64-bit (16 bytes) platforms.
// For empty strings, the second char will be null due to padding.
// The start of the string is the type pointer + string length, which
// takes up 8 bytes on 32-bit, 12 on x64. For empty strings the null
// terminator immediately follows, leaving us with an object
// 10/14 bytes in size. Since everything needs to be a multiple
// of 4/8, this will get padded and zeroed out.
// For one-char strings the second char will be the null terminator.
// NOTE: If in the future there is a way to read the second char
// without pinning the string (e.g. System.Runtime.CompilerServices.Unsafe
// is exposed to mscorlib, or a future version of C# allows inline IL),
// then do that and short-circuit before the fixed.
if (*(a + 1) != *(b + 1)) goto DiffOffset1;
// Since we know that the first two chars are the same,
// we can increment by 2 here and skip 4 bytes.
// This leaves us 8-byte aligned, which results
// on better perf for 64-bit platforms.
length -= 2; a += 2; b += 2;
// unroll the loop
#if BIT64
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto DiffOffset0;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto DiffOffset4;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto DiffOffset8;
length -= 12; a += 12; b += 12;
}
#else // BIT64
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto DiffOffset0;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto DiffOffset2;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8;
length -= 10; a += 10; b += 10;
}
#endif // BIT64
// Fallback loop:
// go back to slower code path and do comparison on 4 bytes at a time.
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) goto DiffNextInt;
length -= 2;
a += 2;
b += 2;
}
// At this point, we have compared all the characters in at least one string.
// The longer string will be larger.
return strA.Length - strB.Length;
#if BIT64
DiffOffset8: a += 4; b += 4;
DiffOffset4: a += 4; b += 4;
#else // BIT64
// Use jumps instead of falling through, since
// otherwise going to DiffOffset8 will involve
// 8 add instructions before getting to DiffNextInt
DiffOffset8: a += 8; b += 8; goto DiffOffset0;
DiffOffset6: a += 6; b += 6; goto DiffOffset0;
DiffOffset4: a += 2; b += 2;
DiffOffset2: a += 2; b += 2;
#endif // BIT64
DiffOffset0:
// If we reached here, we already see a difference in the unrolled loop above
#if BIT64
if (*(int*)a == *(int*)b)
{
a += 2; b += 2;
}
#endif // BIT64
DiffNextInt:
if (*a != *b) return *a - *b;
DiffOffset1:
Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
return *(a + 1) - *(b + 1);
}
}
// Provides a culture-correct string comparison. StrA is compared to StrB
// to determine whether it is lexicographically less, equal, or greater, and then returns
// either a negative integer, 0, or a positive integer; respectively.
//
public static int Compare(string strA, string strB)
{
return Compare(strA, strB, StringComparison.CurrentCulture);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase
//
public static int Compare(string strA, string strB, bool ignoreCase)
{
var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
return Compare(strA, strB, comparisonType);
}
// Provides a more flexible function for string comparison. See StringComparison
// for meaning of different comparisonType.
public static int Compare(string strA, string strB, StringComparison comparisonType)
{
if (object.ReferenceEquals(strA, strB))
{
CheckStringComparison(comparisonType);
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
CheckStringComparison(comparisonType);
return -1;
}
if (strB == null)
{
CheckStringComparison(comparisonType);
return 1;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.Compare(strA, strB, GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.Ordinal:
// Most common case: first character is different.
// Returns false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
case StringComparison.OrdinalIgnoreCase:
return CompareInfo.CompareOrdinalIgnoreCase(strA, strB);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
//
public static int Compare(string strA, string strB, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
return culture.CompareInfo.Compare(strA, strB, options);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase, and the culture is set
// by culture
//
public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo culture)
{
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, strB, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of given length is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(string strA, int indexA, string strB, int indexB, int length)
{
// NOTE: It's important we call the boolean overload, and not the StringComparison
// one. The two have some subtly different behavior (see notes in the former).
return Compare(strA, indexA, strB, indexB, length, ignoreCase: false);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of given length is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean.
//
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase)
{
// Ideally we would just forward to the string.Compare overload that takes
// a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase.
// That function will return early if an optimization can be applied, e.g. if
// (object)strA == strB && indexA == indexB then it will return 0 straightaway.
// There are a couple of subtle behavior differences that prevent us from doing so
// however:
// - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works
// since that method also returns early for nulls before validation. It shouldn't
// for this overload.
// - Since we originally forwarded to CompareInfo.Compare for all of the argument
// validation logic, the ArgumentOutOfRangeExceptions thrown will contain different
// parameter names.
// Therefore, we have to duplicate some of the logic here.
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean,
// and the culture is set by culture.
//
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo culture)
{
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, indexA, strB, indexB, length, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(string strA, int indexA, string strB, int indexB, int length, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
return culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType)
{
CheckStringComparison(comparisonType);
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
{
string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.Compare(strA, indexA, lengthA, strB, indexB, lengthB, GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.Ordinal:
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
default:
Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase); // CheckStringComparison validated these earlier
return CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB);
}
}
// Compares strA and strB using an ordinal (code-point) comparison.
//
public static int CompareOrdinal(string strA, string strB)
{
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
// Most common case, first character is different.
// This will return false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int CompareOrdinal(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
=> SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(strA), strA.Length, ref MemoryMarshal.GetReference(strB), strB.Length);
// Compares strA and strB using an ordinal (code-point) comparison.
//
public static int CompareOrdinal(string strA, int indexA, string strB, int indexB, int length)
{
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
// COMPAT: Checking for nulls should become before the arguments are validated,
// but other optimizations which allow us to return early should come after.
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeCount);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
if (lengthA < 0 || lengthB < 0)
{
string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
}
// Compares this String to another String (cast as object), returning an integer that
// indicates the relationship. This method returns a value less than 0 if this is less than value, 0
// if this is equal to value, or a value greater than 0 if this is greater than value.
//
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
if (!(value is string other))
{
throw new ArgumentException(SR.Arg_MustBeString);
}
return CompareTo(other); // will call the string-based overload
}
// Determines the sorting relation of StrB to the current instance.
//
public int CompareTo(string strB)
{
return string.Compare(this, strB, StringComparison.CurrentCulture);
}
// Determines whether a specified string is a suffix of the current instance.
//
// The case-sensitive and culture-sensitive option is set by options,
// and the default culture is used.
//
public bool EndsWith(string value)
{
return EndsWith(value, StringComparison.CurrentCulture);
}
public bool EndsWith(string value, StringComparison comparisonType)
{
if ((object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
CheckStringComparison(comparisonType);
return true;
}
if (value.Length == 0)
{
CheckStringComparison(comparisonType);
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IsSuffix(this, value, GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.Ordinal:
int offset = this.Length - value.Length;
return (uint)offset <= (uint)this.Length && this.AsSpan(offset).SequenceEqual(value);
case StringComparison.OrdinalIgnoreCase:
return this.Length < value.Length ? false : (CompareInfo.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public bool EndsWith(string value, bool ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture;
return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public bool EndsWith(char value)
{
int lastPos = Length - 1;
return ((uint)lastPos < (uint)Length) && this[lastPos] == value;
}
// Determines whether two strings match.
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
if (!(obj is string str))
return false;
if (this.Length != str.Length)
return false;
return EqualsHelper(this, str);
}
// Determines whether two strings match.
public bool Equals(string value)
{
if (object.ReferenceEquals(this, value))
return true;
// NOTE: No need to worry about casting to object here.
// If either side of an == comparison between strings
// is null, Roslyn generates a simple ceq instruction
// instead of calling string.op_Equality.
if (value == null)
return false;
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
}
public bool Equals(string value, StringComparison comparisonType)
{
if ((object)this == (object)value)
{
CheckStringComparison(comparisonType);
return true;
}
if ((object)value == null)
{
CheckStringComparison(comparisonType);
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, GetCaseCompareOfComparisonCulture(comparisonType)) == 0);
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return (CompareInfo.Invariant.Compare(this, value, GetCaseCompareOfComparisonCulture(comparisonType)) == 0);
case StringComparison.Ordinal:
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length != value.Length)
return false;
return EqualsOrdinalIgnoreCase(this, value);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Determines whether two Strings match.
public static bool Equals(string a, string b)
{
if ((object)a == (object)b)
{
return true;
}
if ((object)a == null || (object)b == null || a.Length != b.Length)
{
return false;
}
return EqualsHelper(a, b);
}
public static bool Equals(string a, string b, StringComparison comparisonType)
{
if ((object)a == (object)b)
{
CheckStringComparison(comparisonType);
return true;
}
if ((object)a == null || (object)b == null)
{
CheckStringComparison(comparisonType);
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, GetCaseCompareOfComparisonCulture(comparisonType)) == 0);
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return (CompareInfo.Invariant.Compare(a, b, GetCaseCompareOfComparisonCulture(comparisonType)) == 0);
case StringComparison.Ordinal:
if (a.Length != b.Length)
return false;
return EqualsHelper(a, b);
case StringComparison.OrdinalIgnoreCase:
if (a.Length != b.Length)
return false;
return EqualsOrdinalIgnoreCase(a, b);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public static bool operator ==(string a, string b)
{
return string.Equals(a, b);
}
public static bool operator !=(string a, string b)
{
return !string.Equals(a, b);
}
// Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
// they will return the same hash code.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
ulong seed = Marvin.DefaultSeed;
return Marvin.ComputeHash32(ref Unsafe.As<char, byte>(ref _firstChar), _stringLength * 2 /* in bytes, not chars */, (uint)seed, (uint)(seed >> 32));
}
// Gets a hash code for this string and this comparison. If strings A and B and comparison C are such
// that string.Equals(A, B, C), then they will return the same hash code with this comparison C.
public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal int GetHashCodeOrdinalIgnoreCase()
{
ulong seed = Marvin.DefaultSeed;
return Marvin.ComputeHash32OrdinalIgnoreCase(ref _firstChar, _stringLength /* in chars, not bytes */, (uint)seed, (uint)(seed >> 32));
}
// A span-based equivalent of String.GetHashCode(). Computes an ordinal hash code.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetHashCode(ReadOnlySpan<char> value)
{
ulong seed = Marvin.DefaultSeed;
return Marvin.ComputeHash32(ref Unsafe.As<char, byte>(ref MemoryMarshal.GetReference(value)), value.Length * 2 /* in bytes, not chars */, (uint)seed, (uint)(seed >> 32));
}
// A span-based equivalent of String.GetHashCode(StringComparison). Uses the specified comparison type.
public static int GetHashCode(ReadOnlySpan<char> value, StringComparison comparisonType)
{
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.GetHashCode(value, GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.GetHashCode(value, GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.Ordinal:
return GetHashCode(value);
case StringComparison.OrdinalIgnoreCase:
return GetHashCodeOrdinalIgnoreCase(value);
default:
ThrowHelper.ThrowArgumentException(ExceptionResource.NotSupported_StringComparison, ExceptionArgument.comparisonType);
Debug.Fail("Should not reach this point.");
return default;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int GetHashCodeOrdinalIgnoreCase(ReadOnlySpan<char> value)
{
ulong seed = Marvin.DefaultSeed;
return Marvin.ComputeHash32OrdinalIgnoreCase(ref MemoryMarshal.GetReference(value), value.Length /* in chars, not bytes */, (uint)seed, (uint)(seed >> 32));
}
// Use this if and only if 'Denial of Service' attacks are not a concern (i.e. never used for free-form user input),
// or are otherwise mitigated
internal unsafe int GetNonRandomizedHashCode()
{
fixed (char* src = &_firstChar)
{
Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary");
uint hash1 = (5381 << 16) + 5381;
uint hash2 = hash1;
uint* ptr = (uint*)src;
int length = this.Length;
while (length > 2)
{
length -= 4;
// Where length is 4n-1 (e.g. 3,7,11,15,19) this additionally consumes the null terminator
hash1 = (BitOperations.RotateLeft(hash1, 5) + hash1) ^ ptr[0];
hash2 = (BitOperations.RotateLeft(hash2, 5) + hash2) ^ ptr[1];
ptr += 2;
}
if (length > 0)
{
// Where length is 4n-3 (e.g. 1,5,9,13,17) this additionally consumes the null terminator
hash2 = (BitOperations.RotateLeft(hash2, 5) + hash2) ^ ptr[0];
}
return (int)(hash1 + (hash2 * 1566083941));
}
}
// Determines whether a specified string is a prefix of the current instance
//
public bool StartsWith(string value)
{
if ((object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
return StartsWith(value, StringComparison.CurrentCulture);
}
public bool StartsWith(string value, StringComparison comparisonType)
{
if ((object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
CheckStringComparison(comparisonType);
return true;
}
if (value.Length == 0)
{
CheckStringComparison(comparisonType);
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IsPrefix(this, value, GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.Ordinal:
if (this.Length < value.Length || _firstChar != value._firstChar)
{
return false;
}
return (value.Length == 1) ?
true : // First char is the same and thats all there is to compare
SpanHelpers.SequenceEqual(
ref Unsafe.As<char, byte>(ref this.GetRawStringData()),
ref Unsafe.As<char, byte>(ref value.GetRawStringData()),
((nuint)value.Length) * 2);
case StringComparison.OrdinalIgnoreCase:
if (this.Length < value.Length)
{
return false;
}
return CompareInfo.EqualsOrdinalIgnoreCase(ref this.GetRawStringData(), ref value.GetRawStringData(), value.Length);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public bool StartsWith(string value, bool ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture;
return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public bool StartsWith(char value) => Length != 0 && _firstChar == value;
internal static void CheckStringComparison(StringComparison comparisonType)
{
// Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase]
if ((uint)comparisonType > (uint)StringComparison.OrdinalIgnoreCase)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.NotSupported_StringComparison, ExceptionArgument.comparisonType);
}
}
internal static CompareOptions GetCaseCompareOfComparisonCulture(StringComparison comparisonType)
{
Debug.Assert((uint)comparisonType <= (uint)StringComparison.OrdinalIgnoreCase);
// Culture enums can be & with CompareOptions.IgnoreCase 0x01 to extract if IgnoreCase or CompareOptions.None 0x00
//
// CompareOptions.None 0x00
// CompareOptions.IgnoreCase 0x01
//
// StringComparison.CurrentCulture: 0x00
// StringComparison.InvariantCulture: 0x02
// StringComparison.Ordinal 0x04
//
// StringComparison.CurrentCultureIgnoreCase: 0x01
// StringComparison.InvariantCultureIgnoreCase: 0x03
// StringComparison.OrdinalIgnoreCase 0x05
return (CompareOptions)((int)comparisonType & (int)CompareOptions.IgnoreCase);
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedGlobalNetworkEndpointGroupsClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<GlobalNetworkEndpointGroups.GlobalNetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<GlobalNetworkEndpointGroups.GlobalNetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGlobalNetworkEndpointGroupRequest request = new GetGlobalNetworkEndpointGroupRequest
{
Project = "projectaa6ff846",
NetworkEndpointGroup = "network_endpoint_groupdf1fb34e",
};
NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
CloudRun = new NetworkEndpointGroupCloudRun(),
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
NetworkEndpointType = NetworkEndpointGroup.Types.NetworkEndpointType.InternetFqdnPort,
Region = "regionedb20d96",
Network = "networkd22ce091",
Subnetwork = "subnetworkf55bf572",
AppEngine = new NetworkEndpointGroupAppEngine(),
Description = "description2cf9da67",
DefaultPort = 4850952,
SelfLink = "self_link7e87f12d",
CloudFunction = new NetworkEndpointGroupCloudFunction(),
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GlobalNetworkEndpointGroupsClient client = new GlobalNetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
NetworkEndpointGroup response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<GlobalNetworkEndpointGroups.GlobalNetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<GlobalNetworkEndpointGroups.GlobalNetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGlobalNetworkEndpointGroupRequest request = new GetGlobalNetworkEndpointGroupRequest
{
Project = "projectaa6ff846",
NetworkEndpointGroup = "network_endpoint_groupdf1fb34e",
};
NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
CloudRun = new NetworkEndpointGroupCloudRun(),
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
NetworkEndpointType = NetworkEndpointGroup.Types.NetworkEndpointType.InternetFqdnPort,
Region = "regionedb20d96",
Network = "networkd22ce091",
Subnetwork = "subnetworkf55bf572",
AppEngine = new NetworkEndpointGroupAppEngine(),
Description = "description2cf9da67",
DefaultPort = 4850952,
SelfLink = "self_link7e87f12d",
CloudFunction = new NetworkEndpointGroupCloudFunction(),
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NetworkEndpointGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GlobalNetworkEndpointGroupsClient client = new GlobalNetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
NetworkEndpointGroup responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
NetworkEndpointGroup responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<GlobalNetworkEndpointGroups.GlobalNetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<GlobalNetworkEndpointGroups.GlobalNetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGlobalNetworkEndpointGroupRequest request = new GetGlobalNetworkEndpointGroupRequest
{
Project = "projectaa6ff846",
NetworkEndpointGroup = "network_endpoint_groupdf1fb34e",
};
NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
CloudRun = new NetworkEndpointGroupCloudRun(),
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
NetworkEndpointType = NetworkEndpointGroup.Types.NetworkEndpointType.InternetFqdnPort,
Region = "regionedb20d96",
Network = "networkd22ce091",
Subnetwork = "subnetworkf55bf572",
AppEngine = new NetworkEndpointGroupAppEngine(),
Description = "description2cf9da67",
DefaultPort = 4850952,
SelfLink = "self_link7e87f12d",
CloudFunction = new NetworkEndpointGroupCloudFunction(),
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GlobalNetworkEndpointGroupsClient client = new GlobalNetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
NetworkEndpointGroup response = client.Get(request.Project, request.NetworkEndpointGroup);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<GlobalNetworkEndpointGroups.GlobalNetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<GlobalNetworkEndpointGroups.GlobalNetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGlobalNetworkEndpointGroupRequest request = new GetGlobalNetworkEndpointGroupRequest
{
Project = "projectaa6ff846",
NetworkEndpointGroup = "network_endpoint_groupdf1fb34e",
};
NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
CloudRun = new NetworkEndpointGroupCloudRun(),
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
NetworkEndpointType = NetworkEndpointGroup.Types.NetworkEndpointType.InternetFqdnPort,
Region = "regionedb20d96",
Network = "networkd22ce091",
Subnetwork = "subnetworkf55bf572",
AppEngine = new NetworkEndpointGroupAppEngine(),
Description = "description2cf9da67",
DefaultPort = 4850952,
SelfLink = "self_link7e87f12d",
CloudFunction = new NetworkEndpointGroupCloudFunction(),
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NetworkEndpointGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GlobalNetworkEndpointGroupsClient client = new GlobalNetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
NetworkEndpointGroup responseCallSettings = await client.GetAsync(request.Project, request.NetworkEndpointGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
NetworkEndpointGroup responseCancellationToken = await client.GetAsync(request.Project, request.NetworkEndpointGroup, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace AdvUtils
{
/// <typeparam name="T">T must be comparable.</typeparam>
public class FixedSizePriorityQueue<T> : IEnumerable<T>
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="capacity">Fix the heap size at this capacity.</param>
public FixedSizePriorityQueue(int capacity)
{
if (capacity < 1)
throw new Exception("priority queue capacity must be at least one!");
m_iCount = 0;
m_iCapacity = capacity;
m_iBottomSize = m_iTopSize = 0;
int iBottomCapacity = Math.Max(capacity / 2, 1);
int iTopCapacity = Math.Max(capacity - iBottomCapacity, 1);
m_rgtTop = new T[iTopCapacity];
m_rgtBottom = new T[iBottomCapacity];
}
public FixedSizePriorityQueue(int cap, IComparer<T> comp)
: this(cap)
{
comparer = comp;
}
#region Basic prio-queue operations.
/// <summary>
/// Get the number of elements currently in the queue.
/// </summary>
public int Count { get { return m_iCount; } }
/// <summary>
/// Get the number of elements that could possibly be held in the queue
/// </summary>
public int Capacity { get { return m_iCapacity; } }
public void Clear()
{
m_iCount = 0;
m_rgtBottom.Initialize();
m_rgtTop.Initialize();
m_iTopSize = m_iBottomSize = 0;
}
public bool Enqueue(T t)
{
// first, are we already at capacity?
if (m_iCapacity == m_iCount)
{
if (m_iCapacity == 1)
{
//We only have a single item in the queue and it's kept in m_rgtTop.
if (!Better(t, m_rgtTop[0], true))
{
return false;
}
else
{
m_rgtTop[0] = t;
return true;
}
}
// then, are we better than the bottom?
if (!Better(t, m_rgtBottom[0], true))
{
// nope, bail.
return false;
}
// yep, put in place...
m_rgtBottom[0] = t;
// first heapfiy the bottom half; get back the
// index where it ended up.
int iUpdated = DownHeapify(m_rgtBottom, 0, m_iBottomSize, false);
// are we not at the boundary? Then we're done.
if (!SemiLeaf(iUpdated, m_iBottomSize)) return true;
// at the boundary: check if we need to update.
int iTop = CheckBoundaryUpwards(iUpdated);
// boundary is okay? bail.
if (iTop == -1) return true;
// ...and fix the top heap property.
UpHeapify(m_rgtTop, iTop, m_iTopSize, true);
return true;
}
// we have space to insert.
++m_iCount;
// need to maintain the invariant that either size(bottom) == size(top),
// or size(bottom) + 1 == size(top).
if (m_iBottomSize < m_iTopSize)
{
Debug.Assert(m_iBottomSize + 1 == m_iTopSize);
// bottom is smaller: put it there.
int iPos = m_iBottomSize++;
m_rgtBottom[iPos] = t;
// see if it should really end up in the top heap...
int iUp = CheckBoundaryUpwards(iPos);
if (iUp == -1)
{
// no -- fix the bottom yep.
UpHeapify(m_rgtBottom, iPos, m_iBottomSize, false);
}
else
{
// yes -- fix the top heap.
UpHeapify(m_rgtTop, iUp, m_iTopSize, true);
}
return true;
}
else
{
Debug.Assert(m_iBottomSize == m_iTopSize);
// put it in the top.
int iPos = m_iTopSize++;
m_rgtTop[iPos] = t;
// see if it should really end up in the bottom.
int iBottom = CheckBoundaryDownwards(iPos);
if (iBottom == -1)
{
// no -- fix the top heap.
UpHeapify(m_rgtTop, iPos, m_iTopSize, true);
}
else
{
// yes -- fix the bottotm.
UpHeapify(m_rgtBottom, iBottom, m_iBottomSize, false);
}
return true;
}
}
#endregion
#region Heap navigators
int Parent(int i) { return (i - 1) / 2; }
int Left(int i) { return 2 * i + 1; }
int Right(int i) { return 2 * i + 2; }
bool IsLeft(int i) { return i % 2 == 1; }
bool IsRight(int i) { return i % 2 == 0; }
bool Leaf(int i, int iSize) { return Left(i) >= iSize; }
bool SemiLeaf(int i, int iSize) { return Right(i) >= iSize; }
int BottomNode(int i)
{
// first see if we have a direct correspondence.
if (i < m_iBottomSize) return i;
// no parallel -- must be that one extra element
// in the target heap. instead point at the parent
// if a left node, or left sibling if a right node.
Debug.Assert(i <= m_iBottomSize);
if (i % 2 == 1) return Parent(i);
return i - 1;
}
int TopNode1(int i)
{
if (Left(i) >= m_iBottomSize && Left(i) < m_iTopSize) return Left(i);
// top is always >= bottom in size,
// so this element is guaranteed to exist.
return i;
}
int TopNode2(int i)
{
if (i == m_iBottomSize - 1 &&
1 == (i % 2) &&
m_iTopSize > m_iBottomSize)
{
return i + 1;
}
if (Left(i) >= m_iBottomSize && Left(i) < m_iTopSize) return Left(i);
return i;
}
#endregion
#region Heap invariant maintenance
int UpHeapify(T[] rgt, int i, int iSize, bool fTop)
{
while (i > 0)
{
int iPar = Parent(i);
if (!Better(rgt[i], rgt[iPar], fTop)) return i;
Swap(rgt, i, rgt, iPar);
i = iPar;
}
return i;
}
int DownHeapify(T[] rgt, int i, int iSize, bool fTop)
{
while (true)
{
int iLeft = Left(i), iRight = Right(i);
int iLargest = i;
if (iLeft < iSize && Better(rgt[iLeft], rgt[iLargest], fTop)) iLargest = iLeft;
if (iRight < iSize && Better(rgt[iRight], rgt[iLargest], fTop)) iLargest = iRight;
if (iLargest == i) return i;
Swap(rgt, i, rgt, iLargest);
i = iLargest;
}
}
int CheckBoundaryUpwards(int iBottomPos)
{
int iTop1 = TopNode1(iBottomPos);
int iTop2 = TopNode2(iBottomPos);
int iBetter = -1;
if (Better(m_rgtBottom[iBottomPos], m_rgtTop[iTop1], true))
{
iBetter = iTop1;
}
if (Better(m_rgtBottom[iBottomPos], m_rgtTop[iTop2], true) &&
(iBetter == -1 || Better(m_rgtTop[iTop1], m_rgtTop[iTop2], true)))
{
iBetter = iTop2;
}
if (iBetter == -1)
{
return -1;
}
// boundary is not okay? move this guy across...
Swap(m_rgtTop, iBetter, m_rgtBottom, iBottomPos);
return iBetter;
}
int CheckBoundaryDownwards(int iTopPos)
{
// compare to the bottom guy in the corresponding posn.
int iBottomPos = BottomNode(iTopPos);
if (iBottomPos == -1)
{
return -1;
}
if (iBottomPos >= m_iBottomSize ||
!Better(m_rgtBottom[iBottomPos], m_rgtTop[iTopPos], true))
{
return -1;
}
Swap(m_rgtTop, iTopPos, m_rgtBottom, iBottomPos);
return iBottomPos;
}
void Swap(T[] rgt1, int i1, T[] rgt2, int i2)
{
T tTemp = rgt1[i1];
rgt1[i1] = rgt2[i2];
rgt2[i2] = tTemp;
}
protected bool Better(T t1, T t2, bool fTop)
{
int i = (comparer == null) ? ((IComparable<T>)t1).CompareTo(t2) : comparer.Compare(t1, t2);
//int i = comparer.Compare(t1, t2);
return (!fTop) ? i < 0 : i > 0;
}
#endregion
#region Data structures
/// <summary>
/// The downward facing heap.
/// </summary>
protected T[] m_rgtBottom;
/// <summary>
/// Upward facing heap.
/// </summary>
protected T[] m_rgtTop;
/// <summary>
/// Total number of elements in the heap.
/// </summary>
protected int m_iCount;
/// <summary>
/// Capacity of the heap.
/// </summary>
protected int m_iCapacity;
/// <summary>
/// Number of nodes in the bottom heap.
/// </summary>
protected int m_iBottomSize;
/// <summary>
/// Number of nodes in the top heap.
/// </summary>
protected int m_iTopSize;
#endregion
protected IComparer<T> comparer = null;
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < m_iTopSize; ++i)
yield return m_rgtTop[i];
for (int i = m_iBottomSize - 1; i >= 0; --i)
yield return m_rgtBottom[i];
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CollectionResolver.cs" company="KlusterKite">
// All rights reserved
// </copyright>
// <summary>
// Resolves requests to the object collection
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace KlusterKite.API.Provider.Resolvers
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using KlusterKite.API.Attributes;
using KlusterKite.API.Attributes.Authorization;
using KlusterKite.API.Client;
using KlusterKite.Security.Attributes;
using KlusterKite.Security.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// Resolves requests to the object collection
/// </summary>
/// <typeparam name="T">The type of node</typeparam>
/// <remarks>
/// <see cref="CollectionResolver{T}"/> uses <see cref="ObjectResolver{T}"/> in it's static initialization.
/// So <see cref="ObjectResolver{T}"/> cannot use <see cref="CollectionResolver{T}"/> in it's static initialization to avoid deadlock
/// </remarks>
[SuppressMessage("ReSharper", "StaticMemberInGenericType",
Justification = "Making use of static properties in generic classes")]
internal class CollectionResolver<T> : IResolver
where T : class
{
/// <summary>
/// The initialization lock to make it thread-safe
/// </summary>
protected static readonly object LockObject = new object();
/// <summary>
/// The filter checks pre-created expressions
/// </summary>
private static readonly Dictionary<string, Func<JProperty, Expression>> FilterChecks =
new Dictionary<string, Func<JProperty, Expression>>();
/// <summary>
/// The filter checks pre-created expressions
/// </summary>
private static readonly ParameterExpression FilterSourceParameter = Expression.Parameter(typeof(T));
/// <summary>
/// The available sorting conditions
/// </summary>
private static readonly Dictionary<string, SortingCondition> SortingConditions =
new Dictionary<string, SortingCondition>();
/// <summary>
/// A value indicating whether the type initialization process was completed
/// </summary>
private static bool isInitialized;
/// <summary>
/// Initializes static members of the <see cref="CollectionResolver{T}"/> class.
/// </summary>
static CollectionResolver()
{
FilterType = new ApiObjectType($"{ApiDescriptionAttribute.GetTypeName(typeof(T))}_Filter");
SortType = new ApiEnumType($"{ApiDescriptionAttribute.GetTypeName(typeof(T))}_Sort");
var param = Expression.Parameter(typeof(T));
GetIdValue =
Expression.Lambda<Func<T, object>>(
Expression.Convert(Expression.Property(param, NodeMetaData.KeyProperty), typeof(object)),
param).Compile();
InitializeType();
}
/// <summary>
/// Initializes a new instance of the <see cref="CollectionResolver{T}"/> class.
/// </summary>
public CollectionResolver()
{
if (NodeMetaData.ScalarType == EnScalarType.None)
{
this.NodeResolver = new ObjectResolver<T>();
}
else
{
this.NodeResolver = new ScalarResolver<T>();
}
}
/// <summary>
/// Gets the type to describe the collection filter argument
/// </summary>
public static ApiObjectType FilterType { get; }
/// <summary>
/// Gets a function to get id value from entity
/// </summary>
public static Func<T, object> GetIdValue { get; }
/// <summary>
/// Gets the type to describe the collection sort argument element
/// </summary>
public static ApiEnumType SortType { get; }
/// <inheritdoc />
public IResolver NodeResolver { get; }
/// <summary>
/// Gets the node metadata
/// </summary>
protected static TypeMetadata NodeMetaData { get; } = TypeMetadata.GenerateTypeMetadata(
typeof(T),
new DeclareFieldAttribute());
/// <summary>
/// Gets the generated arguments
/// </summary>
/// <returns>The list of arguments</returns>
public static IEnumerable<ApiField> GetArguments()
{
if (FilterType.Fields.Count > 2)
{
yield return
FilterType.CreateField(
"filter",
EnFieldFlags.CanBeUsedInInput | EnFieldFlags.Queryable | EnFieldFlags.IsTypeArgument);
}
if (SortType.Values.Any())
{
const EnFieldFlags SortFlags =
EnFieldFlags.CanBeUsedInInput | EnFieldFlags.Queryable | EnFieldFlags.IsTypeArgument
| EnFieldFlags.IsArray;
yield return ApiField.Object("sort", SortType.TypeName, SortFlags);
}
if (NodeMetaData.KeyProperty != null)
{
var keyMetadata = TypeMetadata.GenerateTypeMetadata(
NodeMetaData.KeyProperty.PropertyType,
NodeMetaData.KeyProperty.GetCustomAttribute<PublishToApiAttribute>());
if (keyMetadata.ScalarType != EnScalarType.None)
{
yield return
ApiField.Scalar(
"id",
keyMetadata.ScalarType,
EnFieldFlags.CanBeUsedInInput | EnFieldFlags.Queryable | EnFieldFlags.IsTypeArgument);
}
}
yield return
ApiField.Scalar(
"limit",
EnScalarType.Integer,
EnFieldFlags.CanBeUsedInInput | EnFieldFlags.Queryable | EnFieldFlags.IsTypeArgument);
yield return
ApiField.Scalar(
"offset",
EnScalarType.Integer,
EnFieldFlags.CanBeUsedInInput | EnFieldFlags.Queryable | EnFieldFlags.IsTypeArgument);
}
/// <inheritdoc />
public ApiType GetElementType()
{
return NodeMetaData.ScalarType == EnScalarType.None ? ObjectResolver<T>.GeneratedType : null;
}
/// <inheritdoc />
public IEnumerable<ApiField> GetTypeArguments()
{
return GetArguments();
}
/// <inheritdoc />
public async Task<JToken> ResolveQuery(
object source,
ApiRequest request,
ApiField apiField,
RequestContext context,
JsonSerializer argumentsSerializer,
Action<Exception> onErrorCallback)
{
var arguments = (JObject)request.Arguments;
var id = arguments?.Property("id");
var filterArgument = arguments?.Property("filter")?.Value as JObject;
var sortArgument = arguments?.Property("sort")?.Value as JArray;
var limit = (int?)(arguments?.Property("limit")?.Value as JValue);
var offset = (int?)(arguments?.Property("offset")?.Value as JValue);
var filter = CreateFilter(filterArgument, id);
var sort = sortArgument != null ? this.CreateSort(sortArgument) : null;
var items = await this.GetQueryResult(source, request, filter, sort, limit, offset);
if (items == null)
{
onErrorCallback?.Invoke(new Exception("Source is not a node connection"));
return JValue.CreateNull();
}
SetLog(request, apiField, context, EnConnectionAction.Query);
var result = new JObject();
var fields = request.Fields.GroupBy(f => f.Alias ?? f.FieldName).Select(
g =>
{
var f = g.First();
if (f.Fields == null)
{
return f;
}
return new ApiRequest
{
Alias = f.Alias,
Arguments = f.Arguments,
FieldName = f.FieldName,
Fields = g.SelectMany(sr => sr.Fields).ToList()
};
});
foreach (var requestField in fields)
{
switch (requestField.FieldName)
{
case "count":
result.Add(requestField.Alias ?? requestField.FieldName, new JValue(items.Count));
break;
case "items":
{
var itemsValue =
await new SimpleCollectionResolver(this.NodeResolver).ResolveQuery(
items.Items,
requestField,
apiField,
context,
argumentsSerializer,
onErrorCallback);
result.Add(requestField.Alias ?? requestField.FieldName, itemsValue);
}
break;
}
}
return result;
}
/// <summary>
/// Sets the operation log
/// </summary>
/// <param name="request">
/// The initial request
/// </param>
/// <param name="apiField">
/// The connection field
/// </param>
/// <param name="context">
/// The request context
/// </param>
/// <param name="action">
/// The action performed
/// </param>
protected static void SetLog(
ApiRequest request,
ApiField apiField,
RequestContext context,
EnConnectionAction action)
{
if (apiField.LogAccessRules == null || !apiField.LogAccessRules.Any())
{
return;
}
var rule =
apiField.LogAccessRules.OrderByDescending(r => r.Severity)
.FirstOrDefault(r => r.ConnectionActions.HasFlag(action));
if (rule == null)
{
return;
}
var operationGranted = EnSecurityLogType.OperationGranted;
switch (action)
{
case EnConnectionAction.Create:
operationGranted = EnSecurityLogType.DataCreateGranted;
break;
case EnConnectionAction.Update:
operationGranted = EnSecurityLogType.DataUpdateGranted;
break;
case EnConnectionAction.Delete:
operationGranted = EnSecurityLogType.DataDeleteGranted;
break;
}
SecurityLog.CreateRecord(
operationGranted,
rule.Severity,
context,
rule.LogMessage,
((JObject)request.Arguments).ToString(Formatting.None));
}
/// <summary>
/// Getting the query result
/// </summary>
/// <param name="source">The data source</param>
/// <param name="request">The original request</param>
/// <param name="filter">Filtering expression</param>
/// <param name="sort">Sorting expression</param>
/// <param name="limit">The maximum number of elements</param>
/// <param name="offset">The number of the first element</param>
/// <returns>The query result</returns>
protected virtual Task<QueryResult<T>> GetQueryResult(
object source,
ApiRequest request,
Expression<Func<T, bool>> filter,
IEnumerable<SortingCondition> sort,
int? limit,
int? offset)
{
var queryable = source as IQueryable<T> ?? (source as IEnumerable<T>)?.AsQueryable();
if (queryable == null)
{
return null;
}
if (filter != null)
{
queryable = queryable.Where(filter);
}
var result = new QueryResult<T> { Count = queryable.Count() };
if (sort != null)
{
queryable = queryable.ApplySorting(sort);
}
if (offset.HasValue)
{
queryable = queryable.Skip(offset.Value);
}
if (limit.HasValue)
{
queryable = queryable.Take(limit.Value);
}
result.Items = queryable;
return Task.FromResult(result);
}
/// <summary>
/// Adds a new filter condition
/// </summary>
/// <param name="name">The name of condition</param>
/// <param name="expression">The expression generator</param>
/// <param name="field">The field to check</param>
/// <param name="description">The filter description</param>
private static void AddFilterExpression(
string name,
Func<JProperty, Expression> expression,
ApiField field,
string description)
{
FilterChecks[name] = expression;
description = string.Format(description, field.Name);
var filterDescription = !string.IsNullOrWhiteSpace(field.Description)
? $"{description}, {field.Name}: {field.Description}"
: description;
if (field.ScalarType != EnScalarType.None)
{
FilterType.Fields.Add(
ApiField.Scalar(
name,
field.ScalarType,
EnFieldFlags.Queryable | EnFieldFlags.CanBeUsedInInput,
description: filterDescription));
}
else
{
FilterType.Fields.Add(
ApiField.Object(
name,
field.TypeName,
EnFieldFlags.Queryable | EnFieldFlags.CanBeUsedInInput,
description: filterDescription));
}
}
/// <summary>
/// Creates filter expression by filter request
/// </summary>
/// <param name="filter">The filter request</param>
/// <param name="id">The id argument</param>
/// <returns>The filter expression</returns>
private static Expression<Func<T, bool>> CreateFilter(JObject filter, JProperty id)
{
var filterCheck = filter != null ? CreateFilterPart(filter) : null;
var idCheck = id != null ? FilterChecks[NodeMetaData.KeyPropertyName](id) : null;
var check = filterCheck != null && idCheck != null
? Expression.And(filterCheck, idCheck)
: filterCheck ?? idCheck;
return check == null
? null
: Expression.Lambda<Func<T, bool>>(check, FilterSourceParameter);
}
/// <summary>
/// Creates part of of filter expression according to json description
/// </summary>
/// <param name="filterProperty">The filter json description</param>
/// <returns>The expression</returns>
private static Expression CreateFilterPart(JObject filterProperty)
{
Expression left = Expression.Constant(true);
foreach (var prop in filterProperty.Properties())
{
Func<JProperty, Expression> check;
if (FilterChecks.TryGetValue(prop.Name, out check))
{
left = Expression.And(left, check(prop));
}
}
return left;
}
/// <summary>
/// Performs final type initialization
/// </summary>
private static void InitializeType()
{
if (isInitialized)
{
return;
}
lock (LockObject)
{
if (isInitialized)
{
return;
}
isInitialized = true;
var nodeType = ObjectResolver<T>.GeneratedType;
var realFields = ObjectResolver<T>.DeclaredFields;
var sortableFields = nodeType.Fields.Where(f => f.Flags.HasFlag(EnFieldFlags.IsSortable));
foreach (var sortableField in sortableFields)
{
SortingConditions[$"{sortableField.Name}_asc"] =
new SortingCondition(realFields[sortableField.Name].Name, SortingCondition.EnDirection.Asc);
SortingConditions[$"{sortableField.Name}_desc"] =
new SortingCondition(realFields[sortableField.Name].Name, SortingCondition.EnDirection.Desc);
}
SortType.Values.AddRange(SortingConditions.Keys);
FilterChecks["OR"] = prop =>
{
var subFilters = prop.Value as JArray;
if (subFilters == null)
{
return Expression.Constant(true);
}
Expression or = Expression.Constant(false);
or = subFilters.Children()
.OfType<JObject>()
.Aggregate(or, (current, subFilter) => Expression.Or(current, CreateFilterPart(subFilter)));
return or;
};
FilterType.Fields.Add(
FilterType.CreateField(
"OR",
description: "Combine filter conditions with logic \"OR\"",
flags: EnFieldFlags.Queryable | EnFieldFlags.CanBeUsedInInput));
FilterChecks["AND"] = prop =>
{
var subFilters = prop.Value as JArray;
if (subFilters == null)
{
return Expression.Constant(true);
}
Expression and = Expression.Constant(true);
and = subFilters.Children()
.OfType<JObject>()
.Aggregate(
and,
(current, subFilter) => Expression.And(current, CreateFilterPart(subFilter)));
return and;
};
FilterType.Fields.Add(
FilterType.CreateField(
"AND",
description: "Combine filter conditions with logic \"AND\"",
flags: EnFieldFlags.Queryable | EnFieldFlags.CanBeUsedInInput));
var filterableFields = nodeType.Fields.Where(f => f.Flags.HasFlag(EnFieldFlags.IsFilterable));
var stringContains = typeof(string).GetMethod("Contains");
var stringStartsWith = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
var stringEndsWith = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
var stringToLower = typeof(string).GetMethod("ToLower", new Type[0]);
foreach (var filterableField in filterableFields)
{
var property = realFields[filterableField.Name] as PropertyInfo;
if (property == null)
{
continue;
}
var propertyExpression = Expression.Property(FilterSourceParameter, property);
Func<JProperty, Expression> createConstant =
prop => Expression.Constant(prop.Value.ToObject(property.PropertyType), property.PropertyType);
AddFilterExpression(
filterableField.Name,
prop => Expression.Equal(propertyExpression, createConstant(prop)),
filterableField,
"{0} exactly equals to the parameter");
AddFilterExpression(
$"{filterableField.Name}_not",
prop => Expression.NotEqual(propertyExpression, createConstant(prop)),
filterableField,
"{0} not equals to the parameter");
switch (filterableField.ScalarType)
{
case EnScalarType.Float:
case EnScalarType.Decimal:
case EnScalarType.Integer:
case EnScalarType.DateTime:
AddFilterExpression(
$"{filterableField.Name}_lt",
prop => Expression.LessThan(propertyExpression, createConstant(prop)),
filterableField,
"{0} is less then the parameter");
AddFilterExpression(
$"{filterableField.Name}_lte",
prop => Expression.LessThanOrEqual(propertyExpression, createConstant(prop)),
filterableField,
"{0} is less then or equal to the parameter");
AddFilterExpression(
$"{filterableField.Name}_gt",
prop => Expression.GreaterThan(propertyExpression, createConstant(prop)),
filterableField,
"{0} is greater then the parameter");
AddFilterExpression(
$"{filterableField.Name}_gte",
prop => Expression.GreaterThanOrEqual(propertyExpression, createConstant(prop)),
filterableField,
"{0} is greater then or equal to the parameter");
break;
case EnScalarType.String:
var propertyToLower = Expression.Call(propertyExpression, stringToLower);
AddFilterExpression(
$"{filterableField.Name}_in",
prop => Expression.Call(createConstant(prop), stringContains, propertyExpression),
filterableField,
"{0} is a substring of the parameter");
AddFilterExpression(
$"{filterableField.Name}_not_in",
prop =>
Expression.Not(
Expression.Call(createConstant(prop), stringContains, propertyExpression)),
filterableField,
"{0} is not a substring of the parameter");
AddFilterExpression(
$"{filterableField.Name}_contains",
prop => Expression.Call(propertyExpression, stringContains, createConstant(prop)),
filterableField,
"{0} contains the parameter as substring");
AddFilterExpression(
$"{filterableField.Name}_not_contains",
prop =>
Expression.Not(
Expression.Call(propertyExpression, stringContains, createConstant(prop))),
filterableField,
"{0} doesn't contain the parameter as substring");
AddFilterExpression(
$"{filterableField.Name}_starts_with",
prop => Expression.Call(propertyExpression, stringStartsWith, createConstant(prop)),
filterableField,
"{0} starts with the parameter value");
AddFilterExpression(
$"{filterableField.Name}_not_starts_with",
prop =>
Expression.Not(
Expression.Call(propertyExpression, stringStartsWith, createConstant(prop))),
filterableField,
"{0} doesn't start with the parameter value");
AddFilterExpression(
$"{filterableField.Name}_ends_with",
prop => Expression.Call(propertyExpression, stringEndsWith, createConstant(prop)),
filterableField,
"{0} ends with the parameter value");
AddFilterExpression(
$"{filterableField.Name}_not_ends_with",
prop =>
Expression.Not(
Expression.Call(propertyExpression, stringEndsWith, createConstant(prop))),
filterableField,
"{0} doesn't end with the parameter value");
AddFilterExpression(
$"{filterableField.Name}_l",
prop => Expression.Equal(propertyToLower, createConstant(prop)),
filterableField,
"{0} lowercased equals the parameter");
AddFilterExpression(
$"{filterableField.Name}_l_not",
prop => Expression.NotEqual(propertyToLower, createConstant(prop)),
filterableField,
"{0} lowercased doesn't equal the parameter");
AddFilterExpression(
$"{filterableField.Name}_l_in",
prop => Expression.Call(createConstant(prop), stringContains, propertyToLower),
filterableField,
"{0} lowercased is a substring of the parameter");
AddFilterExpression(
$"{filterableField.Name}_l_not_in",
prop =>
Expression.Not(
Expression.Call(createConstant(prop), stringContains, propertyToLower)),
filterableField,
"{0} lowercased is not a substring of the parameter");
AddFilterExpression(
$"{filterableField.Name}_l_contains",
prop => Expression.Call(propertyToLower, stringContains, createConstant(prop)),
filterableField,
"{0} lowercased contains the parameter as substring");
AddFilterExpression(
$"{filterableField.Name}_l_not_contains",
prop =>
Expression.Not(
Expression.Call(propertyToLower, stringContains, createConstant(prop))),
filterableField,
"{0} lowercased doesn't contain the parameter as substring");
AddFilterExpression(
$"{filterableField.Name}_l_starts_with",
prop => Expression.Call(propertyToLower, stringStartsWith, createConstant(prop)),
filterableField,
"{0} lowercased starts with the parameter value");
AddFilterExpression(
$"{filterableField.Name}_l_not_starts_with",
prop =>
Expression.Not(
Expression.Call(propertyToLower, stringStartsWith, createConstant(prop))),
filterableField,
"{0} lowercased doesn't start with the parameter value");
AddFilterExpression(
$"{filterableField.Name}_l_ends_with",
prop => Expression.Call(propertyToLower, stringEndsWith, createConstant(prop)),
filterableField,
"{0} lowercased ends with the parameter value");
AddFilterExpression(
$"{filterableField.Name}_l_not_ends_with",
prop =>
Expression.Not(
Expression.Call(propertyToLower, stringEndsWith, createConstant(prop))),
filterableField,
"{0} lowercased doesn't end with the parameter value");
break;
}
}
}
}
/// <summary>
/// Creates the list of sorting conditions by sorting request
/// </summary>
/// <param name="arguments">The sorting request</param>
/// <returns>The list of sorting conditions</returns>
private IEnumerable<SortingCondition> CreateSort(JArray arguments)
{
var sortArgs = arguments.ToObject<string[]>();
foreach (var sort in sortArgs)
{
SortingCondition condition;
if (SortingConditions.TryGetValue(sort, out condition))
{
yield return condition;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using WaterOneFlow.Schema.v1_1;
using WaterOneFlowImpl;
using log4net;
using WaterOneFlowImpl.geom;
namespace WaterOneFlow.odws
{
//using WaterOneFlow.odm.v1_1;
using WaterOneFlowImpl.v1_1;
namespace v1_1
{
public class CustomService : IDisposable
{
private Cache appCache;
private HttpContext appContext;
//private VariablesDataset vds;
/* This is now done in the global.asax file
// this got cached, which cause the name to be localhost
*/
private string serviceUrl;
private string serviceName;
private static readonly ILog log = LogManager.GetLogger(typeof(CustomService));
private static readonly ILog queryLog = LogManager.GetLogger("QueryLog");
private static readonly CustomLogging queryLog2 = new CustomLogging();
public CustomService(HttpContext aContext)
{
log.Debug("Starting " + System.Configuration.ConfigurationManager.AppSettings["network"]);
appContext = aContext;
// This is now done in the global.asax file
// this got cached, which cause the name to be localhost
serviceName = ConfigurationManager.AppSettings["GetValuesName"];
Boolean odValues = Boolean.Parse(ConfigurationManager.AppSettings["UseODForValues"]);
if (odValues)
{
string Port = aContext.Request.ServerVariables["SERVER_PORT"];
if (Port == null || Port == "80" || Port == "443")
Port = "";
else
Port = ":" + Port;
string Protocol = aContext.Request.ServerVariables["SERVER_PORT_SECURE"];
if (Protocol == null || Protocol == "0")
Protocol = "http://";
else
Protocol = "https://";
// *** Figure out the base Url which points at the application's root
serviceUrl = Protocol + aContext.Request.ServerVariables["SERVER_NAME"] +
Port +
aContext.Request.ApplicationPath
+ "/" + ConfigurationManager.AppSettings["asmxPage_1_1"] + "?WSDL";
}
else
{
serviceUrl = ConfigurationManager.AppSettings["externalGetValuesService"];
}
}
#region Site Information
public SiteInfoResponseType GetSiteInfo(string locationParameter)
{
string siteId = locationParameter.Substring(locationParameter.LastIndexOf(":")+1);
SiteInfoResponseType resp = new SiteInfoResponseType();
resp.site = new SiteInfoResponseTypeSite[1];
resp.site[0] = new SiteInfoResponseTypeSite();
resp.site[0] = WebServiceUtils.GetSiteFromDb(siteId, true);
resp.queryInfo = CuahsiBuilder.CreateQueryInfoType("GetSiteInfo", new string[] { locationParameter }, null, null, null, null);
return resp;
}
public SiteInfoResponseType GetSiteInfo(string[] locationParameter, Boolean IncludeSeries)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
if (locationParameter != null)
{
queryLog2.LogStart(CustomLogging.Methods.GetSiteInfo, locationParameter.ToString(),
appContext.Request.UserHostName);
}
else
{
queryLog2.LogStart(CustomLogging.Methods.GetSiteInfo, "NULL",
appContext.Request.UserHostName);
}
List<locationParam> lpList = new List<locationParam>();
try
{
foreach (string s in locationParameter)
{
locationParam l = new locationParam(s);
if (l.isGeometry)
{
String error = "Location by Geometry not accepted: " + locationParameter;
log.Debug(error);
throw new WaterOneFlowException(error);
}
else
{
lpList.Add(l);
}
}
}
catch (WaterOneFlowException we)
{
log.Error(we.Message);
throw;
}
catch (Exception e)
{
String error =
"Sorry. Your submitted site ID for this getSiteInfo request caused an problem that we failed to catch programmatically: " +
e.Message;
log.Error(error);
throw new WaterOneFlowException(error);
}
SiteInfoResponseType resp = new SiteInfoResponseType();
resp.site = new SiteInfoResponseTypeSite[locationParameter.Length];
for (int i = 0; i < locationParameter.Length; i++)
{
resp.site[i] = WebServiceUtils.GetSiteFromDb(locationParameter[0], true);
}
foreach (SiteInfoResponseTypeSite site in resp.site)
{
foreach (seriesCatalogType catalog in site.seriesCatalog)
{
catalog.menuGroupName = serviceName;
catalog.serviceWsdl = serviceUrl;
}
}
if (locationParameter != null)
{
queryLog2.LogEnd(CustomLogging.Methods.GetSiteInfo,
locationParameter.ToString(),
timer.ElapsedMilliseconds.ToString(),
resp.site.Length.ToString(),
appContext.Request.UserHostName);
}
else
{
queryLog2.LogEnd(CustomLogging.Methods.GetSiteInfo,
"NULL",
timer.ElapsedMilliseconds.ToString(),
resp.site.Length.ToString(),
appContext.Request.UserHostName);
}
return resp;
}
public SiteInfoResponseType GetSites(string[] locationIDs)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
queryLog2.LogStart(CustomLogging.Methods.GetSites, locationIDs.ToString(),
appContext.Request.UserHostName);
SiteInfoResponseType result = new SiteInfoResponseType();
result.site = WebServiceUtils.GetSitesFromDb();
//set query info
result.queryInfo = CuahsiBuilder.CreateQueryInfoType("GetSites");
NoteType note = CuahsiBuilder.createNote("ALL Sites(empty request)");
result.queryInfo.note = CuahsiBuilder.addNote(null, note);
queryLog2.LogEnd(CustomLogging.Methods.GetSites,
locationIDs.ToString(),
timer.ElapsedMilliseconds.ToString(),
result.site.Length.ToString(),
appContext.Request.UserHostName);
return result;
}
public SiteInfoResponseType GetSitesInBox(
float west, float south, float east, float north,
Boolean IncludeSeries
)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
box queryBox = new box(west, south, east, north);
queryLog2.LogStart(CustomLogging.Methods.GetSitesInBoxObject, queryBox.ToString(),
appContext.Request.UserHostName);
SiteInfoResponseType resp = new SiteInfoResponseType();
resp.site = WebServiceUtils.GetSitesByBox(queryBox, IncludeSeries);
//set query info
resp.queryInfo = CuahsiBuilder.CreateQueryInfoType("GetSitesInBox");
NoteType note = CuahsiBuilder.createNote("box");
resp.queryInfo.note = CuahsiBuilder.addNote(null, note);
queryLog2.LogEnd(CustomLogging.Methods.GetSitesInBoxObject,
queryBox.ToString(),
timer.ElapsedMilliseconds.ToString(),
resp.site.Length.ToString(),
appContext.Request.UserHostName);
return resp;
}
#endregion
#region variable
/// <summary>
/// GetVariableInfo
/// </summary>
/// <param name="VariableParameter">full variable code in format vocabulary:VariableCode</param>
/// <returns>the VariableInfo object</returns>
public VariablesResponseType GetVariableInfo(String VariableParameter)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
queryLog2.LogStart(CustomLogging.Methods.GetVariables, VariableParameter,
appContext.Request.UserHostName);
VariablesResponseType resp;
if(string.IsNullOrEmpty(VariableParameter))
{
resp = new VariablesResponseType();
resp.variables = WebServiceUtils.GetVariablesFromDb();
//setup query info
resp.queryInfo = CuahsiBuilder.CreateQueryInfoType
("GetVariableInfo", null, null, new string[] { string.Empty }, null, null);
CuahsiBuilder.addNote(resp.queryInfo.note,
CuahsiBuilder.createNote("(Request for all variables"));
}
else
{
resp = new VariablesResponseType();
resp.variables = new VariableInfoType[1];
resp.variables[0] = WebServiceUtils.GetVariableInfoFromDb(VariableParameter);
//setup query info
resp.queryInfo = CuahsiBuilder.CreateQueryInfoType
("GetVariableInfo", null, null, new string[] { VariableParameter }, null, null);
}
queryLog2.LogEnd(CustomLogging.Methods.GetVariables,
VariableParameter,
timer.ElapsedMilliseconds.ToString(),
resp.variables.Length.ToString(),
appContext.Request.UserHostName);
return resp;
}
#endregion
#region values
/// <summary>
/// GetValues custom implementation
/// </summary>
/// <param name="SiteNumber">network:SiteCode</param>
/// <param name="Variable">vocabulary:VariableCode</param>
/// <param name="StartDate">yyyy-MM-dd</param>
/// <param name="EndDate">yyyy-MM-dd</param>
/// <returns></returns>
public TimeSeriesResponseType GetValues(string SiteNumber,
string Variable,
string StartDate,
string EndDate)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
// queryLog.Info("GetValues|" + SiteNumber + "|" + Variable + "|" + StartDate + "|" + EndDate);
//String network,method,location, variable, start, end, , processing time,count
queryLog2.LogValuesStart(CustomLogging.Methods.GetValues, // method
SiteNumber, //locaiton
Variable, //variable
StartDate, // startdate
EndDate, //enddate
appContext.Request.UserHostName);
//get siteId, variableId
string siteId = SiteNumber.Substring(SiteNumber.LastIndexOf(":") + 1);
string variableId = Variable.Substring(Variable.LastIndexOf(":") + 1);
//get startDateTime, endDateTime
DateTime startDateTime = DateTime.Parse(StartDate);
DateTime endDateTime = DateTime.Parse(EndDate);
//TimeSeriesResponseType resp = obj.getValues(SiteNumber, Variable, StartDate, EndDate);
TimeSeriesResponseType resp = new TimeSeriesResponseType();
resp.timeSeries = new TimeSeriesType[1];
resp.timeSeries[0] = new TimeSeriesType();
resp.timeSeries[0].sourceInfo = WebServiceUtils.GetSiteFromDb2(siteId);
resp.timeSeries[0].variable = WebServiceUtils.GetVariableInfoFromDb(variableId);
resp.timeSeries[0].values = new TsValuesSingleVariableType[1];
resp.timeSeries[0].values[0] = WebServiceUtils.GetValuesFromDb(siteId, variableId, startDateTime, endDateTime);
//set the query info
resp.queryInfo = new QueryInfoType();
resp.queryInfo.criteria = new QueryInfoTypeCriteria();
resp.queryInfo.creationTime = DateTime.UtcNow;
resp.queryInfo.creationTimeSpecified = true;
resp.queryInfo.criteria.locationParam = SiteNumber;
resp.queryInfo.criteria.variableParam = Variable;
resp.queryInfo.criteria.timeParam = CuahsiBuilder.createQueryInfoTimeCriteria(StartDate, EndDate);
queryLog2.LogValuesEnd(CustomLogging.Methods.GetValues,
SiteNumber, //locaiton
Variable, //variable
StartDate, // startdate
EndDate, //enddate
timer.ElapsedMilliseconds, // processing time
// assume one for now
resp.timeSeries[0].values[0].value.Length, // count
appContext.Request.UserHostName);
return resp;
}
//TODO implement this function
public TimeSeriesResponseType GetValuesForASite(string site, string startDate, string endDate)
{
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
//String network,method,location, variable, start, end, , processing time,count
queryLog2.LogValuesStart(CustomLogging.Methods.GetValuesForSiteObject, // method
site, //locaiton
"ALL", //variable
startDate, // startdate
endDate, //enddate
appContext.Request.UserHostName);
//TimeSeriesResponseType resp = obj.GetValuesForSiteVariable(site, startDate, endDate);
TimeSeriesResponseType resp = new TimeSeriesResponseType();
// //String network,method,location, variable, start, end, , processing time,count
// queryLog.InfoFormat("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}",
//System.Configuration.ConfigurationManager.AppSettings["network"], // network
//"GetValues", // method
//SiteNumber, //locaiton
//Variable, //variable
//StartDate, // startdate
//StartDate, //enddate
//timer.ElapsedMilliseconds, // processing time
//resp.timeSeries.values.value.Length // count
//,
// appContext.Request.UserHostName);
queryLog2.LogValuesEnd(CustomLogging.Methods.GetValuesForSiteObject,
site, //locaiton
"ALL", //variable
startDate, // startdate
endDate, //enddate
timer.ElapsedMilliseconds, // processing time
// assume one for now
-9999, // May need to count all.
appContext.Request.UserHostName);
return resp;
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposeOf)
{
// waterLog.Dispose();
}
#endregion
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebappTokenCode.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Compiler;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Contracts.Foxtrot.Utils;
namespace Microsoft.Contracts.Foxtrot
{
/// <summary>
/// Visitor that creates special closure type for async postconditions.
/// </summary>
/// <remarks>
///
/// Current class generate AsyncClosure with CheckMethod and CheckException methods.
///
/// Following transformation are applied to the original async method:
///
/// // This is oroginal task, generated by the AsyncTaskMethodBuilder
/// var originalTask = t_builder.Task;
///
/// var closure = new AsyncClosure();
/// var task2 = originalTask.ContinueWith(closure.CheckPost).Unwrap();
/// return task2;
///
/// There are 2 cases:
/// 1) Task has no return value.
/// In this case only EnsuresOnThrow could be used, and we emit:
/// Task CheckMethod(Task t)
/// {
/// if (t.Status == TaskStatus.Faulted)
/// {
/// // CheckException will throw if EnsuresOnThrow is not held
/// CheckException(t.Exception);
/// }
///
/// return t;
/// }
///
/// 2) Task(T) reutrns a T value.
/// In this case both EnsuresOnThrow and Contract.Ensures(Contract.Result) could be used.
/// We emit:
///
/// Task<int> CheckMethod(Task<int> t)
/// {
/// if (t.Status == TaskStatus.Faulted)
/// {
/// // CheckException will throw if EnsuresOnThrow is not held
/// CheckException(t.Exception);
/// }
///
/// if (t.Status == TaskStatus.RanToCompletion)
/// {
/// // Check ensures
/// }
/// }
/// </remarks>
internal class EmitAsyncClosure : StandardVisitor
{
// This assembly should be in this class but not in the SystemTypes from System.CompilerCC.
// Moving this type there will lead to test failures and assembly resolution errors.
private static readonly AssemblyNode/*!*/ SystemCoreAssembly = SystemTypes.GetSystemCoreAssembly(false, true);
private static TypeNode TaskExtensionsTypeNode = HelperMethods.FindType(
SystemCoreAssembly,
Identifier.For("System.Threading.Tasks"),
Identifier.For("TaskExtensions"));
private static readonly Identifier CheckExceptionMethodId = Identifier.For("CheckException");
private static readonly Identifier CheckMethodId = Identifier.For("CheckPost");
private readonly Cache<TypeNode> aggregateExceptionType;
private readonly Cache<TypeNode> func2Type;
private readonly Dictionary<Local, MemberBinding> closureLocals = new Dictionary<Local, MemberBinding>();
private readonly List<SourceContext> contractResultCapturedInStaticContext = new List<SourceContext>();
private readonly Rewriter rewriter;
private readonly TypeNode declaringType;
private readonly Class closureClass;
private readonly Class closureClassInstance;
private readonly Specializer /*?*/ forwarder;
private readonly Local closureLocal;
// Fields for the CheckMethod generation
private Method checkPostMethod;
private StatementList checkPostBody;
// Holds a copy of CheckMethod argument
private Local originalResultLocal;
private Parameter checkMethodTaskParameter;
private readonly TypeNode checkMethodTaskType;
public EmitAsyncClosure(Method from, Rewriter rewriter)
{
Contract.Requires(from != null);
Contract.Requires(from.DeclaringType != null);
Contract.Requires(rewriter != null);
if (TaskExtensionsTypeNode == null)
{
throw new InvalidOperationException(
"Can't generate async closure because System.Threading.Tasks.TaskExceptions class is unavailable.");
}
this.rewriter = rewriter;
this.declaringType = from.DeclaringType;
var closureName = HelperMethods.NextUnusedMemberName(declaringType, "<" + from.Name.Name + ">AsyncContractClosure");
this.closureClass = new Class(
declaringModule: declaringType.DeclaringModule,
declaringType: declaringType,
attributes: null,
flags: TypeFlags.NestedPrivate,
Namespace: null,
name: Identifier.For(closureName),
baseClass: SystemTypes.Object,
interfaces: null,
members: null);
declaringType.Members.Add(this.closureClass);
RewriteHelper.TryAddCompilerGeneratedAttribute(this.closureClass);
var taskType = from.ReturnType;
this.aggregateExceptionType = new Cache<TypeNode>(() =>
HelperMethods.FindType(rewriter.AssemblyBeingRewritten, StandardIds.System,
Identifier.For("AggregateException")));
this.func2Type = new Cache<TypeNode>(() =>
HelperMethods.FindType(SystemTypes.SystemAssembly, StandardIds.System, Identifier.For("Func`2")));
if (from.IsGeneric)
{
this.closureClass.TemplateParameters = CreateTemplateParameters(closureClass, from, declaringType);
this.closureClass.IsGeneric = true;
this.closureClass.EnsureMangledName();
this.forwarder = new Specializer(
targetModule: this.declaringType.DeclaringModule,
pars: from.TemplateParameters,
args: this.closureClass.TemplateParameters);
this.forwarder.VisitTypeParameterList(this.closureClass.TemplateParameters);
taskType = this.forwarder.VisitTypeReference(taskType);
}
else
{
this.closureClassInstance = this.closureClass;
}
this.checkMethodTaskType = taskType;
// Emiting CheckPost method declaration
EmitCheckPostMethodCore(checkMethodTaskType);
// Generate closure constructor.
// Constructor should be generated AFTER visiting type parameters in
// the previous block of code. Otherwise current class would not have
// appropriate number of generic arguments!
var ctor = CreateConstructor(closureClass);
closureClass.Members.Add(ctor);
// Now that we added the ctor and the check method, let's instantiate the closure class if necessary
if (this.closureClassInstance == null)
{
var consArgs = new TypeNodeList();
var args = new TypeNodeList();
var parentCount = this.closureClass.DeclaringType.ConsolidatedTemplateParameters == null
? 0
: this.closureClass.DeclaringType.ConsolidatedTemplateParameters.Count;
for (int i = 0; i < parentCount; i++)
{
consArgs.Add(this.closureClass.DeclaringType.ConsolidatedTemplateParameters[i]);
}
var methodCount = from.TemplateParameters == null ? 0 : from.TemplateParameters.Count;
for (int i = 0; i < methodCount; i++)
{
consArgs.Add(from.TemplateParameters[i]);
args.Add(from.TemplateParameters[i]);
}
this.closureClassInstance =
(Class)
this.closureClass.GetConsolidatedTemplateInstance(this.rewriter.AssemblyBeingRewritten,
closureClass.DeclaringType, closureClass.DeclaringType, args, consArgs);
}
// create closure initializer for context method
this.closureLocal = new Local(this.ClosureClass);
this.ClosureInitializer = new Block(new StatementList());
// TODO: What is this?
// Add ClosureLocal instantiation?
this.ClosureInitializer.Statements.Add(
new AssignmentStatement(
this.closureLocal,
new Construct(new MemberBinding(null, this.Ctor), new ExpressionList())));
}
/// <summary>
/// Add postconditions for the task-based methods.
/// </summary>
/// <remarks>
/// Method inserts all required logic to the <paramref name="returnBlock"/> calling
/// ContinueWith method on the <paramref name="taskBasedResult"/>.
/// </remarks>
public void AddAsyncPostconditions(List<Ensures> asyncPostconditions, Block returnBlock, Local taskBasedResult)
{
Contract.Requires(asyncPostconditions != null);
Contract.Requires(returnBlock != null);
Contract.Requires(taskBasedResult != null);
Contract.Requires(asyncPostconditions.Count > 0);
Contract.Assume(taskBasedResult.Type == checkMethodTaskType);
// Async postconditions are impelemented using custom closure class
// with CheckPost method that checks postconditions when the task
// is finished.
// Add Async postconditions to the AsyncClosure
AddAsyncPost(asyncPostconditions);
// Add task.ContinueWith().Unwrap(); method call to returnBlock
AddContinueWithMethodToReturnBlock(returnBlock, taskBasedResult);
}
/// <summary>
/// Returns a list of source spans where non-capturing lambdas were used.
/// </summary>
public IList<SourceContext> ContractResultCapturedInStaticContext
{
get { return contractResultCapturedInStaticContext; }
}
/// <summary>
/// Instance used in calling method context
/// </summary>
public Class ClosureClass
{
get { return this.closureClassInstance; }
}
/// <summary>
/// Local instance of the async closure class
/// </summary>
public Local ClosureLocal { get { return this.closureLocal; } }
/// <summary>
/// Block of code, responsible for closure instance initialization
/// </summary>
public Block ClosureInitializer { get; private set; }
private InstanceInitializer Ctor
{
get { return (InstanceInitializer)this.closureClassInstance.GetMembersNamed(StandardIds.Ctor)[0]; }
}
[Pure]
private static TypeNodeList CreateTemplateParameters(Class closureClass, Method @from, TypeNode declaringType)
{
var dup = new Duplicator(declaringType.DeclaringModule, declaringType);
var templateParameters = new TypeNodeList();
var parentCount = declaringType.ConsolidatedTemplateParameters.CountOrDefault();
for (int i = 0; i < from.TemplateParameters.Count; i++)
{
var tp = HelperMethods.NewEqualTypeParameter(
dup, (ITypeParameter)from.TemplateParameters[i],
closureClass, parentCount + i);
templateParameters.Add(tp);
}
return templateParameters;
}
private void AddContinueWithMethodToReturnBlock(Block returnBlock, Local taskBasedResult)
{
Contract.Requires(returnBlock != null);
Contract.Requires(taskBasedResult != null);
var taskType = taskBasedResult.Type;
// To find appropriate ContinueWith method task type should be unwrapped
var taskTemplate = HelperMethods.Unspecialize(taskType);
var continueWithMethodLocal = GetContinueWithMethod(closureClass, taskTemplate, taskType);
// TODO: not sure that this is possible situation when continueWith method is null.
// Maybe Contract.Assert(continueWithMethod != null) should be used instead!
if (continueWithMethodLocal != null)
{
// We need to create delegate instance that should be passed to ContinueWith method
var funcType = continueWithMethodLocal.Parameters[0].Type;
var funcCtor = funcType.GetConstructor(SystemTypes.Object, SystemTypes.IntPtr);
Contract.Assume(funcCtor != null);
var funcLocal = new Local(funcCtor.DeclaringType);
// Creating a method pointer to the AsyncClosure.CheckMethod
// In this case we can't use checkMethod field.
// Getting CheckMethod from clsoureClassInstance will provide correct (potentially updated)
// generic arguments for enclosing type.
var checkMethodFromClosureInstance = (Method) closureClassInstance.GetMembersNamed(CheckMethodId)[0];
Contract.Assume(checkMethodFromClosureInstance != null);
var ldftn = new UnaryExpression(
new MemberBinding(null, checkMethodFromClosureInstance),
NodeType.Ldftn,
CoreSystemTypes.IntPtr);
// Creating delegate that would be used as a continuation for original task
returnBlock.Statements.Add(
new AssignmentStatement(funcLocal,
new Construct(new MemberBinding(null, funcCtor),
new ExpressionList(closureLocal, ldftn))));
// Wrapping continuation into TaskExtensions.Unwrap method
// (this helps to preserve original exception and original result of the task,
// but allows to throw postconditions violations).
// Generating: result.ContinueWith(closure.CheckPost);
var continueWithCall =
new MethodCall(
new MemberBinding(taskBasedResult, continueWithMethodLocal),
new ExpressionList(funcLocal));
// Generating: TaskExtensions.Unwrap(result.ContinueWith(...))
var unwrapMethod = GetUnwrapMethod(checkMethodTaskType);
var unwrapCall =
new MethodCall(
new MemberBinding(null, unwrapMethod), new ExpressionList(continueWithCall));
// Generating: result = Unwrap(...);
var resultAssignment =
new AssignmentStatement(taskBasedResult, unwrapCall);
returnBlock.Statements.Add(resultAssignment);
}
}
/// <summary>
/// Method generates core part of the CheckMethod
/// </summary>
private void EmitCheckPostMethodCore(TypeNode taskType)
{
Contract.Requires(taskType != null);
this.checkMethodTaskParameter = new Parameter(Identifier.For("task"), taskType);
// TODO ST: can I switch to new Local(taskType.Type)?!? In this case this initialization
// could be moved outside this method
this.originalResultLocal = new Local(new Identifier("taskLocal"), checkMethodTaskParameter.Type);
// Generate: public Task<T> CheckPost(Task<T> task) where T is taskType or
// public Task CheckPost(Task task) for non-generic task.
checkPostMethod = new Method(
declaringType: this.closureClass,
attributes: null,
name: CheckMethodId,
parameters: new ParameterList(checkMethodTaskParameter),
// was: taskType.TemplateArguments[0] when hasResult was true and SystemTypes.Void otherwise
returnType: taskType,
body: null);
checkPostMethod.CallingConvention = CallingConventionFlags.HasThis;
checkPostMethod.Flags |= MethodFlags.Public;
this.checkPostBody = new StatementList();
this.closureClass.Members.Add(this.checkPostMethod);
if (taskType.IsGeneric)
{
// Assign taskParameter to originalResultLocal because
// this field is used in a postcondition
checkPostBody.Add(new AssignmentStatement(this.originalResultLocal, checkMethodTaskParameter));
}
}
private void AddAsyncPost(List<Ensures> asyncPostconditions)
{
var origBody = new Block(this.checkPostBody);
origBody.HasLocals = true;
var newBodyBlock = new Block(new StatementList());
newBodyBlock.HasLocals = true;
var methodBody = new StatementList();
var methodBodyBlock = new Block(methodBody);
methodBodyBlock.HasLocals = true;
checkPostMethod.Body = methodBodyBlock;
methodBody.Add(newBodyBlock);
Block newExitBlock = new Block();
methodBody.Add(newExitBlock);
// Map closure locals to fields and initialize closure fields
foreach (Ensures e in asyncPostconditions)
{
if (e == null) continue;
this.Visit(e);
if (this.forwarder != null)
{
this.forwarder.Visit(e);
}
ReplaceResult repResult = new ReplaceResult(
this.checkPostMethod, this.originalResultLocal,
this.rewriter.AssemblyBeingRewritten);
repResult.Visit(e);
if (repResult.ContractResultWasCapturedInStaticContext)
{
this.contractResultCapturedInStaticContext.Add(e.Assertion.SourceContext);
}
// now need to initialize closure result fields
foreach (var target in repResult.NecessaryResultInitializationAsync(this.closureLocals))
{
// note: target here
methodBody.Add(new AssignmentStatement(target, this.originalResultLocal));
}
}
// Emit normal postconditions
SourceContext? lastEnsuresSourceContext = null;
var ensuresChecks = new StatementList();
Method contractEnsuresMethod = this.rewriter.RuntimeContracts.EnsuresMethod;
foreach (Ensures e in GetTaskResultBasedEnsures(asyncPostconditions))
{
// TODO: Not sure that 'break' is enough! It seems that this is possible
// only when something is broken, because normal postconditions
// are using Contract.Result<T>() and this is possible only for
// generic tasks.
if (IsVoidTask()) break; // something is wrong in the original contract
lastEnsuresSourceContext = e.SourceContext;
//
// Call Contract.RewriterEnsures
//
ExpressionList args = new ExpressionList();
args.Add(e.PostCondition);
args.Add(e.UserMessage ?? Literal.Null);
args.Add(e.SourceConditionText ?? Literal.Null);
ensuresChecks.Add(
new ExpressionStatement(
new MethodCall(
new MemberBinding(null, contractEnsuresMethod),
args, NodeType.Call, SystemTypes.Void),
e.SourceContext));
}
this.rewriter.CleanUpCodeCoverage.VisitStatementList(ensuresChecks);
//
// Normal postconditions
//
// Wrapping normal ensures into following if statement
// if (task.Status == TaskStatus.RanToCompletion)
// { postcondition check }
//
// Implementation of this stuff is a bit tricky because if-statements
// are inverse in the IL.
// Basically, we need to generate following code:
// if (!(task.Status == Task.Status.RanToCompletion))
// goto EndOfNormalPostcondition;
// {postcondition check}
// EndOfNormalPostcondition:
// {other Code}
// Marker for EndOfNormalPostcondition
Block endOfNormalPostcondition = new Block();
// Generate: if (task.Status != RanToCompletion) goto endOfNormalPostcondition;
StatementList checkStatusStatements = CreateIfTaskResultIsEqualsTo(
checkMethodTaskParameter, TaskStatus.RanToCompletion, endOfNormalPostcondition);
methodBodyBlock.Statements.Add(new Block(checkStatusStatements));
// Emit a check for __ContractsRuntime.insideContractEvaluation around Ensures
this.rewriter.EmitRecursionGuardAroundChecks(this.checkPostMethod, methodBodyBlock, ensuresChecks);
// Now, normal postconditions are written to the method body.
// We need to add endOfNormalPostcondition block as a marker.
methodBodyBlock.Statements.Add(endOfNormalPostcondition);
//
// Exceptional postconditions
//
var exceptionalPostconditions = GetExceptionalEnsures(asyncPostconditions).ToList();
if (exceptionalPostconditions.Count > 0)
{
// For exceptional postconditions we need to generate CheckException method first
Method checkExceptionMethod = CreateCheckExceptionMethod();
EmitCheckExceptionBody(checkExceptionMethod, exceptionalPostconditions);
this.closureClass.Members.Add(checkExceptionMethod);
// Then, we're using the same trick as for normal postconditions:
// wrapping exceptional postconditions only when task.Status is TaskStatus.Faulted
Block checkExceptionBlock = new Block(new StatementList());
// Marker for endOfExceptionPostcondition
Block endOfExceptionPostcondition = new Block();
StatementList checkStatusIsException = CreateIfTaskResultIsEqualsTo(
checkMethodTaskParameter, TaskStatus.Faulted, endOfExceptionPostcondition);
checkExceptionBlock.Statements.Add(new Block(checkStatusIsException));
// Now we need to emit actuall check for exceptional postconditions
// Emit: var ae = task.Exception;
var aeLocal = new Local(aggregateExceptionType.Value);
checkExceptionBlock.Statements.Add(
new AssignmentStatement(aeLocal,
new MethodCall(
new MemberBinding(checkMethodTaskParameter,
GetTaskProperty(checkMethodTaskParameter, "get_Exception")),
new ExpressionList())));
// Emit: CheckException(ae);
// Need to store method result somewhere, otherwise stack would be corrupted
var checkResultLocal = new Local(SystemTypes.Boolean);
checkExceptionBlock.Statements.Add(
new AssignmentStatement(checkResultLocal,
new MethodCall(new MemberBinding(null,
checkExceptionMethod),
new ExpressionList(checkExceptionMethod.ThisParameter, aeLocal))));
checkExceptionBlock.Statements.Add(endOfExceptionPostcondition);
methodBody.Add(checkExceptionBlock);
}
// Copy original block to body statement for both: normal and exceptional postconditions.
newBodyBlock.Statements.Add(origBody);
Block returnBlock = CreateReturnBlock(checkMethodTaskParameter, lastEnsuresSourceContext);
methodBody.Add(returnBlock);
}
private static IEnumerable<Ensures> GetTaskResultBasedEnsures(List<Ensures> asyncPostconditions)
{
return asyncPostconditions.Where(post => !(post is EnsuresExceptional));
}
private static IEnumerable<EnsuresExceptional> GetExceptionalEnsures(List<Ensures> asyncPostconditions)
{
return asyncPostconditions.OfType<EnsuresExceptional>();
}
/// <summary>
/// Returns TaskExtensions.Unwrap method.
/// </summary>
[Pure]
private static Member GetUnwrapMethod(TypeNode checkMethodTaskType)
{
Contract.Requires(checkMethodTaskType != null);
Contract.Ensures(Contract.Result<Member>() != null);
Contract.Assume(TaskExtensionsTypeNode != null, "Can't find System.Threading.Tasks.TaskExtensions type");
var unwrapCandidates = TaskExtensionsTypeNode.GetMembersNamed(Identifier.For("Unwrap"));
Contract.Assert(unwrapCandidates != null,
"Can't find Unwrap method in the TaskExtensions type");
// Should be only two methods. If that is not true, we need to change this code to reflect this!
Contract.Assume(unwrapCandidates.Count == 2, "Should be exactly two candidate Unwrap methods.");
// We need to find appropriate Unwrap method based on CheckMethod argument type.
var firstMethod = (Method)unwrapCandidates[0];
var secondMethod = (Method)unwrapCandidates[1];
Contract.Assume(firstMethod != null && secondMethod != null);
var genericUnwrapCandidate = firstMethod.IsGeneric ? firstMethod : secondMethod;
var nonGenericUnwrapCandidate = firstMethod.IsGeneric ? secondMethod : firstMethod;
if (checkMethodTaskType.IsGeneric)
{
// We need to "instantiate" generic first.
// I.e. for Task<int> we need to have Unwrap(Task<Task<int>>): Task<int>
return genericUnwrapCandidate.GetTemplateInstance(null, checkMethodTaskType.TemplateArguments[0]);
}
return nonGenericUnwrapCandidate;
}
/// <summary>
/// Factory method that creates bool CheckException(Exception e)
/// </summary>
[Pure]
private Method CreateCheckExceptionMethod()
{
Contract.Ensures(Contract.Result<Method>() != null);
var exnParameter = new Parameter(Identifier.For("e"), SystemTypes.Exception);
var checkExceptionMethod =
new Method(
declaringType: this.closureClass,
attributes: null,
name: CheckExceptionMethodId,
parameters: new ParameterList(exnParameter),
returnType: SystemTypes.Boolean,
body: new Block(new StatementList()));
checkExceptionMethod.Body.HasLocals = true;
checkExceptionMethod.CallingConvention = CallingConventionFlags.HasThis;
checkExceptionMethod.Flags |= MethodFlags.Public;
if (checkExceptionMethod.ExceptionHandlers == null)
checkExceptionMethod.ExceptionHandlers = new ExceptionHandlerList();
return checkExceptionMethod;
}
private void EmitCheckExceptionBody(Method checkExceptionMethod, List<EnsuresExceptional> exceptionalPostconditions)
{
Contract.Requires(checkExceptionMethod != null);
Contract.Requires(exceptionalPostconditions != null);
Contract.Requires(exceptionalPostconditions.Count > 0);
// We emit the following method:
// bool CheckException(Exception e) {
// var ex = e as C1;
// if (ex != null) {
// EnsuresOnThrow(predicate)
// }
// else {
// var ex2 = e as AggregateException;
// if (ex2 != null) {
// ex2.Handle(CheckException);
// }
// }
//
// // Method always returns true. This is by design!
// // We need to check all exceptions in the AggregateException
// // and fail in EnsuresOnThrow if the postcondition is not met.
// return true; // handled
var body = checkExceptionMethod.Body.Statements;
var returnBlock = new Block(new StatementList());
foreach (var e in exceptionalPostconditions)
{
// The catchBlock contains the catchBody, and then
// an empty block that is used in the EH.
// TODO ST: name is confusing because there is no catch blocks in this method!
Block catchBlock = new Block(new StatementList());
// local is: var ex1 = e as C1;
Local localEx = new Local(e.Type);
body.Add(
new AssignmentStatement(localEx,
new BinaryExpression(checkExceptionMethod.Parameters[0],
new MemberBinding(null, e.Type),
NodeType.Isinst)));
Block skipBlock = new Block();
body.Add(new Branch(new UnaryExpression(localEx, NodeType.LogicalNot), skipBlock));
body.Add(catchBlock);
body.Add(skipBlock);
// call Contract.EnsuresOnThrow
ExpressionList args = new ExpressionList();
args.Add(e.PostCondition);
args.Add(e.UserMessage ?? Literal.Null);
args.Add(e.SourceConditionText ?? Literal.Null);
args.Add(localEx);
var checks = new StatementList();
checks.Add(
new ExpressionStatement(
new MethodCall(
new MemberBinding(null, this.rewriter.RuntimeContracts.EnsuresOnThrowMethod),
args,
NodeType.Call,
SystemTypes.Void),
e.SourceContext));
this.rewriter.CleanUpCodeCoverage.VisitStatementList(checks);
// TODO ST: actually I can't see this recursion guard check in the resulting IL!!
rewriter.EmitRecursionGuardAroundChecks(checkExceptionMethod, catchBlock, checks);
catchBlock.Statements.Add(new Branch(null, returnBlock));
}
// recurse on AggregateException itself
{
// var ae = e as AggregateException;
// if (ae != null) {
// ae.Handle(this.CheckException);
// }
Block catchBlock = new Block(new StatementList());
var aggregateType = aggregateExceptionType.Value;
// var ex2 = e as AggregateException;
Local localEx2 = new Local(aggregateType);
body.Add(
new AssignmentStatement(localEx2,
new BinaryExpression(
checkExceptionMethod.Parameters[0],
new MemberBinding(null, aggregateType),
NodeType.Isinst)));
Block skipBlock = new Block();
body.Add(new Branch(new UnaryExpression(localEx2, NodeType.LogicalNot), skipBlock));
body.Add(catchBlock);
body.Add(skipBlock);
var funcType = func2Type.Value;
funcType = funcType.GetTemplateInstance(this.rewriter.AssemblyBeingRewritten, SystemTypes.Exception, SystemTypes.Boolean);
var handleMethod = aggregateType.GetMethod(Identifier.For("Handle"), funcType);
var funcLocal = new Local(funcType);
var ldftn =
new UnaryExpression(
new MemberBinding(null, checkExceptionMethod),
NodeType.Ldftn,
CoreSystemTypes.IntPtr);
catchBlock.Statements.Add(
new AssignmentStatement(funcLocal,
new Construct(
new MemberBinding(null, funcType.GetConstructor(SystemTypes.Object, SystemTypes.IntPtr)),
new ExpressionList(checkExceptionMethod.ThisParameter, ldftn))));
catchBlock.Statements.Add(
new ExpressionStatement(new MethodCall(new MemberBinding(localEx2, handleMethod),
new ExpressionList(funcLocal))));
}
// add return true to CheckException method
body.Add(returnBlock);
body.Add(new Return(Literal.True));
}
/// <summary>
/// Returns property for the task object.
/// </summary>
private static Method GetTaskProperty(Parameter taskParameter, string propertyName)
{
Contract.Requires(taskParameter != null);
Contract.Ensures(Contract.Result<Method>() != null);
// For generic task Status property defined in the base class.
// That's why we need to check what the taskParameter type is - is it generic or not.
// If the taskParameter is generic we need to use base type (because Task<T> : Task).
var taskTypeWithStatusProperty = taskParameter.Type.IsGeneric
? taskParameter.Type.BaseType
: taskParameter.Type;
return taskTypeWithStatusProperty.GetMethod(Identifier.For(propertyName));
}
/// <summary>
/// Method returns a list of statements that checks task status.
/// </summary>
private static StatementList CreateIfTaskResultIsEqualsTo(
Parameter taskParameterToCheck, TaskStatus expectedStatus,
Block endBlock)
{
Contract.Ensures(Contract.Result<StatementList>() != null);
var result = new StatementList();
// If-statement is slightly different in IL.
// To get `if (condition) {statements}`
// we need to generate:
// if (!condition) goto endBLock; statements; endBlock:
// This method emits a check that simplifies CheckMethod implementation.
var statusProperty = GetTaskProperty(taskParameterToCheck, "get_Status");
Contract.Assert(statusProperty != null, "Can't find Task.Status property");
// Emitting: var tmpStatus = task.Status;
var tmpStatus = new Local(statusProperty.ReturnType);
result.Add(
new AssignmentStatement(tmpStatus,
new MethodCall(new MemberBinding(taskParameterToCheck, statusProperty),
new ExpressionList())));
// if (tmpStatus != expectedStatus)
// goto endOfMethod;
// This is an inverted form of the check: if (tmpStatus == expectedStatus) {check}
result.Add(
new Branch(
new BinaryExpression(
tmpStatus,
new Literal(expectedStatus),
NodeType.Ne),
endBlock));
return result;
}
private static Block CreateReturnBlock(Parameter checkPostTaskParameter, SourceContext? lastEnsuresSourceContext)
{
Statement returnStatement = new Return(checkPostTaskParameter);
if (lastEnsuresSourceContext != null)
{
returnStatement.SourceContext = lastEnsuresSourceContext.Value;
}
Block returnBlock = new Block(new StatementList(1));
returnBlock.Statements.Add(returnStatement);
return returnBlock;
}
/// <summary>
/// Returns correct version of the ContinueWith method.
/// </summary>
private static Method GetContinueWithMethod(Class closureClass, TypeNode taskTemplate, TypeNode taskType)
{
var continueWithCandidates = taskTemplate.GetMembersNamed(Identifier.For("ContinueWith"));
for (int i = 0; i < continueWithCandidates.Count; i++)
{
var cand = continueWithCandidates[i] as Method;
if (cand == null) continue;
// For non-generic version we're looking for ContinueWith(Action<Task>)
//if (taskType.TemplateArgumentsCount() == 0)
if (!taskType.IsGeneric)
{
if (cand.IsGeneric) continue;
if (cand.ParameterCount != 1) continue;
if (cand.Parameters[0].Type.GetMetadataName() != "Action`1") continue;
return cand;
}
// For generic version we're looking for ContinueWith(Func<Task, T>)
if (!cand.IsGeneric) continue;
if (cand.TemplateParameters.Count != 1) continue;
if (cand.ParameterCount != 1) continue;
if (cand.Parameters[0].Type.GetMetadataName() != "Func`2") continue;
// now create instance, first of task
var taskInstance = taskTemplate.GetTemplateInstance(
closureClass.DeclaringModule,
taskType.TemplateArguments[0]);
// ST: some black magic is happening, but it seems it is required to get ContinueWith
// from generic instantiated version of the task
var candMethod = (Method)taskInstance.GetMembersNamed(Identifier.For("ContinueWith"))[i];
// Candidate method would have following signature:
// Task<T> ContinueWith(Task<T> t) for generic version
return candMethod.GetTemplateInstance(null, taskType);
}
return null;
}
private static InstanceInitializer CreateConstructor(Class closureClass)
{
var ctor = new InstanceInitializer(closureClass, null, null, null);
ctor.CallingConvention = CallingConventionFlags.HasThis;
ctor.Flags |= MethodFlags.Public | MethodFlags.HideBySig;
// Regular block that calls base class constructor
ctor.Body = new Block(
new StatementList(
new ExpressionStatement(
new MethodCall(new MemberBinding(ctor.ThisParameter, SystemTypes.Object.GetConstructor()),
new ExpressionList())),
new Return()));
return ctor;
}
private bool IsVoidTask()
{
return this.checkPostMethod.ReturnType == SystemTypes.Void;
}
// Visitor for changing closure locals to fields
public override Expression VisitLocal(Local local)
{
if (HelperMethods.IsClosureType(this.declaringType, local.Type))
{
MemberBinding mb;
if (!closureLocals.TryGetValue(local, out mb))
{
// TODO ST: not clear what's going on here!
// Forwarder would be null, if enclosing method with async closure is not generic
var localType = forwarder != null ? forwarder.VisitTypeReference(local.Type) : local.Type;
var closureField = new Field(this.closureClass, null, FieldFlags.Public, local.Name, localType, null);
this.closureClass.Members.Add(closureField);
mb = new MemberBinding(this.checkPostMethod.ThisParameter, closureField);
closureLocals.Add(local, mb);
// initialize the closure field
var instantiatedField = Rewriter.GetMemberInstanceReference(closureField, this.closureClassInstance);
this.ClosureInitializer.Statements.Add(
new AssignmentStatement(
new MemberBinding(this.closureLocal, instantiatedField), local));
}
return mb;
}
return local;
}
}
}
| |
/*
* 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.
*/
//------------------------------------------------------------------------------
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
// To get up to date fundamental definition files for your hedgefund contact [email protected]
using System;
using Newtonsoft.Json;
namespace QuantConnect.Data.Fundamental
{
/// <summary>
/// Definition of the SecurityReference class
/// </summary>
public class SecurityReference
{
/// <summary>
/// An arrangement of characters (often letters) representing a particular security listed on an exchange or otherwise traded publicly.
/// Note: Morningstar's multi-share class symbols will often contain a "period" within the symbol; e.g. BRK.B for Berkshire Hathaway
/// Class B.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1001
/// </remarks>
[JsonProperty("1001")]
public string SecuritySymbol { get; set; }
/// <summary>
/// The Id representing the stock exchange that the particular share class is trading. See separate reference document for Exchange
/// Mappings.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1002
/// </remarks>
[JsonProperty("1002")]
public string ExchangeId { get; set; }
/// <summary>
/// 3 Character ISO code of the currency that the exchange price is denominated in; i.e. the trading currency of the security. See
/// separate reference document for Currency Mappings.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1004
/// </remarks>
[JsonProperty("1004")]
public string CurrencyId { get; set; }
/// <summary>
/// </summary>
/// <remarks>
/// Morningstar DataId: 1005
/// </remarks>
[JsonProperty("1005")]
public string Valoren { get; set; }
/// <summary>
/// The initial day that the share begins trading on a public exchange.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1009
/// </remarks>
[JsonProperty("1009")]
public DateTime IPODate { get; set; }
/// <summary>
/// Indicator to denote if the share class is a depository receipt. 1 denotes it is an ADR or GDR; otherwise 0.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1010
/// </remarks>
[JsonProperty("1010")]
public bool IsDepositaryReceipt { get; set; }
/// <summary>
/// The number of underlying common shares backing each American Depository Receipt traded.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1011
/// </remarks>
[JsonProperty("1011")]
public decimal DepositaryReceiptRatio { get; set; }
/// <summary>
/// Each security will be assigned to one of the below security type classifications;
/// - Common Stock (ST00000001)
/// - Preferred Stock (ST00000002)
/// - Units (ST000000A1)
/// </summary>
/// <remarks>
/// Morningstar DataId: 1012
/// </remarks>
[JsonProperty("1012")]
public string SecurityType { get; set; }
/// <summary>
/// Provides information when applicable such as whether the share class is Class A or Class B, an ADR, GDR, or a business
/// development company (BDC). For preferred stocks, this field provides more detail about the preferred share class.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1013
/// </remarks>
[JsonProperty("1013")]
public string ShareClassDescription { get; set; }
/// <summary>
/// At the ShareClass level; each share is assigned to 1 of 4 possible status classifications; (A) Active, (D) Deactive, (I) Inactive, or (O)
/// Obsolete:
/// - Active-Share class is currently trading in a public market, and we have fundamental data available.
/// - Deactive-Share class was once Active, but is no longer trading due to share being delisted from the exchange.
/// - Inactive-Share class is currently trading in a public market, but no fundamental data is available.
/// - Obsolete-Share class was once Inactive, but is no longer trading due to share being delisted from the exchange.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1014
/// </remarks>
[JsonProperty("1014")]
public string ShareClassStatus { get; set; }
/// <summary>
/// This indicator will denote if the indicated share is the primary share for the company. A "1" denotes the primary share, a "0"
/// denotes a share that is not the primary share. The primary share is defined as the first share that a company IPO'd with and is still
/// actively trading. If this share is no longer trading, we will denote the primary share as the share with the highest volume.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1015
/// </remarks>
[JsonProperty("1015")]
public bool IsPrimaryShare { get; set; }
/// <summary>
/// Shareholder election plan to re-invest cash dividend into additional shares.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1016
/// </remarks>
[JsonProperty("1016")]
public bool IsDividendReinvest { get; set; }
/// <summary>
/// A plan to make it possible for individual investors to invest in public companies without going through a stock broker.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1017
/// </remarks>
[JsonProperty("1017")]
public bool IsDirectInvest { get; set; }
/// <summary>
/// Identifier assigned to each security Morningstar covers.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1018
/// </remarks>
[JsonProperty("1018")]
public string InvestmentId { get; set; }
/// <summary>
/// IPO offer price indicates the price at which an issuer sells its shares under an initial public offering (IPO). The offer price is set by
/// issuer and its underwriters.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1019
/// </remarks>
[JsonProperty("1019")]
public decimal IPOOfferPrice { get; set; }
/// <summary>
/// The date on which an inactive security was delisted from an exchange.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1020
/// </remarks>
[JsonProperty("1020")]
public DateTime DelistingDate { get; set; }
/// <summary>
/// The reason for an inactive security's delisting from an exchange. The full list of Delisting Reason codes can be found within the Data
/// Definitions- Appendix A DelistingReason Codes tab.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1021
/// </remarks>
[JsonProperty("1021")]
public string DelistingReason { get; set; }
/// <summary>
/// The MIC (market identifier code) of the related shareclass of the company. See Data Appendix A for the relevant MIC to exchange
/// name mapping.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1022
/// </remarks>
[JsonProperty("1022")]
public string MIC { get; set; }
/// <summary>
/// Refers to the type of securities that can be found within the equity database. For the vast majority, this value will populate as null
/// for regular common shares. For a minority of shareclasses, this will populate as either "Participating Preferred", "Closed-End Fund",
/// "Foreign Share", or "Foreign Participated Preferred" which reflects our limited coverage of these types of securities within our
/// equity database.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1023
/// </remarks>
[JsonProperty("1023")]
public string CommonShareSubType { get; set; }
/// <summary>
/// The estimated offer price range (low-high) for a new IPO. The field should be used until the final IPO price becomes available, as
/// populated in the data field "IPOPrice".
/// </summary>
/// <remarks>
/// Morningstar DataId: 1024
/// </remarks>
[JsonProperty("1024")]
public string IPOOfferPriceRange { get; set; }
/// <summary>
/// Classification to denote different Marketplace or Market tiers within a stock exchange.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1025
/// </remarks>
[JsonProperty("1025")]
public string ExchangeSubMarketGlobalId { get; set; }
/// <summary>
/// The relationship between the chosen share class and the primary share class.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1026
/// </remarks>
[JsonProperty("1026")]
public decimal ConversionRatio { get; set; }
/// <summary>
/// Nominal value of a security determined by the issuing company.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1027
/// </remarks>
[JsonProperty("1027")]
public decimal ParValue { get; set; }
/// <summary>
/// </summary>
/// <remarks>
/// Morningstar DataId: 1028
/// </remarks>
[JsonProperty("1028")]
public bool TradingStatus { get; set; }
/// <summary>
/// </summary>
/// <remarks>
/// Morningstar DataId: 1029
/// </remarks>
[JsonProperty("1029")]
public string MarketDataID { get; set; }
/// <summary>
/// Creates an instance of the SecurityReference class
/// </summary>
public SecurityReference()
{
}
/// <summary>
/// Applies updated values from <paramref name="update"/> to this instance
/// </summary>
/// <remarks>Used to apply data updates to the current instance. This WILL overwrite existing values. Default update values are ignored.</remarks>
/// <param name="update">The next data update for this instance</param>
public void UpdateValues(SecurityReference update)
{
if (update == null) return;
if (!string.IsNullOrWhiteSpace(update.SecuritySymbol)) SecuritySymbol = update.SecuritySymbol;
if (!string.IsNullOrWhiteSpace(update.ExchangeId)) ExchangeId = update.ExchangeId;
if (!string.IsNullOrWhiteSpace(update.CurrencyId)) CurrencyId = update.CurrencyId;
if (!string.IsNullOrWhiteSpace(update.Valoren)) Valoren = update.Valoren;
if (update.IPODate != default(DateTime)) IPODate = update.IPODate;
if (update.IsDepositaryReceipt != default(bool)) IsDepositaryReceipt = update.IsDepositaryReceipt;
if (update.DepositaryReceiptRatio != default(decimal)) DepositaryReceiptRatio = update.DepositaryReceiptRatio;
if (!string.IsNullOrWhiteSpace(update.SecurityType)) SecurityType = update.SecurityType;
if (!string.IsNullOrWhiteSpace(update.ShareClassDescription)) ShareClassDescription = update.ShareClassDescription;
if (!string.IsNullOrWhiteSpace(update.ShareClassStatus)) ShareClassStatus = update.ShareClassStatus;
if (update.IsPrimaryShare != default(bool)) IsPrimaryShare = update.IsPrimaryShare;
if (update.IsDividendReinvest != default(bool)) IsDividendReinvest = update.IsDividendReinvest;
if (update.IsDirectInvest != default(bool)) IsDirectInvest = update.IsDirectInvest;
if (!string.IsNullOrWhiteSpace(update.InvestmentId)) InvestmentId = update.InvestmentId;
if (update.IPOOfferPrice != default(decimal)) IPOOfferPrice = update.IPOOfferPrice;
if (update.DelistingDate != default(DateTime)) DelistingDate = update.DelistingDate;
if (!string.IsNullOrWhiteSpace(update.DelistingReason)) DelistingReason = update.DelistingReason;
if (!string.IsNullOrWhiteSpace(update.MIC)) MIC = update.MIC;
if (!string.IsNullOrWhiteSpace(update.CommonShareSubType)) CommonShareSubType = update.CommonShareSubType;
if (!string.IsNullOrWhiteSpace(update.IPOOfferPriceRange)) IPOOfferPriceRange = update.IPOOfferPriceRange;
if (!string.IsNullOrWhiteSpace(update.ExchangeSubMarketGlobalId)) ExchangeSubMarketGlobalId = update.ExchangeSubMarketGlobalId;
if (update.ConversionRatio != default(decimal)) ConversionRatio = update.ConversionRatio;
if (update.ParValue != default(decimal)) ParValue = update.ParValue;
if (update.TradingStatus != default(bool)) TradingStatus = update.TradingStatus;
if (!string.IsNullOrWhiteSpace(update.MarketDataID)) MarketDataID = update.MarketDataID;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
namespace System.Transactions
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Serialization not yet supported and will be done using DistributedTransaction")]
public sealed class CommittableTransaction : Transaction, IAsyncResult
{
internal bool _completedSynchronously = false;
// Create a transaction with defaults
public CommittableTransaction() : this(TransactionManager.DefaultIsolationLevel, TransactionManager.DefaultTimeout)
{
}
// Create a transaction with the given info
public CommittableTransaction(TimeSpan timeout) : this(TransactionManager.DefaultIsolationLevel, timeout)
{
}
// Create a transaction with the given options
public CommittableTransaction(TransactionOptions options) : this(options.IsolationLevel, options.Timeout)
{
}
internal CommittableTransaction(IsolationLevel isoLevel, TimeSpan timeout) : base(isoLevel, (InternalTransaction)null)
{
// object to use for synchronization rather than locking on a public object
_internalTransaction = new InternalTransaction(timeout, this);
// Because we passed null for the internal transaction to the base class, we need to
// fill in the traceIdentifier field here.
_internalTransaction._cloneCount = 1;
_cloneId = 1;
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionCreated(this, "CommittableTransaction");
}
}
public IAsyncResult BeginCommit(AsyncCallback asyncCallback, object asyncState)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
etwLog.TransactionCommit(this, "CommittableTransaction");
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(CommittableTransaction));
}
lock (_internalTransaction)
{
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
// this.complete will get set to true when the transaction enters a state that is
// beyond Phase0.
_internalTransaction.State.BeginCommit(_internalTransaction, true, asyncCallback, asyncState);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return this;
}
// Forward the commit to the state machine to take the appropriate action.
//
public void Commit()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
etwLog.TransactionCommit(this, "CommittableTransaction");
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(CommittableTransaction));
}
lock (_internalTransaction)
{
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
_internalTransaction.State.BeginCommit(_internalTransaction, false, null, null);
// now that commit has started wait for the monitor on the transaction to know
// if the transaction is done.
do
{
if (_internalTransaction.State.IsCompleted(_internalTransaction))
{
break;
}
} while (Monitor.Wait(_internalTransaction));
_internalTransaction.State.EndCommit(_internalTransaction);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
internal override void InternalDispose()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Interlocked.Exchange(ref _disposed, Transaction._disposedTrueValue) == Transaction._disposedTrueValue)
{
return;
}
if (_internalTransaction.State.get_Status(_internalTransaction) == TransactionStatus.Active)
{
lock (_internalTransaction)
{
// Since this is the root transaction do state based dispose.
_internalTransaction.State.DisposeRoot(_internalTransaction);
}
}
// Attempt to clean up the internal transaction
long remainingITx = Interlocked.Decrement(ref _internalTransaction._cloneCount);
if (remainingITx == 0)
{
_internalTransaction.Dispose();
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
public void EndCommit(IAsyncResult asyncResult)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (asyncResult != ((object)this))
{
throw new ArgumentException(SR.BadAsyncResult, nameof(asyncResult));
}
lock (_internalTransaction)
{
do
{
if (_internalTransaction.State.IsCompleted(_internalTransaction))
{
break;
}
} while (Monitor.Wait(_internalTransaction));
_internalTransaction.State.EndCommit(_internalTransaction);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
object IAsyncResult.AsyncState => _internalTransaction._asyncState;
bool IAsyncResult.CompletedSynchronously => _completedSynchronously;
WaitHandle IAsyncResult.AsyncWaitHandle
{
get
{
if (_internalTransaction._asyncResultEvent == null)
{
lock (_internalTransaction)
{
if (_internalTransaction._asyncResultEvent == null)
{
// Demand create an event that is already signaled if the transaction has completed.
ManualResetEvent temp = new ManualResetEvent(
_internalTransaction.State.get_Status(_internalTransaction) != TransactionStatus.Active);
_internalTransaction._asyncResultEvent = temp;
}
}
}
return _internalTransaction._asyncResultEvent;
}
}
bool IAsyncResult.IsCompleted
{
get
{
lock (_internalTransaction)
{
return _internalTransaction.State.get_Status(_internalTransaction) != TransactionStatus.Active;
}
}
}
}
}
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Tilde.Framework.Controller;
using Tilde.Framework.View;
using Tilde.Framework.Model;
using System.Text.RegularExpressions;
namespace Tilde.CorePlugins.TextEditor
{
public partial class TextView : Tilde.Framework.View.DocumentView
{
protected TextPlugin mTextPlugin;
protected bool mSaving;
[Flags]
enum CaretPolicy
{
// Caret policy, used by SetXCaretPolicy and SetYCaretPolicy.
// If CARET_SLOP is set, we can define a slop value: caretSlop.
// This value defines an unwanted zone (UZ) where the caret is... unwanted.
// This zone is defined as a number of pixels near the vertical margins,
// and as a number of lines near the horizontal margins.
// By keeping the caret away from the edges, it is seen within its context,
// so it is likely that the identifier that the caret is on can be completely seen,
// and that the current line is seen with some of the lines following it which are
// often dependent on that line.
CARET_SLOP=0x01,
// If CARET_STRICT is set, the policy is enforced... strictly.
// The caret is centred on the display if slop is not set,
// and cannot go in the UZ if slop is set.
CARET_STRICT=0x04,
// If CARET_JUMPS is set, the display is moved more energetically
// so the caret can move in the same direction longer before the policy is applied again.
CARET_JUMPS=0x10,
// If CARET_EVEN is not set, instead of having symmetrical UZs,
// the left and bottom UZs are extended up to right and top UZs respectively.
// This way, we favour the displaying of useful information: the begining of lines,
// where most code reside, and the lines after the caret, eg. the body of a function.
CARET_EVEN=0x08
}
static string [] s_propertiesToForward =
{
"tab.timmy.whinge.level"
};
public TextView(IManager manager, Document doc)
: base(manager, doc)
{
InitializeComponent();
mTextPlugin = (TextPlugin)Manager.GetPlugin(typeof(TextPlugin));
string ext = System.IO.Path.GetExtension(doc.FileName);
if (ext == "")
ext = System.IO.Path.GetFileName(doc.FileName);
else
ext = ext.Substring(1);
string lang = TextPlugin.ScintillaProperties.GetLanguageFromExtension(ext);
if (lang == null)
lang = "txt";
string filepattern = TextPlugin.ScintillaProperties.GetExtensionListFromLanguage(lang);
if (filepattern != null && filepattern.Contains(";"))
filepattern = filepattern.Split(new char[] { ';' }, 2)[0];
scintillaControl.Configuration = new Scintilla.Configuration.ScintillaConfig(TextPlugin.ScintillaProperties, filepattern);
scintillaControl.ConfigurationLanguage = lang;
scintillaControl.UseMonospaceFont(TextPlugin.ScintillaProperties.GetByKey("font.monospace"));
scintillaControl.TabWidth = 4;
scintillaControl.EndOfLineMode = Scintilla.Enums.EndOfLine.LF;
foreach (string param in s_propertiesToForward)
{
if(TextPlugin.ScintillaProperties.ContainsKey(param))
{
scintillaControl.Property(param, TextPlugin.ScintillaProperties[param]);
}
}
mSaving = false;
TextDocument textDoc = Document as TextDocument;
doc.PropertyChange += new PropertyChangeEventHandler(doc_PropertyChange);
doc.Saving += new DocumentSavingEventHandler(doc_Saving);
doc.Saved += new DocumentSavedEventHandler(doc_Saved);
scintillaControl.SetYCaretPolicy((int) (CaretPolicy.CARET_SLOP | CaretPolicy.CARET_STRICT | CaretPolicy.CARET_EVEN), 6);
mTextPlugin.Options.OptionsChanged += new OptionsChangedDelegate(Options_OptionsChanged);
UpdateOptions();
scintillaControl.Text = textDoc.Text;
scintillaControl.EmptyUndoBuffer();
scintillaControl.SetSavePoint();
scintillaControl.ModEventMask = (int) (Scintilla.Enums.ModificationFlags.User | Scintilla.Enums.ModificationFlags.InsertText | Scintilla.Enums.ModificationFlags.DeleteText);
if (textDoc.ReadOnly)
scintillaControl.IsReadOnly = true;
}
void Options_OptionsChanged(IOptions sender, string option)
{
UpdateOptions();
}
void UpdateOptions()
{
scintillaControl.ViewWhitespace = mTextPlugin.Options.Whitespace;
scintillaControl.SetWhiteSpaceForeground(mTextPlugin.Options.WhitespaceForeground.A > 0, mTextPlugin.Options.WhitespaceForeground.R | (mTextPlugin.Options.WhitespaceForeground.G << 8) | (mTextPlugin.Options.WhitespaceForeground.B << 16));
scintillaControl.SetWhiteSpaceBackground(mTextPlugin.Options.WhitespaceBackground.A > 0, mTextPlugin.Options.WhitespaceBackground.R | (mTextPlugin.Options.WhitespaceBackground.G << 8) | (mTextPlugin.Options.WhitespaceBackground.B << 16));
scintillaControl.IsIndentationGuides = mTextPlugin.Options.IndentationGuides;
scintillaControl.HighlightGuide = mTextPlugin.Options.IndentationGuideHighlight ? 1 : 0;
scintillaControl.EdgeMode = (int)mTextPlugin.Options.LineEdgeMode;
scintillaControl.EdgeColumn = mTextPlugin.Options.LineEdgeColumn;
scintillaControl.EdgeColor = mTextPlugin.Options.LineEdgeColor.R | (mTextPlugin.Options.LineEdgeColor.G << 8) | (mTextPlugin.Options.LineEdgeColor.B << 16);
}
public TextView()
{
InitializeComponent();
}
public Scintilla.ScintillaControl ScintillaControl
{
get { return scintillaControl; }
}
public void ShowLine(int line)
{
scintillaControl.EnsureVisible(line - 1);
scintillaControl.GotoLine(line - 1);
}
public void SelectText(int line, int start, int end)
{
int linePos = scintillaControl.PositionFromLine(line - 1);
scintillaControl.SetSelection(linePos + start, linePos + end);
scintillaControl.ScrollCaret();
}
void doc_PropertyChange(object sender, PropertyChangeEventArgs args)
{
if (!mSaving && args.Property == "Text")
{
scintillaControl.IsReadOnly = false;
scintillaControl.Text = (Document as TextDocument).Text;
scintillaControl.EmptyUndoBuffer();
scintillaControl.IsReadOnly = Document.ReadOnly;
}
else if(args.Property == "ReadOnly")
{
scintillaControl.IsReadOnly = Document.ReadOnly;
}
}
void doc_Saving(Document sender)
{
mSaving = true;
try
{
(sender as TextDocument).Text = scintillaControl.Text;
}
finally
{
mSaving = false;
}
}
void doc_Saved(Document sender, bool success)
{
if(success)
scintillaControl.SetSavePoint();
}
protected void MergeMenu(MenuStrip target)
{
foreach(ToolStripMenuItem item in menuStripTextView.Items)
{
foreach(ToolStripMenuItem dest in target.Items)
{
if (item.Text == dest.Text)
{
MergeMenu(item, dest);
}
}
}
}
private void MergeMenu(ToolStripMenuItem source, ToolStripMenuItem dest)
{
while(source.DropDownItems.Count > 0)
{
ToolStripItem item = source.DropDownItems[0];
source.DropDownItems.Remove(item);
dest.DropDownItems.Add(item);
}
}
protected bool ToggleMarker(int marker, int line)
{
int markers = scintillaControl.MarkerGet(line);
if ((markers & (1 << marker)) != 0)
{
scintillaControl.MarkerDelete(line, marker);
return false;
}
else
{
scintillaControl.MarkerAdd(line, marker);
return true;
}
}
private void EditUndoItem_Click(object sender, EventArgs e)
{
scintillaControl.Undo();
}
private void EditRedoItem_Click(object sender, EventArgs e)
{
scintillaControl.Redo();
}
private void EditCutItem_Click(object sender, EventArgs e)
{
scintillaControl.Cut();
}
private void EditCopyItem_Click(object sender, EventArgs e)
{
scintillaControl.Copy();
}
private void EditPasteItem_Click(object sender, EventArgs e)
{
scintillaControl.Paste();
}
private void UpdateMenu()
{
bool isSelection = scintillaControl.SelectionEnd > scintillaControl.SelectionStart;
EditUndoItem.Enabled = scintillaControl.CanUndo;
EditRedoItem.Enabled = scintillaControl.CanRedo;
EditCutItem.Enabled = !scintillaControl.IsReadOnly && isSelection;
EditCopyItem.Enabled = isSelection;
EditPasteItem.Enabled = scintillaControl.CanPaste;
}
private void scintillaControl_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Modifiers & Keys.Control) != 0)
{
if (e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z)
e.SuppressKeyPress = true;
}
}
/// <summary>
/// This notification is sent when the text or styling of the document changes or is about to change.
/// You can set a mask for the notifications that are sent to the container with SCI_SETMODEVENTMASK.
/// The notification structure contains information about what changed, how the change occurred and
/// whether this changed the number of lines in the document. No modifications may be performed while
/// in a SCN_MODIFIED event.
/// </summary>
private void scintillaControl_Modified(object sender, Scintilla.ModifiedEventArgs e)
{
if(this.IsHandleCreated && e.IsUserChange && ((e.ModificationType & (int) Scintilla.Enums.ModificationFlags.ChangeStyle) == 0))
Document.Modified = true;
UpdateMenu();
}
/// <summary>
/// When in read-only mode, this notification is sent to the container if the user tries to change the text.
/// This can be used to check the document out of a version control system.
/// </summary>
private void scintillaControl_ModifyAttemptRO(object sender, Scintilla.ModifyAttemptROEventArgs e)
{
Document.Checkout();
}
private void scintillaControl_SavePointLeft(object sender, Scintilla.SavePointLeftEventArgs e)
{
Document.Modified = true;
}
private void scintillaControl_SavePointReached(object sender, Scintilla.SavePointReachedEventArgs e)
{
Document.Modified = false;
}
/// <summary>
/// Either the text or styling of the document has changed or the selection range has changed.
/// Now would be a good time to update any container UI elements that depend on document or view state.
/// </summary>
private void scintillaControl_UpdateUI(object sender, Scintilla.UpdateUIEventArgs e)
{
UpdateMenu();
}
public void AutoSelect()
{
if (scintillaControl.SelectionStart == scintillaControl.SelectionEnd)
{
int pos = scintillaControl.SelectionStart;
scintillaControl.SelectionStart = scintillaControl.WordStartPosition(pos, true);
scintillaControl.SelectionEnd = scintillaControl.WordEndPosition(pos, true);
}
}
private void EditFindItem_Click(object sender, EventArgs e)
{
AutoSelect();
mTextPlugin.Find(scintillaControl.GetSelectedText());
}
private void EditReplaceItem_Click(object sender, EventArgs e)
{
AutoSelect();
mTextPlugin.Replace(scintillaControl.GetSelectedText());
}
private void EditFindNextItem_Click(object sender, EventArgs e)
{
mTextPlugin.FindNext();
}
private void EditFindPreviousItem_Click(object sender, EventArgs e)
{
mTextPlugin.FindPrevious();
}
private void TextView_Activated(object sender, EventArgs e)
{
}
private void EditGotoLineItem_Click(object sender, EventArgs e)
{
GotoLineForm form = new GotoLineForm(scintillaControl.LineCount);
if (form.ShowDialog(this) == DialogResult.OK)
{
ShowLine(form.Selection);
}
}
}
}
| |
// 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 program was translated to C# and adapted for xunit-performance.
** New variants of several tests were added to compare class versus
** struct and to compare jagged arrays vs multi-dimensional arrays.
*/
/*
** BYTEmark (tm)
** BYTE Magazine's Native Mode benchmarks
** Rick Grehan, BYTE Magazine
**
** Create:
** Revision: 3/95
**
** DISCLAIMER
** The source, executable, and documentation files that comprise
** the BYTEmark benchmarks are made available on an "as is" basis.
** This means that we at BYTE Magazine have made every reasonable
** effort to verify that the there are no errors in the source and
** executable code. We cannot, however, guarantee that the programs
** are error-free. Consequently, McGraw-HIll and BYTE Magazine make
** no claims in regard to the fitness of the source code, executable
** code, and documentation of the BYTEmark.
**
** Furthermore, BYTE Magazine, McGraw-Hill, and all employees
** of McGraw-Hill cannot be held responsible for any damages resulting
** from the use of this code or the results obtained from using
** this code.
*/
using System;
/***********************
** LU DECOMPOSITION **
** (Linear Equations) **
************************
** These routines come from "Numerical Recipes in Pascal".
** Note that, as in the assignment algorithm, though we
** separately define LUARRAYROWS and LUARRAYCOLS, the two
** must be the same value (this routine depends on a square
** matrix).
*/
internal class LUDecomp : LUStruct
{
private const int MAXLUARRAYS = 1000;
private static double[] s_LUtempvv;
public override string Name()
{
return "LU DECOMPOSITION";
}
public override double Run()
{
double[][] a;
double[] b;
double[][][] abase = null;
double[][] bbase = null;
int n;
int i;
long accumtime;
double iterations;
/*
** Our first step is to build a "solvable" problem. This
** will become the "seed" set that all others will be
** derived from. (I.E., we'll simply copy these arrays
** into the others.
*/
a = new double[global.LUARRAYROWS][];
for (int j = 0; j < global.LUARRAYROWS; j++)
{
a[j] = new double[global.LUARRAYCOLS];
}
b = new double[global.LUARRAYROWS];
n = global.LUARRAYROWS;
s_LUtempvv = new double[global.LUARRAYROWS];
build_problem(a, n, b);
if (this.adjust == 0)
{
for (i = 1; i <= MAXLUARRAYS; i++)
{
abase = new double[i + 1][][];
for (int j = 0; j < i + 1; j++)
{
abase[j] = new double[global.LUARRAYROWS][];
for (int k = 0; k < global.LUARRAYROWS; k++)
{
abase[j][k] = new double[global.LUARRAYCOLS];
}
}
bbase = new double[i + 1][];
for (int j = 0; j < i + 1; j++)
{
bbase[j] = new double[global.LUARRAYROWS];
}
if (DoLUIteration(a, b, abase, bbase, i) > global.min_ticks)
{
this.numarrays = i;
break;
}
}
if (this.numarrays == 0)
{
throw new Exception("FPU:LU -- Array limit reached");
}
}
else
{
abase = new double[this.numarrays][][];
for (int j = 0; j < this.numarrays; j++)
{
abase[j] = new double[global.LUARRAYROWS][];
for (int k = 0; k < global.LUARRAYROWS; k++)
{
abase[j][k] = new double[global.LUARRAYCOLS];
}
}
bbase = new double[this.numarrays][];
for (int j = 0; j < this.numarrays; j++)
{
bbase[j] = new double[global.LUARRAYROWS];
}
}
accumtime = 0;
iterations = 0.0;
do
{
accumtime += DoLUIteration(a, b, abase, bbase, this.numarrays);
iterations += (double)this.numarrays;
} while (ByteMark.TicksToSecs(accumtime) < this.request_secs);
if (this.adjust == 0) this.adjust = 1;
return iterations / ByteMark.TicksToFracSecs(accumtime);
}
private static long DoLUIteration(double[][] a, double[] b, double[][][] abase, double[][] bbase, int numarrays)
{
double[][] locabase;
double[] locbbase;
long elapsed;
int k, j, i;
for (j = 0; j < numarrays; j++)
{
locabase = abase[j];
locbbase = bbase[j];
for (i = 0; i < global.LUARRAYROWS; i++)
for (k = 0; k < global.LUARRAYCOLS; k++)
locabase[i][k] = a[i][k];
for (i = 0; i < global.LUARRAYROWS; i++)
locbbase[i] = b[i];
}
elapsed = ByteMark.StartStopwatch();
for (i = 0; i < numarrays; i++)
{
locabase = abase[i];
locbbase = bbase[i];
lusolve(locabase, global.LUARRAYROWS, locbbase);
}
return (ByteMark.StopStopwatch(elapsed));
}
private static void build_problem(double[][] a, int n, double[] b)
{
int i, j, k, k1;
double rcon;
ByteMark.randnum(13);
for (i = 0; i < n; i++)
{
b[i] = (double)(ByteMark.abs_randwc(100) + 1);
for (j = 0; j < n; j++)
if (i == j)
a[i][j] = (double)(ByteMark.abs_randwc(1000) + 1);
else
a[i][j] = (double)0.0;
}
for (i = 0; i < 8 * n; i++)
{
k = ByteMark.abs_randwc(n);
k1 = ByteMark.abs_randwc(n);
if (k != k1)
{
if (k < k1) rcon = 1.0;
else rcon = -1.0;
for (j = 0; j < n; j++)
a[k][j] += a[k1][j] * rcon;
b[k] += b[k1] * rcon;
}
}
}
private static int ludcmp(double[][] a, int n, int[] indx, out int d)
{
double big;
double sum;
double dum;
int i, j, k;
int imax = 0;
double tiny;
tiny = 1.0e-20;
d = 1;
for (i = 0; i < n; i++)
{
big = 0.0;
for (j = 0; j < n; j++)
if (Math.Abs(a[i][j]) > big)
big = Math.Abs(a[i][j]);
if (big == 0.0) return 0;
s_LUtempvv[i] = 1.0 / big;
}
for (j = 0; j < n; j++)
{
if (j != 0)
for (i = 0; i < j; i++)
{
sum = a[i][j];
if (i != 0)
for (k = 0; k < i; k++)
sum -= a[i][k] * a[k][j];
a[i][j] = sum;
}
big = 0.0;
for (i = j; i < n; i++)
{
sum = a[i][j];
if (j != 0)
for (k = 0; k < j; k++)
sum -= a[i][k] * a[k][j];
a[i][j] = sum;
dum = s_LUtempvv[i] * Math.Abs(sum);
if (dum >= big)
{
big = dum;
imax = i;
}
}
if (j != imax)
{
for (k = 0; k < n; k++)
{
dum = a[imax][k];
a[imax][k] = a[j][k];
a[j][k] = dum;
}
d = -d;
dum = s_LUtempvv[imax];
s_LUtempvv[imax] = s_LUtempvv[j];
s_LUtempvv[j] = dum;
}
indx[j] = imax;
if (a[j][j] == 0.0)
a[j][j] = tiny;
if (j != (n - 1))
{
dum = 1.0 / a[j][j];
for (i = j + 1; i < n; i++)
a[i][j] = a[i][j] * dum;
}
}
return 1;
}
private static void lubksb(double[][] a, int n, int[] indx, double[] b)
{
int i, j;
int ip;
int ii;
double sum;
ii = -1;
for (i = 0; i < n; i++)
{
ip = indx[i];
sum = b[ip];
b[ip] = b[i];
if (ii != -1)
for (j = ii; j < i; j++)
sum = sum - a[i][j] * b[j];
else
if (sum != (double)0.0)
ii = i;
b[i] = sum;
}
for (i = (n - 1); i >= 0; i--)
{
sum = b[i];
if (i != (n - 1))
for (j = (i + 1); j < n; j++)
sum = sum - a[i][j] * b[j];
b[i] = sum / a[i][i];
}
}
private static int lusolve(double[][] a, int n, double[] b)
{
int[] indx = new int[global.LUARRAYROWS];
int d;
if (ludcmp(a, n, indx, out d) == 0) return 0;
lubksb(a, n, indx, b);
return 1;
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk.Khronos
{
/// <summary>
/// Structure specifying parameters of a newly created swapchain object.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public partial struct SwapchainCreateInfo
{
/// <summary>
/// A bitmask indicating parameters of swapchain creation. Bits which
/// can be set include: + --
/// </summary>
public SharpVk.Khronos.SwapchainCreateFlags? Flags
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.Khronos.Surface Surface
{
get;
set;
}
/// <summary>
///
/// </summary>
public uint MinImageCount
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.Format ImageFormat
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.Khronos.ColorSpace ImageColorSpace
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.Extent2D ImageExtent
{
get;
set;
}
/// <summary>
///
/// </summary>
public uint ImageArrayLayers
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.ImageUsageFlags ImageUsage
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.SharingMode ImageSharingMode
{
get;
set;
}
/// <summary>
///
/// </summary>
public uint[] QueueFamilyIndices
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.Khronos.SurfaceTransformFlags PreTransform
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.Khronos.CompositeAlphaFlags CompositeAlpha
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.Khronos.PresentMode PresentMode
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool Clipped
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.Khronos.Swapchain OldSwapchain
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <param name="pointer">
/// </param>
internal unsafe void MarshalTo(SharpVk.Interop.Khronos.SwapchainCreateInfo* pointer)
{
pointer->SType = StructureType.SwapchainCreateInfo;
pointer->Next = null;
if (this.Flags != null)
{
pointer->Flags = this.Flags.Value;
}
else
{
pointer->Flags = default(SharpVk.Khronos.SwapchainCreateFlags);
}
pointer->Surface = this.Surface?.handle ?? default(SharpVk.Interop.Khronos.Surface);
pointer->MinImageCount = this.MinImageCount;
pointer->ImageFormat = this.ImageFormat;
pointer->ImageColorSpace = this.ImageColorSpace;
pointer->ImageExtent = this.ImageExtent;
pointer->ImageArrayLayers = this.ImageArrayLayers;
pointer->ImageUsage = this.ImageUsage;
pointer->ImageSharingMode = this.ImageSharingMode;
pointer->QueueFamilyIndexCount = (uint)(Interop.HeapUtil.GetLength(this.QueueFamilyIndices));
if (this.QueueFamilyIndices != null)
{
var fieldPointer = (uint*)(Interop.HeapUtil.AllocateAndClear<uint>(this.QueueFamilyIndices.Length).ToPointer());
for(int index = 0; index < (uint)(this.QueueFamilyIndices.Length); index++)
{
fieldPointer[index] = this.QueueFamilyIndices[index];
}
pointer->QueueFamilyIndices = fieldPointer;
}
else
{
pointer->QueueFamilyIndices = null;
}
pointer->PreTransform = this.PreTransform;
pointer->CompositeAlpha = this.CompositeAlpha;
pointer->PresentMode = this.PresentMode;
pointer->Clipped = this.Clipped;
pointer->OldSwapchain = this.OldSwapchain?.handle ?? default(SharpVk.Interop.Khronos.Swapchain);
}
}
}
| |
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/**
* Namespace: System.Web.UI.WebControls
* Class: PagedDataSource
*
* Author: Gaurav Vaish
* Maintainer: [email protected]
* Contact: <[email protected]>, <[email protected]>
* Implementation: yes
* Status: 100%
*
* (C) Gaurav Vaish (2002)
*/
using System;
using System.ComponentModel;
using System.Collections;
using System.Web;
using System.Web.UI;
namespace System.Web.UI.WebControls
{
public sealed class PagedDataSource : ICollection, IEnumerable, ITypedList
{
private int pageSize;
private bool allowPaging;
private int currentPageIndex;
private bool allowCustomPaging;
private int virtualCount;
#if NET_2_0
DataSourceSelectArguments arguments;
DataSourceView view;
bool serverPaging;
#endif
private IEnumerable dataSource;
public PagedDataSource()
{
Initialize();
}
private void Initialize()
{
pageSize = 10;
allowPaging = false;
currentPageIndex = 0;
allowCustomPaging = false;
virtualCount = 0;
}
#if NET_2_0
public DataSourceSelectArguments DataSourceSelectArguments {
get { return arguments; }
set { arguments = value; }
}
public DataSourceView DataSourceView {
get { return view; }
set { view = value; }
}
public bool AllowServerPaging {
get { return serverPaging; }
set { serverPaging = value; }
}
public bool IsServerPagingEnabled {
get { return allowPaging && serverPaging; }
}
public void SetItemCountFromPageIndex (int highestPageIndex)
{
arguments.StartRowIndex = CurrentPageIndex * PageSize;
arguments.MaximumRows = (highestPageIndex - CurrentPageIndex) * PageSize + 1;
IEnumerable data = view.ExecuteSelect (arguments);
virtualCount = CurrentPageIndex * PageSize;
if (data is ICollection) {
virtualCount += ((ICollection)data).Count;
} else {
IEnumerator e = data.GetEnumerator ();
while (e.MoveNext())
virtualCount++;
}
}
#endif
public bool AllowCustomPaging
{
get
{
return allowCustomPaging;
}
set
{
allowCustomPaging = value;
}
}
public bool AllowPaging
{
get
{
return allowPaging;
}
set
{
allowPaging = value;
}
}
public int Count
{
get
{
if(dataSource != null)
{
if(!IsPagingEnabled)
{
return DataSourceCount;
}
if(IsCustomPagingEnabled)
{
return pageSize;
}
if(IsLastPage)
{
int n = DataSourceCount;
if (n == 0) return 0;
else return (n - FirstIndexInPage);
}
return pageSize;
}
return 0;
}
}
public int CurrentPageIndex
{
get
{
return currentPageIndex;
}
set
{
currentPageIndex = value;
}
}
public IEnumerable DataSource
{
get
{
return dataSource;
}
set
{
dataSource = value;
}
}
public int DataSourceCount
{
get
{
if(dataSource != null)
{
#if NET_2_0
if (serverPaging)
{
return virtualCount;
}
#endif
if(IsCustomPagingEnabled)
{
return virtualCount;
}
if(dataSource is ICollection)
{
return ((ICollection)dataSource).Count;
}
throw new HttpException(HttpRuntime.FormatResourceString("PagedDataSource_Cannot_Get_Count"));
}
return 0;
}
}
public int FirstIndexInPage
{
get
{
if(dataSource != null && IsPagingEnabled && !IsCustomPagingEnabled)
{
return (currentPageIndex * pageSize);
}
return 0;
}
}
public bool IsCustomPagingEnabled
{
get
{
return (IsPagingEnabled && allowCustomPaging);
}
}
public bool IsFirstPage
{
get
{
return (!IsPagingEnabled || (CurrentPageIndex == 0));
}
}
public bool IsLastPage
{
get
{
return (!IsPagingEnabled || (CurrentPageIndex == (PageCount - 1)) || PageCount <= 1);
}
}
public bool IsPagingEnabled
{
get
{
return (allowPaging && pageSize != 0);
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public int PageCount
{
get
{
if(dataSource != null) {
if(!IsPagingEnabled)
return 1;
int total = (DataSourceCount + pageSize - 1) / pageSize;
return (total > 0 ? total : 1);
}
return 0;
}
}
public int PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
}
}
public object SyncRoot
{
get
{
return this;
}
}
public int VirtualCount
{
get
{
return virtualCount;
}
set
{
virtualCount = value;
}
}
public void CopyTo(Array array, int index)
{
IEnumerator enumerator = this.GetEnumerator();
if(enumerator == null) return;
while(enumerator.MoveNext())
array.SetValue(enumerator.Current, index++);
}
public IEnumerator GetEnumerator()
{
#if NET_2_0
int fInd = serverPaging ? 0 : FirstIndexInPage;
#else
int fInd = FirstIndexInPage;
#endif
int count = -1;
if(dataSource is ICollection)
{
count = Count;
}
if(dataSource is IList)
{
return (new PrivateListEnumerator((IList)dataSource, fInd, count));
}
if(dataSource is Array)
{
return (new PrivateArrayEnumerator((object[])dataSource, fInd, count));
}
if(dataSource is ICollection)
{
return (new PrivateICollectionEnumerator((ICollection)dataSource, fInd, count));
}
if(allowCustomPaging)
{
return (new PrivateIEnumeratorEnumerator(dataSource.GetEnumerator(), Count));
}
return dataSource.GetEnumerator();
}
class PrivateIEnumeratorEnumerator : IEnumerator
{
private int index;
private int max;
private IEnumerator enumerator;
public PrivateIEnumeratorEnumerator(IEnumerator enumerator, int count)
{
this.enumerator = enumerator;
index = -1;
max = count;
}
public bool MoveNext()
{
enumerator.MoveNext();
index++;
return (index < max);
}
public void Reset()
{
index = -1;
enumerator.Reset();
}
public object Current
{
get
{
return enumerator.Current;
}
}
}
class PrivateICollectionEnumerator : IEnumerator
{
private int index;
private int start;
private int max;
private ICollection collection;
private IEnumerator collEnum;
public PrivateICollectionEnumerator(ICollection collection, int start, int count)
{
this.collection = collection;
this.start = start;
index = -1;
max = start + count;
if(max > collection.Count)
{
max = collection.Count;
}
}
public bool MoveNext()
{
if(collEnum == null)
{
int cIndex = 0;
collEnum = collection.GetEnumerator();
while(cIndex < start)
{
collEnum.MoveNext();
cIndex++;
}
}
collEnum.MoveNext();
index++;
return (start + index < max);
}
public void Reset()
{
index = -1;
collEnum = null;
}
public object Current
{
get
{
return collEnum.Current;
}
}
}
class PrivateArrayEnumerator : IEnumerator
{
private int index;
private int start;
private int max;
private object[] values;
public PrivateArrayEnumerator(object[] values, int start, int count)
{
this.values = values;
this.start = start;
index = -1;
max = start + count;
if(max > this.values.Length)
{
max = this.values.Length;
}
}
public bool MoveNext()
{
index++;
return (index + start < max);
}
public void Reset()
{
index = -1;
}
public object Current
{
get
{
if(index >= 0)
{
return values[index + start];
}
throw new InvalidOperationException("Enumerator_MoveNext_Not_Called");
}
}
}
class PrivateListEnumerator : IEnumerator
{
private int index;
private int start;
private int max;
private IList collection;
public PrivateListEnumerator(IList list, int start, int count)
{
collection = list;
this.start = start;
index = -1;
max = start + count;
if(max > list.Count)
{
max = list.Count;
}
}
public bool MoveNext()
{
index++;
return (index + start < max);
}
public void Reset()
{
index = -1;
}
public object Current
{
get
{
if(index >= 0)
{
return collection[index + start];
}
throw new InvalidOperationException("Enumerator_MoveNext_Not_Called");
}
}
}
public string GetListName(PropertyDescriptor[] listAccessors)
{
return String.Empty;
}
public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
{
if(dataSource != null)
{
if(dataSource is ITypedList)
{
return ((ITypedList)dataSource).GetItemProperties(listAccessors);
}
}
return null;
}
}
}
| |
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.TestHooks;
using Orleans.TestingHost;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Tester;
using TestExtensions;
using UnitTests;
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())
{
this.HostedCluster.RestartSilo(silo);
}
this.HostedCluster.InitializeClient();
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}");
}
}
#region Utility functions
// ---------- 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);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
public class Fog : MonoBehaviour {
// This is the basis script of the fog of war system
// Without this, the VisionSignal, VisionBlocker, and VisionReceiver scripts won't do anything
// This should be set to the fill up the overall size of your map
// Width and Length will be the size of the fog texture you want
// While the displacement is used to fill in the rest
// Ex. if you have a map that is 500x500, and want your fog texture to be 100x100, the disp will be 5
public int width = 0;
public int length = 0;
public int disp = 0;
// You will niot directly access these, however these lists keep track of your units on the screen
List<GameObject> agents = new List<GameObject>(0);
List<int> agentsRadius = new List<int>(0);
int agentsAmount = 0;
// Much like the above lists, this keeps track of the objects you want hidden
List<GameObject> hiddenAgent = new List<GameObject>(0);
List<VisionReceiver> hiddenRend = new List<VisionReceiver>(0);
int[] hideSetting;
int hideAmount = 0;
// The fog variable is the texture you are actually modifying for the fog system
Texture2D fog;
int[] fogState = new int[0];
public Vector3 startPos = Vector3.zero;
Color32[] fogColor;
int[] fogHeight;
Vector3[] locA;
Vector3[] locH;
[HideInInspector]
public MiniMap map;
public Color revealed;
public Color visited;
public Color hidden;
public Material terrainMat;
public Texture transparentTexture;
bool[][] visitedPoints;
public int blendRate = 5;
bool funActive = false;
void OnDrawGizmos () {
// This is required so that the terrain's mat will be reset after the game ends. This is only for Unity testing issues
if (!Application.isPlaying)
if(terrainMat != null)
terrainMat.SetTexture("_FOWTex", transparentTexture);
if(gameObject.name != "Fog")
gameObject.name = "Fog";
}
// Use this for initialization
void Awake () {
fog = new Texture2D(width, length, TextureFormat.ARGB32, false);
fogColor = new Color32[width*length];
for(int x = 0; x < width; x++){
for(int y = 0; y < length; y++){
fog.SetPixel(x, y, hidden);
fogColor[x+y*width] = hidden;
}
}
fog.Apply();
if(map == null){
GameObject obj = GameObject.Find("MiniMap");
if(obj)
map = obj.GetComponent<MiniMap>();
}
if(map){
map.fogTexture = fog;
}
terrainMat.SetTexture("_FOWTex", fog);
fogState = new int[width*length];
fogHeight = new int[width*length];
}
// Fixed Update runs less than Update
void FixedUpdate () {
// If the function is already running then we don't need to run another function
if(!funActive)
UpdateFog();
}
// The main fog function, it is executed whenever the thread is clear
void UpdateFog () {
locA = new Vector3[agentsAmount];
for(int x = 0; x < agentsAmount; x++){
if(agents[x] == null){
agents.RemoveAt(x);
agentsRadius.RemoveAt(x);
agentsAmount--;
x--;
}
locA[x] = agents[x].transform.position;
}
locH = new Vector3[hideAmount];
for(int x = 0; x < hideAmount; x++){
if(hiddenAgent[x] == null){
hiddenAgent.RemoveAt(x);
hiddenRend.RemoveAt(x);
hideAmount--;
x--;
}
locH[x] = hiddenAgent[x].transform.position;
}
// MultiThreaded request. This keeps the many processes off the main thread and runs them in the background
ThreadPool.QueueUserWorkItem(new WaitCallback(ModifyFog));
// Finally, we set and apply the new colors to the fog texture
fog.SetPixels32(fogColor);
fog.Apply(false);
// And we set the hidden objects
for(int x = 0; x < hideAmount; x++){
hiddenRend[x].SetRenderer(hideSetting[x]);
}
}
void ModifyFog (object obj) {
funActive = true;
int[] fogVision = new int[fogColor.Length];
Color32[] fColor = new Color32[fogColor.Length];
for(int x = 0; x < fogColor.Length; x++){
if(fogColor[x] == revealed){
fogVision[x] = 0;
Color tColor = fogColor[x];
tColor[3] += (0.003921568627451f)*blendRate;
fColor[x] = tColor;
Color visitedColor = visited;
if(tColor[3] > visitedColor[3]){
fColor[x] = visited;
}
}
else if(fogColor[x] == hidden){
fogVision[x] = 2;
fColor[x] = hidden;
}
else{
fogVision[x] = 1;
Color tColor = fogColor[x];
tColor[3] += (0.003921568627451f)*blendRate;
fColor[x] = tColor;
Color visitedColor = visited;
if(tColor[3] > visitedColor[3]){
fColor[x] = visited;
}
}
}
for(int x = 0; x < agentsAmount; x++){
if(x < locA.Length){
Vector2 loc = DetermineLoc(locA[x]);
int rad = agentsRadius[x];
int locX = (int)loc.x;
int locY = (int)loc.y;
for(int z = -agentsRadius[x]; z <= agentsRadius[x]; z++){
line(locX, locY, locX+z, locY-rad, rad, ref fogVision, ref fColor);
line(locX, locY, locX+z, locY+rad, rad, ref fogVision, ref fColor);
line(locX, locY, locX-rad, locY+z, rad, ref fogVision, ref fColor);
line(locX, locY, locX+rad, locY+z, rad, ref fogVision, ref fColor);
}
}
}
fogColor = fColor;
CheckRenderer(fogVision);
funActive = false;
}
// Bresenham's Line Algorithm at work for shadow casting
void line(int x,int y,int x2, int y2, int radius, ref int[] fogVision, ref Color32[] fColor) {
int orPosX = x;
int orPosY = y;
int w = x2 - x ;
int h = y2 - y ;
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ;
if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ;
if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ;
int longest = Mathf.Abs(w) ;
int shortest = Mathf.Abs(h) ;
if (!(longest>shortest)) {
longest = Mathf.Abs(h) ;
shortest = Mathf.Abs(w) ;
if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ;
dx2 = 0 ;
}
int numerator = longest >> 1 ;
for (int i=0;i<=longest;i++) {
float dist = new Vector2(orPosX-x, orPosY-y).sqrMagnitude;
if(x < width && x >= 0){
if(x+y*width > 0 && x+y*width < fogHeight.Length){
if(fogHeight[x+y*width] == 0 && dist < radius*radius-2){
fogVision[x+y*width] = 0;
fColor[x+y*width] = LerpColor(fogColor[x+y*width]);
}
else if(fogHeight[x+y*width] == -1){
fogVision[x+y*width] = 0;
fColor[x+y*width] = LerpColor(fogColor[x+y*width]);
break;
}
else{
break;
}
}
}
numerator += shortest ;
if (!(numerator<longest)) {
numerator -= longest ;
x += dx1 ;
y += dy1 ;
} else {
x += dx2 ;
y += dy2 ;
}
}
}
// A function to lerp the alpha values between two colors for the fade effect
Color32 LerpColor (Color32 curColor) {
Color tColor = curColor;
tColor[3] -= (0.003921568627451f)*blendRate;
Color32 rColor = tColor;
Color visitedColor = revealed;
if(tColor[3] < visitedColor[3]){
rColor = revealed;
}
return rColor;
}
void CheckRenderer (int[] fogVision) {
for(int x = 0; x < hideAmount; x++){
if(x < locH.Length){
Vector2 loc = DetermineLoc(locH[x]);
hideSetting[x] = fogVision[(int)(loc.x+loc.y*width)];
}
}
}
public void AddAgent (GameObject obj, int sight, VisionSignal signal){
agents.Add(obj);
agentsRadius.Add(sight);
agentsAmount++;
}
public void ClosePoints (int range, Vector3 loc3d){
Vector2 loc = DetermineLoc(loc3d);
fogHeight[(int)loc.x+((int)loc.y)*width] = -1;
for(int x = -range; x < range; x++){
for(int y = -range; y < range; y++){
float dist = Mathf.Sqrt((x)*(x)+(y)*(y));
if(dist <= range){
fogHeight[(int)loc.x+x+((int)loc.y+y)*width] = -1;
}
}
}
}
public void AddRenderer (GameObject obj, VisionReceiver receiver){
hiddenAgent.Add(obj);
hiddenRend.Add(receiver);
hideSetting = new int[hideAmount+1];
hideAmount++;
}
Vector2 DetermineLoc (Vector3 loc) {
float xLoc = (loc.x-startPos.x);
float yLoc = (loc.z-startPos.z);
int x = Mathf.RoundToInt(xLoc/disp);
int y = Mathf.RoundToInt(yLoc/disp);
Vector2 nLoc = new Vector2(x,y);
return nLoc;
}
public bool CheckLocation (Vector3 loc){
Vector2 point = DetermineLoc(loc);
if(fogColor[(int)point.x+((int)point.y)*width] == hidden){
return false;
}
else{
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Transactions.Tests
{
// Ported from Mono
public class TransactionScopeTest
{
[Fact]
public void TransactionScopeWithInvalidTimeSpanThrows()
{
Assert.Throws<ArgumentNullException>("transactionToUse", () => new TransactionScope(null, TimeSpan.FromSeconds(-1)));
Assert.Throws<ArgumentOutOfRangeException>("scopeTimeout", () => new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(-1)));
}
[Fact]
public void TransactionScopeCommit()
{
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
Assert.NotNull(Transaction.Current);
Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status);
scope.Complete();
}
Assert.Null(Transaction.Current);
}
[Fact]
public void TransactionScopeAbort()
{
Assert.Null(Transaction.Current);
IntResourceManager irm = new IntResourceManager(1);
using (TransactionScope scope = new TransactionScope())
{
Assert.NotNull(Transaction.Current);
Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status);
irm.Value = 2;
/* Not completing scope here */
}
irm.Check(0, 0, 1, 0, "irm");
Assert.Equal(1, irm.Value);
Assert.Null(Transaction.Current);
}
[Fact]
public void TransactionScopeCompleted1()
{
Assert.Throws<InvalidOperationException>(() =>
{
using (TransactionScope scope = new TransactionScope())
{
scope.Complete();
/* Can't access ambient transaction after scope.Complete */
TransactionStatus status = Transaction.Current.TransactionInformation.Status;
}
});
}
[Fact]
public void TransactionScopeCompleted2()
{
using (TransactionScope scope = new TransactionScope())
{
scope.Complete();
Assert.Throws<InvalidOperationException>(() =>
{
Transaction.Current = Transaction.Current;
});
}
}
[Fact]
public void TransactionScopeCompleted3()
{
Assert.Throws<InvalidOperationException>(() =>
{
using (TransactionScope scope = new TransactionScope())
{
scope.Complete();
scope.Complete();
}
});
}
#region NestedTransactionScope tests
[Fact]
public void NestedTransactionScope1()
{
IntResourceManager irm = new IntResourceManager(1);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
/* Complete this scope */
scope.Complete();
}
Assert.Null(Transaction.Current);
/* Value = 2, got committed */
Assert.Equal(irm.Value, 2);
irm.Check(1, 1, 0, 0, "irm");
}
[Fact]
public void NestedTransactionScope2()
{
IntResourceManager irm = new IntResourceManager(1);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
/* Not-Completing this scope */
}
Assert.Null(Transaction.Current);
/* Value = 2, got rolledback */
Assert.Equal(irm.Value, 1);
irm.Check(0, 0, 1, 0, "irm");
}
[Fact]
public void NestedTransactionScope3()
{
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(10);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope())
{
irm2.Value = 20;
scope2.Complete();
}
scope.Complete();
}
Assert.Null(Transaction.Current);
/* Both got committed */
Assert.Equal(irm.Value, 2);
Assert.Equal(irm2.Value, 20);
irm.Check(1, 1, 0, 0, "irm");
irm2.Check(1, 1, 0, 0, "irm2");
}
[Fact]
public void NestedTransactionScope4()
{
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(10);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope())
{
irm2.Value = 20;
/* Inner Tx not completed, Tx should get rolled back */
//scope2.Complete();
}
/* Both rolledback */
irm.Check(0, 0, 1, 0, "irm");
irm2.Check(0, 0, 1, 0, "irm2");
Assert.Equal(TransactionStatus.Aborted, Transaction.Current.TransactionInformation.Status);
//scope.Complete ();
}
Assert.Null(Transaction.Current);
Assert.Equal(irm.Value, 1);
Assert.Equal(irm2.Value, 10);
irm.Check(0, 0, 1, 0, "irm");
}
[Fact]
public void NestedTransactionScope5()
{
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(10);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope())
{
irm2.Value = 20;
scope2.Complete();
}
Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status);
/* Not completing outer scope
scope.Complete (); */
}
Assert.Null(Transaction.Current);
Assert.Equal(irm.Value, 1);
Assert.Equal(irm2.Value, 10);
irm.Check(0, 0, 1, 0, "irm");
irm2.Check(0, 0, 1, 0, "irm2");
}
[Fact]
public void NestedTransactionScope6()
{
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(10);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew))
{
irm2.Value = 20;
scope2.Complete();
}
/* vr2, committed */
irm2.Check(1, 1, 0, 0, "irm2");
Assert.Equal(irm2.Value, 20);
Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status);
scope.Complete();
}
Assert.Null(Transaction.Current);
Assert.Equal(irm.Value, 2);
irm.Check(1, 1, 0, 0, "irm");
}
[Fact]
public void NestedTransactionScope7()
{
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(10);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew))
{
irm2.Value = 20;
/* Not completing
scope2.Complete();*/
}
/* irm2, rolled back*/
irm2.Check(0, 0, 1, 0, "irm2");
Assert.Equal(irm2.Value, 10);
Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status);
scope.Complete();
}
Assert.Null(Transaction.Current);
/* ..But irm got committed */
Assert.Equal(irm.Value, 2);
irm.Check(1, 1, 0, 0, "irm");
}
[Fact]
public void NestedTransactionScope8()
{
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(10);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress))
{
/* Not transactional, so this WON'T get committed */
irm2.Value = 20;
scope2.Complete();
}
irm2.Check(0, 0, 0, 0, "irm2");
Assert.Equal(20, irm2.Value);
Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status);
scope.Complete();
}
Assert.Null(Transaction.Current);
Assert.Equal(irm.Value, 2);
irm.Check(1, 1, 0, 0, "irm");
}
[Fact]
public void NestedTransactionScope8a()
{
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(10);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope())
{
irm2.Value = 20;
scope2.Complete();
}
irm2.Check(1, 1, 0, 0, "irm2");
Assert.Equal(20, irm2.Value);
scope.Complete();
}
Assert.Null(Transaction.Current);
Assert.Equal(2, irm.Value);
irm.Check(0, 0, 0, 0, "irm");
}
[Fact]
public void NestedTransactionScope9()
{
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(10);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress))
{
/* Not transactional, so this WON'T get committed */
irm2.Value = 4;
scope2.Complete();
}
irm2.Check(0, 0, 0, 0, "irm2");
using (TransactionScope scope3 = new TransactionScope(TransactionScopeOption.RequiresNew))
{
irm.Value = 6;
scope3.Complete();
}
/* vr's value has changed as the inner scope committed = 6 */
irm.Check(1, 1, 0, 0, "irm");
Assert.Equal(irm.Value, 6);
Assert.Equal(irm.Actual, 6);
Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status);
scope.Complete();
}
Assert.Null(Transaction.Current);
Assert.Equal(irm.Value, 6);
irm.Check(2, 2, 0, 0, "irm");
}
[Fact]
public void NestedTransactionScope10()
{
Assert.Throws<TransactionAbortedException>(() =>
{
IntResourceManager irm = new IntResourceManager(1);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope())
{
irm.Value = 4;
/* Not completing this, so the transaction will
* get aborted
scope2.Complete (); */
}
using (TransactionScope scope3 = new TransactionScope())
{
/* Aborted transaction cannot be used for another
* TransactionScope
*/
}
}
});
}
[Fact]
public void NestedTransactionScope12()
{
IntResourceManager irm = new IntResourceManager(1);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope())
{
irm.Value = 4;
/* Not completing this, so the transaction will
* get aborted
scope2.Complete (); */
}
using (TransactionScope scope3 = new TransactionScope(TransactionScopeOption.RequiresNew))
{
/* Using RequiresNew here, so outer transaction
* being aborted doesn't matter
*/
scope3.Complete();
}
}
}
[Fact]
public void NestedTransactionScope13()
{
Assert.Throws<TransactionAbortedException>(() =>
{
IntResourceManager irm = new IntResourceManager(1);
Assert.Null(Transaction.Current);
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
using (TransactionScope scope2 = new TransactionScope())
{
irm.Value = 4;
/* Not completing this, so the transaction will
* get aborted
scope2.Complete (); */
}
scope.Complete();
}
});
}
#endregion
/* Tests using IntResourceManager */
[Fact]
public void RMFail1()
{
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(10);
IntResourceManager irm3 = new IntResourceManager(12);
Assert.Null(Transaction.Current);
try
{
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
irm2.Value = 20;
irm3.Value = 24;
/* Make second RM fail to prepare, this should throw
* TransactionAbortedException when the scope ends
*/
irm2.FailPrepare = true;
scope.Complete();
}
}
catch (TransactionAbortedException)
{
irm.Check(1, 0, 1, 0, "irm");
irm2.Check(1, 0, 0, 0, "irm2");
irm3.Check(0, 0, 1, 0, "irm3");
}
Assert.Null(Transaction.Current);
}
[Fact]
[OuterLoop] // 30 second timeout
public void RMFail2()
{
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(10);
IntResourceManager irm3 = new IntResourceManager(12);
Assert.Null(Transaction.Current);
TransactionAbortedException e = Assert.Throws<TransactionAbortedException>(() =>
{
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 0, 10)))
{
irm.Value = 2;
irm2.Value = 20;
irm3.Value = 24;
/* irm2 won't call Prepared or ForceRollback in
* its Prepare (), so TransactionManager will timeout
* waiting for it
*/
irm2.IgnorePrepare = true;
scope.Complete();
}
});
Assert.NotNull(e.InnerException);
Assert.IsType<TimeoutException>(e.InnerException);
Assert.Null(Transaction.Current);
}
#region Explicit Transaction Tests
[Fact]
public void ExplicitTransactionCommit()
{
Assert.Null(Transaction.Current);
CommittableTransaction ct = new CommittableTransaction();
Transaction oldTransaction = Transaction.Current;
Transaction.Current = ct;
IntResourceManager irm = new IntResourceManager(1);
irm.Value = 2;
ct.Commit();
Assert.Equal(2, irm.Value);
Assert.Equal(TransactionStatus.Committed, ct.TransactionInformation.Status);
Transaction.Current = oldTransaction;
}
[Fact]
public void ExplicitTransactionRollback()
{
Assert.Null(Transaction.Current);
CommittableTransaction ct = new CommittableTransaction();
Transaction oldTransaction = Transaction.Current;
Transaction.Current = ct;
try
{
IntResourceManager irm = new IntResourceManager(1);
irm.Value = 2;
Assert.Equal(TransactionStatus.Active, ct.TransactionInformation.Status);
ct.Rollback();
Assert.Equal(1, irm.Value);
Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status);
}
finally
{
Transaction.Current = oldTransaction;
}
}
[Fact]
public void ExplicitTransaction1()
{
Assert.Null(Transaction.Current);
CommittableTransaction ct = new CommittableTransaction();
Transaction oldTransaction = Transaction.Current;
Transaction.Current = ct;
try
{
IntResourceManager irm = new IntResourceManager(1);
irm.Value = 2;
using (TransactionScope scope = new TransactionScope())
{
Assert.Equal(ct, Transaction.Current);
irm.Value = 4;
scope.Complete();
}
Assert.Equal(ct, Transaction.Current);
Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status);
Assert.Equal(1, irm.Actual);
ct.Commit();
Assert.Equal(4, irm.Actual);
Assert.Equal(TransactionStatus.Committed, Transaction.Current.TransactionInformation.Status);
}
finally
{
Transaction.Current = oldTransaction;
}
}
[Fact]
public void ExplicitTransaction2()
{
Assert.Null(Transaction.Current);
CommittableTransaction ct = new CommittableTransaction();
Transaction oldTransaction = Transaction.Current;
Transaction.Current = ct;
try
{
IntResourceManager irm = new IntResourceManager(1);
irm.Value = 2;
using (TransactionScope scope = new TransactionScope())
{
Assert.Equal(ct, Transaction.Current);
/* Not calling scope.Complete
scope.Complete ();*/
}
Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status);
Assert.Equal(ct, Transaction.Current);
Assert.Equal(1, irm.Actual);
Assert.Equal(1, irm.NumRollback);
irm.Check(0, 0, 1, 0, "irm");
}
finally
{
Transaction.Current = oldTransaction;
}
Assert.Throws<TransactionAbortedException>(() => ct.Commit());
}
[Fact]
public void ExplicitTransaction3()
{
Assert.Null(Transaction.Current);
CommittableTransaction ct = new CommittableTransaction();
Transaction oldTransaction = Transaction.Current;
Transaction.Current = ct;
try
{
IntResourceManager irm = new IntResourceManager(1);
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
Assert.True(ct != Transaction.Current, "Scope with RequiresNew should have a new ambient transaction");
irm.Value = 3;
scope.Complete();
}
irm.Value = 2;
Assert.Equal(3, irm.Actual);
Assert.Equal(ct, Transaction.Current);
ct.Commit();
Assert.Equal(2, irm.Actual);
}
finally
{
Transaction.Current = oldTransaction;
}
}
[Fact]
public void ExplicitTransaction4()
{
Assert.Null(Transaction.Current);
CommittableTransaction ct = new CommittableTransaction();
Transaction oldTransaction = Transaction.Current;
/* Not setting ambient transaction
Transaction.Current = ct;
*/
IntResourceManager irm = new IntResourceManager(1);
using (TransactionScope scope = new TransactionScope(ct))
{
Assert.Equal(ct, Transaction.Current);
irm.Value = 2;
scope.Complete();
}
Assert.Equal(oldTransaction, Transaction.Current);
Assert.Equal(TransactionStatus.Active, ct.TransactionInformation.Status);
Assert.Equal(1, irm.Actual);
ct.Commit();
Assert.Equal(2, irm.Actual);
Assert.Equal(TransactionStatus.Committed, ct.TransactionInformation.Status);
irm.Check(1, 1, 0, 0, "irm");
}
[Fact]
public void ExplicitTransaction5()
{
Assert.Null(Transaction.Current);
CommittableTransaction ct = new CommittableTransaction();
Transaction oldTransaction = Transaction.Current;
/* Not setting ambient transaction
Transaction.Current = ct;
*/
IntResourceManager irm = new IntResourceManager(1);
using (TransactionScope scope = new TransactionScope(ct))
{
Assert.Equal(ct, Transaction.Current);
irm.Value = 2;
/* Not completing this scope
scope.Complete (); */
}
Assert.Equal(oldTransaction, Transaction.Current);
Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status);
Assert.Equal(1, irm.Actual);
irm.Check(0, 0, 1, 0, "irm");
}
[Fact]
public void ExplicitTransaction6()
{
Assert.Throws<InvalidOperationException>(() =>
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
irm.Value = 2;
ct.Commit();
ct.Commit();
});
}
[Fact]
public void ExplicitTransaction6a()
{
Assert.Throws<InvalidOperationException>(() =>
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
irm.Value = 2;
ct.Commit();
/* Using a already committed transaction in a new
* TransactionScope
*/
TransactionScope scope = new TransactionScope(ct);
});
}
[Fact]
public void ExplicitTransaction6b()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
Transaction.Current = ct;
try
{
TransactionScope scope1 = new TransactionScope();
/* Enlist */
irm.Value = 2;
scope1.Complete();
Assert.Throws<TransactionAbortedException>(() => ct.Commit());
irm.Check(0, 0, 1, 0, "irm");
scope1.Dispose();
}
finally
{
Transaction.Current = null;
}
}
[Fact]
public void ExplicitTransaction6c()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
Transaction.Current = ct;
try
{
TransactionScope scope1 = new TransactionScope(TransactionScopeOption.RequiresNew);
/* Enlist */
irm.Value = 2;
TransactionScope scope2 = new TransactionScope();
Assert.Throws<InvalidOperationException>(() => scope1.Dispose());
irm.Check(0, 0, 1, 0, "irm");
scope2.Dispose();
}
finally
{
Transaction.Current = null;
}
}
[Fact]
public void ExplicitTransaction6d()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
Transaction.Current = ct;
try
{
TransactionScope scope1 = new TransactionScope();
/* Enlist */
irm.Value = 2;
TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew);
Assert.Throws<InvalidOperationException>(() => scope1.Dispose());
scope2.Dispose();
}
finally
{
Transaction.Current = null;
}
}
[Fact]
public void ExplicitTransaction6e()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
Transaction.Current = ct;
try
{
TransactionScope scope1 = new TransactionScope();
/* Enlist */
irm.Value = 2;
TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress);
Assert.Throws<InvalidOperationException>(() => scope1.Dispose());
scope2.Dispose();
}
finally
{
Transaction.Current = null;
}
}
[Fact]
public void ExplicitTransaction7()
{
Assert.Throws<TransactionException>(() =>
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
irm.Value = 2;
ct.Commit();
/* Cannot accept any new work now, so TransactionException */
ct.Rollback();
});
}
[Fact]
public void ExplicitTransaction8()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
using (TransactionScope scope = new TransactionScope(ct))
{
irm.Value = 2;
Assert.Throws<TransactionAbortedException>(() => ct.Commit()); /* FIXME: Why TransactionAbortedException ?? */
irm.Check(0, 0, 1, 0, "irm");
}
}
[Fact]
public void ExplicitTransaction8a()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
using (TransactionScope scope = new TransactionScope(ct))
{
irm.Value = 2;
scope.Complete();
Assert.Throws<TransactionAbortedException>(() => ct.Commit()); /* FIXME: Why TransactionAbortedException ?? */
irm.Check(0, 0, 1, 0, "irm");
}
}
[Fact]
public void ExplicitTransaction9()
{
Assert.Throws<InvalidOperationException>(() =>
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
ct.BeginCommit(null, null);
ct.BeginCommit(null, null);
});
}
[Fact]
public void ExplicitTransaction10()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
Transaction.Current = ct;
try
{
irm.Value = 2;
TransactionScope scope = new TransactionScope(ct);
Assert.Equal(ct, Transaction.Current);
Assert.Throws<TransactionAbortedException>(() => ct.Commit());
irm.Check(0, 0, 1, 0, "irm");
}
finally
{
Transaction.Current = null;
}
}
[Fact]
public void ExplicitTransaction10a()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
Transaction.Current = ct;
try
{
irm.Value = 2;
Transaction.Current = null;
TransactionScope scope = new TransactionScope(ct);
Assert.Equal(ct, Transaction.Current);
Transaction.Current = null;
Assert.Throws<TransactionAbortedException>(() => ct.Commit());
irm.Check(0, 0, 1, 0, "irm");
}
finally
{
Transaction.Current = null;
}
}
[Fact]
public void ExplicitTransaction10b()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
Transaction.Current = ct;
try
{
irm.Value = 2;
Transaction.Current = null;
TransactionScope scope = new TransactionScope(ct);
Assert.Equal(ct, Transaction.Current);
IAsyncResult ar = ct.BeginCommit(null, null);
Assert.Throws<TransactionAbortedException>(() => ct.EndCommit(ar));
irm.Check(0, 0, 1, 0, "irm");
}
finally
{
Transaction.Current = null;
}
}
[Fact]
public void ExplicitTransaction12()
{
Assert.Throws<ArgumentException>(() =>
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
irm.FailPrepare = true;
ct.BeginCommit(null, null);
ct.EndCommit(null);
});
}
[Fact]
public void ExplicitTransaction13()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
Assert.Null(Transaction.Current);
Transaction.Current = ct;
try
{
irm.Value = 2;
irm.FailPrepare = true;
Assert.Throws<TransactionAbortedException>(() => ct.Commit());
Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status);
Assert.Throws<InvalidOperationException>(() => ct.BeginCommit(null, null));
}
finally
{
Transaction.Current = null;
}
}
[Fact]
public void ExplicitTransaction14()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
Assert.Null(Transaction.Current);
Transaction.Current = ct;
try
{
irm.Value = 2;
ct.Commit();
Assert.Equal(TransactionStatus.Committed, ct.TransactionInformation.Status);
Assert.Throws<InvalidOperationException>(() => ct.BeginCommit(null, null));
}
finally
{
Transaction.Current = null;
}
}
[Fact]
public void ExplicitTransaction15()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm = new IntResourceManager(1);
IntResourceManager irm2 = new IntResourceManager(3);
Assert.Null(Transaction.Current);
Transaction.Current = ct;
try
{
Assert.Throws<InvalidOperationException>(() =>
{
using (TransactionScope scope = new TransactionScope())
{
irm.Value = 2;
Transaction.Current = new CommittableTransaction();
irm2.Value = 6;
}
});
irm.Check(0, 0, 1, 0, "irm");
irm2.Check(0, 0, 1, 0, "irm2");
}
finally
{
Transaction.Current = null;
}
}
[Fact]
public void ExplicitTransaction16()
{
CommittableTransaction ct = new CommittableTransaction();
IntResourceManager irm0 = new IntResourceManager(3);
IntResourceManager irm = new IntResourceManager(1);
Assert.Null(Transaction.Current);
Transaction.Current = ct;
try
{
irm.FailPrepare = true;
irm.FailWithException = true;
irm.Value = 2;
irm0.Value = 6;
var e = Assert.Throws<TransactionAbortedException>(() => ct.Commit());
Assert.NotNull(e.InnerException);
Assert.IsType<NotSupportedException>(e.InnerException);
irm.Check(1, 0, 0, 0, "irm");
irm0.Check(0, 0, 1, 0, "irm0");
}
finally
{
Transaction.Current = null;
}
}
#endregion
}
}
| |
// Copyright 2021 Esri.
//
// 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 Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using UIKit;
namespace ArcGISRuntime.Samples.FeatureLayerRenderingModeScene
{
[Register("FeatureLayerRenderingModeScene")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Feature layer rendering mode (scene)",
category: "Layers",
description: "Render features in a scene statically or dynamically by setting the feature layer rendering mode.",
instructions: "Tap the button to trigger the same zoom animation on both static and dynamicly rendered scenes.",
tags: new[] { "3D", "dynamic", "feature layer", "features", "rendering", "static" })]
public class FeatureLayerRenderingModeScene : UIViewController
{
// Hold references to UI controls.
private SceneView _staticSceneView;
private SceneView _dynamicSceneView;
private UIStackView _stackView;
private UIBarButtonItem _zoomButton;
// Points for demonstrating zoom.
private readonly MapPoint _zoomedOutPoint = new MapPoint(-118.37, 34.46, SpatialReferences.Wgs84);
private readonly MapPoint _zoomedInPoint = new MapPoint(-118.45, 34.395, SpatialReferences.Wgs84);
// Viewpoints for each zoom level.
private Camera _zoomedOutCamera;
private Camera _zoomedInCamera;
// URI for the feature service.
private const string FeatureService = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/";
// Hold the current zoom state.
private bool _zoomed;
public FeatureLayerRenderingModeScene()
{
Title = "Feature layer rendering mode (Scene)";
}
private void Initialize()
{
// Initialize the cameras (viewpoints) with two points.
_zoomedOutCamera = new Camera(_zoomedOutPoint, 42000, 0, 0, 0);
_zoomedInCamera = new Camera(_zoomedInPoint, 2500, 90, 75, 0);
// Create the scene for displaying the feature layer in static mode.
Scene staticScene = new Scene
{
InitialViewpoint = new Viewpoint(_zoomedOutPoint, _zoomedOutCamera)
};
// Create the scene for displaying the feature layer in dynamic mode.
Scene dynamicScene = new Scene
{
InitialViewpoint = new Viewpoint(_zoomedOutPoint, _zoomedOutCamera)
};
foreach (string identifier in new[] { "8", "9", "0" })
{
// Create the table.
ServiceFeatureTable serviceTable = new ServiceFeatureTable(new Uri(FeatureService + identifier));
// Create and add the static layer.
FeatureLayer staticLayer = new FeatureLayer(serviceTable)
{
RenderingMode = FeatureRenderingMode.Static
};
staticScene.OperationalLayers.Add(staticLayer);
// Create and add the dynamic layer.
FeatureLayer dynamicLayer = new FeatureLayer(new ServiceFeatureTable(serviceTable.Source));
dynamicLayer.RenderingMode = FeatureRenderingMode.Dynamic;
dynamicScene.OperationalLayers.Add(dynamicLayer);
}
// Add the scenes to the scene views.
_staticSceneView.Scene = staticScene;
_dynamicSceneView.Scene = dynamicScene;
}
private void _zoomButton_TouchUpInside(object sender, EventArgs e)
{
// Zoom out if zoomed.
if (_zoomed)
{
_staticSceneView.SetViewpointCameraAsync(_zoomedOutCamera, new TimeSpan(0, 0, 5));
_dynamicSceneView.SetViewpointCameraAsync(_zoomedOutCamera, new TimeSpan(0, 0, 5));
}
else // Zoom in otherwise.
{
_staticSceneView.SetViewpointCameraAsync(_zoomedInCamera, new TimeSpan(0, 0, 5));
_dynamicSceneView.SetViewpointCameraAsync(_zoomedInCamera, new TimeSpan(0, 0, 5));
}
// Toggle zoom state.
_zoomed = !_zoomed;
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor };
_staticSceneView = new SceneView();
_staticSceneView.TranslatesAutoresizingMaskIntoConstraints = false;
_dynamicSceneView = new SceneView();
_dynamicSceneView.TranslatesAutoresizingMaskIntoConstraints = false;
_stackView = new UIStackView(new UIView[] { _staticSceneView, _dynamicSceneView });
_stackView.TranslatesAutoresizingMaskIntoConstraints = false;
_stackView.Distribution = UIStackViewDistribution.FillEqually;
_stackView.Axis = View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact ? UILayoutConstraintAxis.Horizontal : UILayoutConstraintAxis.Vertical;
_zoomButton = new UIBarButtonItem();
_zoomButton.Title = "Zoom";
UIToolbar toolbar = new UIToolbar();
toolbar.TranslatesAutoresizingMaskIntoConstraints = false;
toolbar.Items = new[]
{
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
_zoomButton,
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace)
};
UILabel staticLabel = new UILabel
{
Text = "Static",
BackgroundColor = UIColor.FromWhiteAlpha(0f, .6f),
TextColor = UIColor.White,
TextAlignment = UITextAlignment.Center,
TranslatesAutoresizingMaskIntoConstraints = false
};
UILabel dynamicLabel = new UILabel
{
Text = "Dynamic",
BackgroundColor = UIColor.FromWhiteAlpha(0f, .6f),
TextColor = UIColor.White,
TextAlignment = UITextAlignment.Center,
TranslatesAutoresizingMaskIntoConstraints = false
};
// Add the views.
View.AddSubviews(_stackView, toolbar, staticLabel, dynamicLabel);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
_stackView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_stackView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor),
_stackView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_stackView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor),
staticLabel.TopAnchor.ConstraintEqualTo(_staticSceneView.TopAnchor),
staticLabel.HeightAnchor.ConstraintEqualTo(40),
staticLabel.LeadingAnchor.ConstraintEqualTo(_staticSceneView.LeadingAnchor),
staticLabel.TrailingAnchor.ConstraintEqualTo(_staticSceneView.TrailingAnchor),
dynamicLabel.TopAnchor.ConstraintEqualTo(_dynamicSceneView.TopAnchor),
dynamicLabel.HeightAnchor.ConstraintEqualTo(40),
dynamicLabel.LeadingAnchor.ConstraintEqualTo(_dynamicSceneView.LeadingAnchor),
dynamicLabel.TrailingAnchor.ConstraintEqualTo(_dynamicSceneView.TrailingAnchor)
});
}
public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
{
base.TraitCollectionDidChange(previousTraitCollection);
if (View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact)
{
_stackView.Axis = UILayoutConstraintAxis.Horizontal;
}
else
{
_stackView.Axis = UILayoutConstraintAxis.Vertical;
}
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Subscribe to events.
_zoomButton.Clicked += _zoomButton_TouchUpInside;
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
// Unsubscribe from events, per best practice.
_zoomButton.Clicked -= _zoomButton_TouchUpInside;
}
}
}
| |
// Copyright (c) 2013 SharpYaml - Alexandre Mutel
//
// 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.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using SharpYaml;
using SharpYaml.Events;
using System.Text;
namespace SharpYaml.Serialization
{
/// <summary>
/// Represents a sequence node in the YAML document.
/// </summary>
[DebuggerDisplay("Count = {children.Count}")]
public class YamlSequenceNode : YamlNode, IEnumerable<YamlNode>
{
private readonly IList<YamlNode> children = new List<YamlNode>();
/// <summary>
/// Gets the collection of child nodes.
/// </summary>
/// <value>The children.</value>
public IList<YamlNode> Children
{
get
{
return children;
}
}
/// <summary>
/// Gets or sets the style of the node.
/// </summary>
/// <value>The style.</value>
public YamlStyle Style { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="YamlSequenceNode"/> class.
/// </summary>
/// <param name="events">The events.</param>
/// <param name="state">The state.</param>
internal YamlSequenceNode(EventReader events, DocumentLoadingState state)
{
SequenceStart sequence = events.Expect<SequenceStart>();
Load(sequence, state);
bool hasUnresolvedAliases = false;
while (!events.Accept<SequenceEnd>())
{
YamlNode child = ParseNode(events, state);
children.Add(child);
hasUnresolvedAliases |= child is YamlAliasNode;
}
if (hasUnresolvedAliases)
{
state.AddNodeWithUnresolvedAliases(this);
}
#if DEBUG
else
{
foreach (var child in children)
{
if (child is YamlAliasNode)
{
throw new InvalidOperationException("Error in alias resolution.");
}
}
}
#endif
events.Expect<SequenceEnd>();
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlSequenceNode"/> class.
/// </summary>
public YamlSequenceNode()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlSequenceNode"/> class.
/// </summary>
public YamlSequenceNode(params YamlNode[] children)
: this((IEnumerable<YamlNode>)children)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlSequenceNode"/> class.
/// </summary>
public YamlSequenceNode(IEnumerable<YamlNode> children)
{
foreach (var child in children)
{
this.children.Add(child);
}
}
/// <summary>
/// Adds the specified child to the <see cref="Children"/> collection.
/// </summary>
/// <param name="child">The child.</param>
public void Add(YamlNode child)
{
children.Add(child);
}
/// <summary>
/// Adds a scalar node to the <see cref="Children"/> collection.
/// </summary>
/// <param name="child">The child.</param>
public void Add(string child)
{
children.Add(new YamlScalarNode(child));
}
/// <summary>
/// Resolves the aliases that could not be resolved when the node was created.
/// </summary>
/// <param name="state">The state of the document.</param>
internal override void ResolveAliases(DocumentLoadingState state)
{
for (int i = 0; i < children.Count; ++i)
{
if (children[i] is YamlAliasNode)
{
children[i] = state.GetNode(children[i].Anchor, true, children[i].Start, children[i].End);
}
}
}
/// <summary>
/// Saves the current node to the specified emitter.
/// </summary>
/// <param name="emitter">The emitter where the node is to be saved.</param>
/// <param name="state">The state.</param>
internal override void Emit(IEmitter emitter, EmitterState state)
{
emitter.Emit(new SequenceStart(Anchor, Tag, true, Style));
foreach (var node in children)
{
node.Save(emitter, state);
}
emitter.Emit(new SequenceEnd());
}
/// <summary>
/// Accepts the specified visitor by calling the appropriate Visit method on it.
/// </summary>
/// <param name="visitor">
/// A <see cref="IYamlVisitor"/>.
/// </param>
public override void Accept(IYamlVisitor visitor)
{
visitor.Visit(this);
}
/// <summary />
public override bool Equals(object other)
{
var obj = other as YamlSequenceNode;
if (obj == null || !Equals(obj) || children.Count != obj.children.Count)
{
return false;
}
for (int i = 0; i < children.Count; ++i)
{
if (!SafeEquals(children[i], obj.children[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
var hashCode = base.GetHashCode();
foreach (var item in children)
{
hashCode = CombineHashCodes(hashCode, GetHashCode(item));
}
return hashCode;
}
/// <summary>
/// Gets all nodes from the document, starting on the current node.
/// </summary>
public override IEnumerable<YamlNode> AllNodes
{
get
{
yield return this;
foreach (var child in children)
{
foreach (var node in child.AllNodes)
{
yield return node;
}
}
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var text = new StringBuilder("[ ");
foreach (var child in children)
{
if(text.Length > 2)
{
text.Append(", ");
}
text.Append(child);
}
text.Append(" ]");
return text.ToString();
}
#region IEnumerable<YamlNode> Members
/// <summary />
public IEnumerator<YamlNode> GetEnumerator()
{
return Children.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| |
using System;
using System.Linq.Expressions;
using Toggl.Phoebe.Data.DataObjects;
namespace Toggl.Phoebe.Data.Models
{
public class WorkspaceModel : Model<WorkspaceData>
{
private static string GetPropertyName<T> (Expression<Func<WorkspaceModel, T>> expr)
{
return expr.ToPropertyName ();
}
public static new readonly string PropertyId = Model<WorkspaceData>.PropertyId;
public static readonly string PropertyName = GetPropertyName (m => m.Name);
public static readonly string PropertyIsPremium = GetPropertyName (m => m.IsPremium);
public static readonly string PropertyDefaultRate = GetPropertyName (m => m.DefaultRate);
public static readonly string PropertyDefaultCurrency = GetPropertyName (m => m.DefaultCurrency);
public static readonly string PropertyProjectCreationPrivileges = GetPropertyName (m => m.ProjectCreationPrivileges);
public static readonly string PropertyBillableRatesVisibility = GetPropertyName (m => m.BillableRatesVisibility);
public static readonly string PropertyRoundingMode = GetPropertyName (m => m.RoundingMode);
public static readonly string PropertyRoundingPercision = GetPropertyName (m => m.RoundingPercision);
public static readonly string PropertyLogoUrl = GetPropertyName (m => m.LogoUrl);
public WorkspaceModel ()
{
}
public WorkspaceModel (WorkspaceData data) : base (data)
{
}
public WorkspaceModel (Guid id) : base (id)
{
}
protected override WorkspaceData Duplicate (WorkspaceData data)
{
return new WorkspaceData (data);
}
protected override void OnBeforeSave ()
{
}
protected override void DetectChangedProperties (WorkspaceData oldData, WorkspaceData newData)
{
base.DetectChangedProperties (oldData, newData);
if (oldData.Name != newData.Name) {
OnPropertyChanged (PropertyName);
}
if (oldData.IsPremium != newData.IsPremium) {
OnPropertyChanged (PropertyIsPremium);
}
if (oldData.DefaultRate != newData.DefaultRate) {
OnPropertyChanged (PropertyDefaultRate);
}
if (oldData.DefaultCurrency != newData.DefaultCurrency) {
OnPropertyChanged (PropertyDefaultCurrency);
}
if (oldData.ProjectCreationPrivileges != newData.ProjectCreationPrivileges) {
OnPropertyChanged (PropertyProjectCreationPrivileges);
}
if (oldData.BillableRatesVisibility != newData.BillableRatesVisibility) {
OnPropertyChanged (PropertyBillableRatesVisibility);
}
if (oldData.RoundingMode != newData.RoundingMode) {
OnPropertyChanged (PropertyRoundingMode);
}
if (oldData.RoundingPercision != newData.RoundingPercision) {
OnPropertyChanged (PropertyRoundingPercision);
}
if (oldData.LogoUrl != newData.LogoUrl) {
OnPropertyChanged (PropertyLogoUrl);
}
}
public string Name
{
get {
EnsureLoaded ();
return Data.Name;
} set {
if (Name == value) {
return;
}
MutateData (data => data.Name = value);
}
}
public bool IsPremium
{
get {
EnsureLoaded ();
return Data.IsPremium;
} set {
if (IsPremium == value) {
return;
}
MutateData (data => data.IsPremium = value);
}
}
public decimal? DefaultRate
{
get {
EnsureLoaded ();
return Data.DefaultRate;
} set {
if (DefaultRate == value) {
return;
}
MutateData (data => data.DefaultRate = value);
}
}
public string DefaultCurrency
{
get {
EnsureLoaded ();
return Data.DefaultCurrency;
} set {
if (DefaultCurrency == value) {
return;
}
MutateData (data => data.DefaultCurrency = value);
}
}
public AccessLevel ProjectCreationPrivileges
{
get {
EnsureLoaded ();
return Data.ProjectCreationPrivileges;
} set {
if (ProjectCreationPrivileges == value) {
return;
}
MutateData (data => data.ProjectCreationPrivileges = value);
}
}
public AccessLevel BillableRatesVisibility
{
get {
EnsureLoaded ();
return Data.BillableRatesVisibility;
} set {
if (BillableRatesVisibility == value) {
return;
}
MutateData (data => data.BillableRatesVisibility = value);
}
}
public RoundingMode RoundingMode
{
get {
EnsureLoaded ();
return Data.RoundingMode;
} set {
if (RoundingMode == value) {
return;
}
MutateData (data => data.RoundingMode = value);
}
}
public int RoundingPercision
{
get {
EnsureLoaded ();
return Data.RoundingPercision;
} set {
if (RoundingPercision == value) {
return;
}
MutateData (data => data.RoundingPercision = value);
}
}
public string LogoUrl
{
get {
EnsureLoaded ();
return Data.LogoUrl;
} set {
if (LogoUrl == value) {
return;
}
MutateData (data => data.LogoUrl = value);
}
}
public static explicit operator WorkspaceModel (WorkspaceData data)
{
if (data == null) {
return null;
}
return new WorkspaceModel (data);
}
public static implicit operator WorkspaceData (WorkspaceModel model)
{
return model.Data;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities.Debugger
{
using System;
using System.Activities.Expressions;
using System.Activities.Hosting;
using System.Activities.Runtime;
using System.Activities.Statements;
using System.Activities.XamlIntegration;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime;
[DebuggerNonUserCode]
class DebugManager
{
static StateManager.DynamicModuleManager dynamicModuleManager;
WorkflowInstance host;
StateManager stateManager;
Dictionary<object, State> states;
Dictionary<int, Stack<Activity>> runningThreads;
InstrumentationTracker instrumentationTracker;
List<string> temporaryFiles;
public DebugManager(Activity root, string moduleNamePrefix, string typeNamePrefix, string auxiliaryThreadName, bool breakOnStartup,
WorkflowInstance host, bool debugStartedAtRoot) :
this(root, moduleNamePrefix, typeNamePrefix, auxiliaryThreadName, breakOnStartup, host, debugStartedAtRoot, false)
{
}
internal DebugManager(Activity root, string moduleNamePrefix, string typeNamePrefix, string auxiliaryThreadName, bool breakOnStartup,
WorkflowInstance host, bool debugStartedAtRoot, bool resetDynamicModule)
{
if (resetDynamicModule)
{
dynamicModuleManager = null;
}
if (dynamicModuleManager == null)
{
dynamicModuleManager = new StateManager.DynamicModuleManager(moduleNamePrefix);
}
this.stateManager = new StateManager(
new StateManager.Properties
{
ModuleNamePrefix = moduleNamePrefix,
TypeNamePrefix = typeNamePrefix,
AuxiliaryThreadName = auxiliaryThreadName,
BreakOnStartup = breakOnStartup
},
debugStartedAtRoot, dynamicModuleManager);
this.states = new Dictionary<object, State>();
this.runningThreads = new Dictionary<int, Stack<Activity>>();
this.instrumentationTracker = new InstrumentationTracker(root);
this.host = host;
}
// Whether we're priming the background thread (in Attach To Process case).
public bool IsPriming
{
set { this.stateManager.IsPriming = value; }
}
// Whether debugging is done from the start of the root workflow,
// contrast to attaching into the middle of a running workflow.
bool DebugStartedAtRoot
{
get
{
return this.stateManager.DebugStartedAtRoot;
}
}
internal void Instrument(Activity activity)
{
bool isTemporaryFile = false;
string sourcePath = null;
bool instrumentationFailed = false;
Dictionary<string, byte[]> checksumCache = null;
try
{
byte[] checksum;
Dictionary<object, SourceLocation> sourceLocations = SourceLocationProvider.GetSourceLocations(activity, out sourcePath, out isTemporaryFile, out checksum);
if (checksum != null)
{
checksumCache = new Dictionary<string, byte[]>();
checksumCache.Add(sourcePath.ToUpperInvariant(), checksum);
}
Instrument(activity, sourceLocations, Path.GetFileNameWithoutExtension(sourcePath), checksumCache);
}
catch (Exception ex)
{
instrumentationFailed = true;
Trace.WriteLine(SR.DebugInstrumentationFailed(ex.Message));
if (Fx.IsFatal(ex))
{
throw;
}
}
List<Activity> sameSourceActivities = this.instrumentationTracker.GetSameSourceSubRoots(activity);
this.instrumentationTracker.MarkInstrumented(activity);
foreach (Activity sameSourceActivity in sameSourceActivities)
{
if (!instrumentationFailed)
{
MapInstrumentationStates(activity, sameSourceActivity);
}
// Mark it as instrumentated, even though it fails so it won't be
// retried.
this.instrumentationTracker.MarkInstrumented(sameSourceActivity);
}
if (isTemporaryFile)
{
if (this.temporaryFiles == null)
{
this.temporaryFiles = new List<string>();
}
Fx.Assert(!string.IsNullOrEmpty(sourcePath), "SourcePath cannot be null for temporary file");
this.temporaryFiles.Add(sourcePath);
}
}
// Workflow rooted at rootActivity1 and rootActivity2 have same source file, but they
// are two different instantiation.
// rootActivity1 has been instrumented and its instrumentation states can be
// re-used by rootActivity2.
//
// MapInstrumentationStates will walk both Workflow trees in parallel and map every
// state for activities in rootActivity1 to corresponding activities in rootActivity2.
void MapInstrumentationStates(Activity rootActivity1, Activity rootActivity2)
{
Queue<KeyValuePair<Activity, Activity>> pairsRemaining = new Queue<KeyValuePair<Activity, Activity>>();
pairsRemaining.Enqueue(new KeyValuePair<Activity, Activity>(rootActivity1, rootActivity2));
HashSet<Activity> visited = new HashSet<Activity>();
KeyValuePair<Activity, Activity> currentPair;
State state;
while (pairsRemaining.Count > 0)
{
currentPair = pairsRemaining.Dequeue();
Activity activity1 = currentPair.Key;
Activity activity2 = currentPair.Value;
if (this.states.TryGetValue(activity1, out state))
{
if (this.states.ContainsKey(activity2))
{
Trace.WriteLine("Workflow", SR.DuplicateInstrumentation(activity2.DisplayName));
}
else
{
// Map activity2 to the same state.
this.states.Add(activity2, state);
}
}
//Some activities may not have corresponding Xaml node, e.g. ActivityFaultedOutput.
visited.Add(activity1);
// This to avoid comparing any value expression with DesignTimeValueExpression (in designer case).
IEnumerator<Activity> enumerator1 = WorkflowInspectionServices.GetActivities(activity1).GetEnumerator();
IEnumerator<Activity> enumerator2 = WorkflowInspectionServices.GetActivities(activity2).GetEnumerator();
bool hasNextItem1 = enumerator1.MoveNext();
bool hasNextItem2 = enumerator2.MoveNext();
while (hasNextItem1 && hasNextItem2)
{
if (!visited.Contains(enumerator1.Current)) // avoid adding the same activity (e.g. some default implementation).
{
if (enumerator1.Current.GetType() != enumerator2.Current.GetType())
{
// Give debugger log instead of just asserting; to help user find out mismatch problem.
Trace.WriteLine(
"Unmatched type: " + enumerator1.Current.GetType().FullName +
" vs " + enumerator2.Current.GetType().FullName + "\n");
}
pairsRemaining.Enqueue(new KeyValuePair<Activity, Activity>(enumerator1.Current, enumerator2.Current));
}
hasNextItem1 = enumerator1.MoveNext();
hasNextItem2 = enumerator2.MoveNext();
}
// If enumerators do not finish at the same time, then they have unmatched number of activities.
// Give debugger log instead of just asserting; to help user find out mismatch problem.
if (hasNextItem1 || hasNextItem2)
{
Trace.WriteLine("Workflow", "Unmatched number of children\n");
}
}
}
// Main instrumentation.
// Currently the typeNamePrefix is used to notify the Designer of which file to show.
// This will no longer necessary when the callstack API can give us the source line
// information.
public void Instrument(Activity rootActivity, Dictionary<object, SourceLocation> sourceLocations, string typeNamePrefix, Dictionary<string, byte[]> checksumCache)
{
Queue<KeyValuePair<Activity, string>> pairsRemaining = new Queue<KeyValuePair<Activity, string>>();
string name;
Activity activity = rootActivity;
KeyValuePair<Activity, string> pair = new KeyValuePair<Activity, string>(activity, string.Empty);
pairsRemaining.Enqueue(pair);
HashSet<string> existingNames = new HashSet<string>();
HashSet<Activity> visited = new HashSet<Activity>();
SourceLocation sourceLocation;
while (pairsRemaining.Count > 0)
{
pair = pairsRemaining.Dequeue();
activity = pair.Key;
string parentName = pair.Value;
string displayName = activity.DisplayName;
// If no DisplayName, then use the type name.
if (string.IsNullOrEmpty(displayName))
{
displayName = activity.GetType().Name;
}
if (parentName == string.Empty)
{ // the root
name = displayName;
}
else
{
name = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", parentName, displayName);
}
int i = 0;
while (existingNames.Contains(name))
{
++i;
name = string.Format(CultureInfo.InvariantCulture, "{0}.{1}{2}", parentName, displayName, i.ToString(CultureInfo.InvariantCulture));
}
existingNames.Add(name);
visited.Add(activity);
if (sourceLocations.TryGetValue(activity, out sourceLocation))
{
object[] objects = activity.GetType().GetCustomAttributes(typeof(DebuggerStepThroughAttribute), false);
if ((objects == null || objects.Length == 0))
{
Instrument(activity, sourceLocation, name);
}
}
foreach (Activity childActivity in WorkflowInspectionServices.GetActivities(activity))
{
if (!visited.Contains(childActivity))
{
pairsRemaining.Enqueue(new KeyValuePair<Activity, string>(childActivity, name));
}
}
}
this.stateManager.Bake(typeNamePrefix, checksumCache);
}
// Exiting the DebugManager.
// Delete all temporary files
public void Exit()
{
if (this.temporaryFiles != null)
{
foreach (string temporaryFile in this.temporaryFiles)
{
// Clean up published source.
try
{
File.Delete(temporaryFile);
}
catch (IOException)
{
// ---- IOException silently.
}
this.temporaryFiles = null;
}
}
this.stateManager.ExitThreads(); // State manager is still keep for the session in SessionStateManager
this.stateManager = null;
}
void Instrument(Activity activity, SourceLocation sourceLocation, string name)
{
Fx.Assert(activity != null, "activity can't be null");
Fx.Assert(sourceLocation != null, "sourceLocation can't be null");
if (this.states.ContainsKey(activity))
{
Trace.WriteLine(SR.DuplicateInstrumentation(activity.DisplayName));
}
else
{
State activityState = this.stateManager.DefineStateWithDebugInfo(sourceLocation, name);
this.states.Add(activity, activityState);
}
}
// Test whether activity has been instrumented.
// If not, try to instrument it.
// It will return true if instrumentation is already done or
// instrumentation is succesful. False otherwise.
bool EnsureInstrumented(Activity activity)
{
// This is the most common case, we will find the instrumentation.
if (this.states.ContainsKey(activity))
{
return true;
}
// No states correspond to this yet.
if (this.instrumentationTracker.IsUninstrumentedSubRoot(activity))
{
Instrument(activity);
return this.states.ContainsKey(activity);
}
else
{
return false;
}
}
// Primitive EnterState
void EnterState(int threadId, Activity activity, Dictionary<string, object> locals)
{
Fx.Assert(activity != null, "activity cannot be null");
this.Push(threadId, activity);
State activityState;
if (this.states.TryGetValue(activity, out activityState))
{
this.stateManager.EnterState(threadId, activityState, locals);
}
else
{
Fx.Assert(false, "Uninstrumented activity is disallowed: " + activity.DisplayName);
}
}
public void OnEnterState(ActivityInstance instance)
{
Fx.Assert(instance != null, "ActivityInstance cannot be null");
Activity activity = instance.Activity;
if (this.EnsureInstrumented(activity))
{
this.EnterState(GetOrCreateThreadId(activity, instance), activity, GenerateLocals(instance));
}
}
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.ReviewUnusedParameters)]
public void OnEnterState(Activity expression, ActivityInstance instance, LocationEnvironment environment)
{
if (this.EnsureInstrumented(expression))
{
this.EnterState(GetOrCreateThreadId(expression, instance), expression, GenerateLocals(instance));
}
}
void LeaveState(Activity activity)
{
Fx.Assert(activity != null, "Activity cannot be null");
int threadId = GetExecutingThreadId(activity, true);
// If debugging was not started from the root, then threadId should not be < 0.
Fx.Assert(!this.DebugStartedAtRoot || threadId >= 0, "Leaving from an unknown state");
if (threadId >= 0)
{
State activityState;
if (this.states.TryGetValue(activity, out activityState))
{
this.stateManager.LeaveState(threadId, activityState);
}
else
{
Fx.Assert(false, "Uninstrumented activity is disallowed: " + activity.DisplayName);
}
this.Pop(threadId);
}
}
public void OnLeaveState(ActivityInstance activityInstance)
{
Fx.Assert(activityInstance != null, "ActivityInstance cannot be null");
if (this.EnsureInstrumented(activityInstance.Activity))
{
this.LeaveState(activityInstance.Activity);
}
}
static Dictionary<string, object> GenerateLocals(ActivityInstance instance)
{
Dictionary<string, object> locals = new Dictionary<string, object>();
locals.Add("debugInfo", new DebugInfo(instance));
return locals;
}
void Push(int threadId, Activity activity)
{
((Stack<Activity>)this.runningThreads[threadId]).Push(activity);
}
void Pop(int threadId)
{
Stack<Activity> stack = this.runningThreads[threadId];
stack.Pop();
if (stack.Count == 0)
{
this.stateManager.Exit(threadId);
this.runningThreads.Remove(threadId);
}
}
// Given an activity, return the thread id where it is currently
// executed (on the top of the callstack).
// Boolean "strict" parameter determine whether the activity itself should
// be on top of the stack.
// Strict checking is needed in the case of "Leave"-ing a state.
// Non-strict checking is needed for "Enter"-ing a state, since the direct parent of
// the activity may not yet be executed (e.g. the activity is an argument of another activity,
// the activity is "enter"-ed even though the direct parent is not yet "enter"-ed.
int GetExecutingThreadId(Activity activity, bool strict)
{
int threadId = -1;
foreach (KeyValuePair<int, Stack<Activity>> entry in this.runningThreads)
{
Stack<Activity> threadStack = entry.Value;
if (threadStack.Peek() == activity)
{
threadId = entry.Key;
break;
}
}
if (threadId < 0 && !strict)
{
foreach (KeyValuePair<int, Stack<Activity>> entry in this.runningThreads)
{
Stack<Activity> threadStack = entry.Value;
Activity topActivity = threadStack.Peek();
if (!IsParallelActivity(topActivity) && IsAncestorOf(threadStack.Peek(), activity))
{
threadId = entry.Key;
break;
}
}
}
return threadId;
}
static bool IsAncestorOf(Activity ancestorActivity, Activity activity)
{
Fx.Assert(activity != null, "IsAncestorOf: Cannot pass null as activity");
Fx.Assert(ancestorActivity != null, "IsAncestorOf: Cannot pass null as ancestorActivity");
activity = activity.Parent;
while (activity != null && activity != ancestorActivity && !IsParallelActivity(activity))
{
activity = activity.Parent;
}
return (activity == ancestorActivity);
}
static bool IsParallelActivity(Activity activity)
{
Fx.Assert(activity != null, "IsParallel: Cannot pass null as activity");
return activity is Parallel ||
(activity.GetType().IsGenericType && activity.GetType().GetGenericTypeDefinition() == typeof(ParallelForEach<>));
}
// Get threads currently executing the parent of the given activity,
// if none then create a new one and prep the call stack to current state.
int GetOrCreateThreadId(Activity activity, ActivityInstance instance)
{
int threadId = -1;
if (activity.Parent != null && !IsParallelActivity(activity.Parent))
{
threadId = GetExecutingThreadId(activity.Parent, false);
}
if (threadId < 0)
{
threadId = CreateLogicalThread(activity, instance, false);
}
return threadId;
}
// Create logical thread and bring its call stack to reflect call from
// the root up to (but not including) the instance.
// If the activity is an expression though, then the call stack will also include the instance
// (since it is the parent of the expression).
int CreateLogicalThread(Activity activity, ActivityInstance instance, bool primeCurrentInstance)
{
Stack<ActivityInstance> ancestors = null;
if (!this.DebugStartedAtRoot)
{
ancestors = new Stack<ActivityInstance>();
if (activity != instance.Activity || primeCurrentInstance)
{ // This mean that activity is an expression and
// instance is the parent of this expression.
Fx.Assert(primeCurrentInstance || (activity is ActivityWithResult), "Expect an ActivityWithResult");
Fx.Assert(primeCurrentInstance || (activity.Parent == instance.Activity), "Argument Expression is not given correct parent instance");
if (primeCurrentInstance || !IsParallelActivity(instance.Activity))
{
ancestors.Push(instance);
}
}
ActivityInstance instanceParent = instance.Parent;
while (instanceParent != null && !IsParallelActivity(instanceParent.Activity))
{
ancestors.Push(instanceParent);
instanceParent = instanceParent.Parent;
}
if (instanceParent != null && IsParallelActivity(instanceParent.Activity))
{
// Ensure thread is created for the parent (a Parallel activity).
int parentThreadId = GetExecutingThreadId(instanceParent.Activity, false);
if (parentThreadId < 0)
{
parentThreadId = CreateLogicalThread(instanceParent.Activity, instanceParent, true);
Fx.Assert(parentThreadId > 0, "Parallel main thread can't be created");
}
}
}
string threadName = "DebuggerThread:";
if (activity.Parent != null)
{
threadName += activity.Parent.DisplayName;
}
else // Special case for the root of WorklowService that does not have a parent.
{
threadName += activity.DisplayName;
}
int newThreadId = this.stateManager.CreateLogicalThread(threadName);
Stack<Activity> newStack = new Stack<Activity>();
this.runningThreads.Add(newThreadId, newStack);
if (!this.DebugStartedAtRoot && ancestors != null)
{ // Need to create callstack to current activity.
PrimeCallStack(newThreadId, ancestors);
}
return newThreadId;
}
// Prime the call stack to contains all the ancestors of this instance.
// Note: the call stack will not include the current instance.
void PrimeCallStack(int threadId, Stack<ActivityInstance> ancestors)
{
Fx.Assert(!this.DebugStartedAtRoot, "Priming should not be called if the debugging is attached from the start of the workflow");
bool currentIsPrimingValue = this.stateManager.IsPriming;
this.stateManager.IsPriming = true;
while (ancestors.Count > 0)
{
ActivityInstance currentInstance = ancestors.Pop();
if (EnsureInstrumented(currentInstance.Activity))
{
this.EnterState(threadId, currentInstance.Activity, GenerateLocals(currentInstance));
}
}
this.stateManager.IsPriming = currentIsPrimingValue;
}
}
}
| |
// 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.2.2.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AccountOperations operations.
/// </summary>
public partial interface IAccountOperations
{
/// <summary>
/// Gets the first page of Data Lake Analytics accounts, if any, within
/// a specific resource group. This includes a link to the next page,
/// if any.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just
/// those requested, e.g. Categories?$select=CategoryName,Description.
/// Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the
/// matching resources included with the resources in the response,
/// e.g. Categories?$count=true. Optional.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeAnalyticsAccountBasic>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, ODataQuery<DataLakeAnalyticsAccount> odataQuery = default(ODataQuery<DataLakeAnalyticsAccount>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the first page of Data Lake Analytics accounts, if any, within
/// the current subscription. This includes a link to the next page, if
/// any.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just
/// those requested, e.g. Categories?$select=CategoryName,Description.
/// Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the
/// matching resources included with the resources in the response,
/// e.g. Categories?$count=true. Optional.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeAnalyticsAccountBasic>>> ListWithHttpMessagesAsync(ODataQuery<DataLakeAnalyticsAccount> odataQuery = default(ODataQuery<DataLakeAnalyticsAccount>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the specified Data Lake Analytics account. This supplies
/// the user with computation services for Data Lake Analytics
/// workloads
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.the account will be associated with.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create Data Lake Analytics account
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeAnalyticsAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, DataLakeAnalyticsAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the Data Lake Analytics account object specified by the
/// accountName with the contents of the account object.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the update Data Lake Analytics account
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeAnalyticsAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, DataLakeAnalyticsAccountUpdateParameters parameters = default(DataLakeAnalyticsAccountUpdateParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Begins the delete process for the Data Lake Analytics account
/// object specified by the account name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to delete
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets details of the specified Data Lake Analytics account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to retrieve.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeAnalyticsAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the specified Data Lake Analytics account. This supplies
/// the user with computation services for Data Lake Analytics
/// workloads
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.the account will be associated with.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create Data Lake Analytics account
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeAnalyticsAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, DataLakeAnalyticsAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the Data Lake Analytics account object specified by the
/// accountName with the contents of the account object.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the update Data Lake Analytics account
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeAnalyticsAccount>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, DataLakeAnalyticsAccountUpdateParameters parameters = default(DataLakeAnalyticsAccountUpdateParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Begins the delete process for the Data Lake Analytics account
/// object specified by the account name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to delete
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the first page of Data Lake Analytics accounts, if any, within
/// a specific resource group. This includes a link to the next page,
/// if any.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeAnalyticsAccountBasic>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the first page of Data Lake Analytics accounts, if any, within
/// the current subscription. This includes a link to the next page, if
/// any.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeAnalyticsAccountBasic>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Xml;
using System.Runtime.Serialization.Configuration;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Security;
using System.Security.Permissions;
[DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
#if USE_REFEMIT
public struct KeyValue<K, V>
#else
internal struct KeyValue<K, V>
#endif
{
K key;
V value;
internal KeyValue(K key, V value)
{
this.key = key;
this.value = value;
}
[DataMember(IsRequired = true)]
public K Key
{
get { return key; }
set { key = value; }
}
[DataMember(IsRequired = true)]
public V Value
{
get { return value; }
set { this.value = value; }
}
}
internal enum CollectionKind : byte
{
None,
GenericDictionary,
Dictionary,
GenericList,
GenericCollection,
List,
GenericEnumerable,
Collection,
Enumerable,
Array,
}
#if USE_REFEMIT
public sealed class CollectionDataContract : DataContract
#else
internal sealed class CollectionDataContract : DataContract
#endif
{
[Fx.Tag.SecurityNote(Critical = "XmlDictionaryString representing the XML element name for collection items."
+ "Statically cached and used from IL generated code.")]
[SecurityCritical]
XmlDictionaryString collectionItemName;
[Fx.Tag.SecurityNote(Critical = "XmlDictionaryString representing the XML namespace for collection items."
+ "Statically cached and used from IL generated code.")]
[SecurityCritical]
XmlDictionaryString childElementNamespace;
[Fx.Tag.SecurityNote(Critical = "Internal DataContract representing the contract for collection items."
+ "Statically cached and used from IL generated code.")]
[SecurityCritical]
DataContract itemContract;
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization. "
+ "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
CollectionDataContractCriticalHelper helper;
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
internal CollectionDataContract(CollectionKind kind)
: base(new CollectionDataContractCriticalHelper(kind))
{
InitCollectionDataContract(this);
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
internal CollectionDataContract(Type type)
: base(new CollectionDataContractCriticalHelper(type))
{
InitCollectionDataContract(this);
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
internal CollectionDataContract(Type type, DataContract itemContract)
: base(new CollectionDataContractCriticalHelper(type, itemContract))
{
InitCollectionDataContract(this);
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string serializationExceptionMessage, string deserializationExceptionMessage)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, serializationExceptionMessage, deserializationExceptionMessage))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage)
: base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical fields; called from all constructors.")]
[SecurityCritical]
void InitCollectionDataContract(DataContract sharedTypeContract)
{
this.helper = base.Helper as CollectionDataContractCriticalHelper;
this.collectionItemName = helper.CollectionItemName;
if (helper.Kind == CollectionKind.Dictionary || helper.Kind == CollectionKind.GenericDictionary)
{
this.itemContract = helper.ItemContract;
}
this.helper.SharedTypeContract = sharedTypeContract;
}
void InitSharedTypeContract()
{
}
static Type[] KnownInterfaces
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical knownInterfaces property.",
Safe = "knownInterfaces only needs to be protected for write.")]
[SecuritySafeCritical]
get { return CollectionDataContractCriticalHelper.KnownInterfaces; }
}
internal CollectionKind Kind
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical kind property.",
Safe = "kind only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.Kind; }
}
internal Type ItemType
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical itemType property.",
Safe = "itemType only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.ItemType; }
}
public DataContract ItemContract
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical itemContract property.",
Safe = "itemContract only needs to be protected for write.")]
[SecuritySafeCritical]
get { return itemContract ?? helper.ItemContract; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical itemContract property.")]
[SecurityCritical]
set
{
itemContract = value;
helper.ItemContract = value;
}
}
internal DataContract SharedTypeContract
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical sharedTypeContract property.",
Safe = "sharedTypeContract only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.SharedTypeContract; }
}
internal string ItemName
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical itemName property.",
Safe = "itemName only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.ItemName; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical itemName property.")]
[SecurityCritical]
set { helper.ItemName = value; }
}
public XmlDictionaryString CollectionItemName
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical collectionItemName property.",
Safe = "collectionItemName only needs to be protected for write.")]
[SecuritySafeCritical]
get { return this.collectionItemName; }
}
internal string KeyName
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical keyName property.",
Safe = "keyName only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.KeyName; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical keyName property.")]
[SecurityCritical]
set { helper.KeyName = value; }
}
internal string ValueName
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical valueName property.",
Safe = "valueName only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.ValueName; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical valueName property.")]
[SecurityCritical]
set { helper.ValueName = value; }
}
internal bool IsDictionary
{
get { return KeyName != null; }
}
public XmlDictionaryString ChildElementNamespace
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical childElementNamespace property.",
Safe = "childElementNamespace only needs to be protected for write; initialized in getter if null.")]
[SecuritySafeCritical]
get
{
if (this.childElementNamespace == null)
{
lock (this)
{
if (this.childElementNamespace == null)
{
if (helper.ChildElementNamespace == null && !IsDictionary)
{
XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary());
Thread.MemoryBarrier();
helper.ChildElementNamespace = tempChildElementNamespace;
}
this.childElementNamespace = helper.ChildElementNamespace;
}
}
}
return childElementNamespace;
}
}
internal bool IsItemTypeNullable
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical isItemTypeNullable property.",
Safe = "isItemTypeNullable only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.IsItemTypeNullable; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical isItemTypeNullable property.")]
[SecurityCritical]
set { helper.IsItemTypeNullable = value; }
}
internal bool IsConstructorCheckRequired
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical isConstructorCheckRequired property.",
Safe = "isConstructorCheckRequired only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.IsConstructorCheckRequired; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical isConstructorCheckRequired property.")]
[SecurityCritical]
set { helper.IsConstructorCheckRequired = value; }
}
internal MethodInfo GetEnumeratorMethod
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical getEnumeratorMethod property.",
Safe = "getEnumeratorMethod only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.GetEnumeratorMethod; }
}
internal MethodInfo AddMethod
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical addMethod property.",
Safe = "addMethod only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.AddMethod; }
}
internal ConstructorInfo Constructor
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical constructor property.",
Safe = "constructor only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.Constructor; }
}
internal override DataContractDictionary KnownDataContracts
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical knownDataContracts property.",
Safe = "knownDataContracts only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.KnownDataContracts; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical knownDataContracts property.")]
[SecurityCritical]
set { helper.KnownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical invalidCollectionInSharedContractMessage property.",
Safe = "invalidCollectionInSharedContractMessage only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.InvalidCollectionInSharedContractMessage; }
}
internal string SerializationExceptionMessage
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical serializationExceptionMessage property.",
Safe = "serializationExceptionMessage only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.SerializationExceptionMessage; }
}
internal string DeserializationExceptionMessage
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical deserializationExceptionMessage property.",
Safe = "deserializationExceptionMessage only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.DeserializationExceptionMessage; }
}
internal bool IsReadOnlyContract
{
get { return this.DeserializationExceptionMessage != null; }
}
bool ItemNameSetExplicit
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical itemNameSetExplicit property.",
Safe = "itemNameSetExplicit only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.ItemNameSetExplicit; }
}
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical xmlFormatWriterDelegate property.",
Safe = "xmlFormatWriterDelegate only needs to be protected for write; initialized in getter if null.")]
[SecuritySafeCritical]
get
{
if (helper.XmlFormatWriterDelegate == null)
{
lock (this)
{
if (helper.XmlFormatWriterDelegate == null)
{
XmlFormatCollectionWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateCollectionWriter(this);
Thread.MemoryBarrier();
helper.XmlFormatWriterDelegate = tempDelegate;
}
}
}
return helper.XmlFormatWriterDelegate;
}
}
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical xmlFormatReaderDelegate property.",
Safe = "xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null.")]
[SecuritySafeCritical]
get
{
if (helper.XmlFormatReaderDelegate == null)
{
lock (this)
{
if (helper.XmlFormatReaderDelegate == null)
{
if (this.IsReadOnlyContract)
{
ThrowInvalidDataContractException(helper.DeserializationExceptionMessage, null /*type*/);
}
XmlFormatCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateCollectionReader(this);
Thread.MemoryBarrier();
helper.XmlFormatReaderDelegate = tempDelegate;
}
}
}
return helper.XmlFormatReaderDelegate;
}
}
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical xmlFormatGetOnlyCollectionReaderDelegate property.",
Safe = "xmlFormatGetOnlyCollectionReaderDelegate only needs to be protected for write; initialized in getter if null.")]
[SecuritySafeCritical]
get
{
if (helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
lock (this)
{
if (helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
if (this.UnderlyingType.IsInterface && (this.Kind == CollectionKind.Enumerable || this.Kind == CollectionKind.Collection || this.Kind == CollectionKind.GenericEnumerable))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GetOnlyCollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(this.UnderlyingType))));
}
if (this.IsReadOnlyContract)
{
ThrowInvalidDataContractException(helper.DeserializationExceptionMessage, null /*type*/);
}
Fx.Assert(this.AddMethod != null || this.Kind == CollectionKind.Array, "Add method cannot be null if the collection is being used as a get-only property");
XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this);
Thread.MemoryBarrier();
helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate;
}
}
}
return helper.XmlFormatGetOnlyCollectionReaderDelegate;
}
}
[Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing collections. Since the data is cached statically, we lock down access to it.")]
[SecurityCritical(SecurityCriticalScope.Everything)]
class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
static Type[] _knownInterfaces;
Type itemType;
bool isItemTypeNullable;
CollectionKind kind;
readonly MethodInfo getEnumeratorMethod, addMethod;
readonly ConstructorInfo constructor;
readonly string serializationExceptionMessage, deserializationExceptionMessage;
DataContract itemContract;
DataContract sharedTypeContract;
DataContractDictionary knownDataContracts;
bool isKnownTypeAttributeChecked;
string itemName;
bool itemNameSetExplicit;
XmlDictionaryString collectionItemName;
string keyName;
string valueName;
XmlDictionaryString childElementNamespace;
string invalidCollectionInSharedContractMessage;
XmlFormatCollectionReaderDelegate xmlFormatReaderDelegate;
XmlFormatGetOnlyCollectionReaderDelegate xmlFormatGetOnlyCollectionReaderDelegate;
XmlFormatCollectionWriterDelegate xmlFormatWriterDelegate;
bool isConstructorCheckRequired = false;
internal static Type[] KnownInterfaces
{
get
{
if (_knownInterfaces == null)
{
// Listed in priority order
_knownInterfaces = new Type[]
{
Globals.TypeOfIDictionaryGeneric,
Globals.TypeOfIDictionary,
Globals.TypeOfIListGeneric,
Globals.TypeOfICollectionGeneric,
Globals.TypeOfIList,
Globals.TypeOfIEnumerableGeneric,
Globals.TypeOfICollection,
Globals.TypeOfIEnumerable
};
}
return _knownInterfaces;
}
}
void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute)
{
this.kind = kind;
if (itemType != null)
{
this.itemType = itemType;
this.isItemTypeNullable = DataContract.IsTypeNullable(itemType);
bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary);
string itemName = null, keyName = null, valueName = null;
if (collectionContractAttribute != null)
{
if (collectionContractAttribute.IsItemNameSetExplicit)
{
if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType))));
itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName);
itemNameSetExplicit = true;
}
if (collectionContractAttribute.IsKeyNameSetExplicit)
{
if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName)));
keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName);
}
if (collectionContractAttribute.IsValueNameSetExplicit)
{
if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName)));
valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName);
}
}
XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3);
this.Name = dictionary.Add(this.StableName.Name);
this.Namespace = dictionary.Add(this.StableName.Namespace);
this.itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name;
this.collectionItemName = dictionary.Add(this.itemName);
if (isDictionary)
{
this.keyName = keyName ?? Globals.KeyLocalName;
this.valueName = valueName ?? Globals.ValueLocalName;
}
}
if (collectionContractAttribute != null)
{
this.IsReference = collectionContractAttribute.IsReference;
}
}
internal CollectionDataContractCriticalHelper(CollectionKind kind)
: base()
{
Init(kind, null, null);
}
// array
internal CollectionDataContractCriticalHelper(Type type)
: base(type)
{
if (type == Globals.TypeOfArray)
type = Globals.TypeOfObjectArray;
if (type.GetArrayRank() > 1)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SupportForMultidimensionalArraysNotPresent)));
this.StableName = DataContract.GetStableName(type);
Init(CollectionKind.Array, type.GetElementType(), null);
}
// array
internal CollectionDataContractCriticalHelper(Type type, DataContract itemContract)
: base(type)
{
if (type.GetArrayRank() > 1)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SupportForMultidimensionalArraysNotPresent)));
this.StableName = CreateQualifiedName(Globals.ArrayPrefix + itemContract.StableName.Name, itemContract.StableName.Namespace);
this.itemContract = itemContract;
Init(CollectionKind.Array, type.GetElementType(), null);
}
// read-only collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string serializationExceptionMessage, string deserializationExceptionMessage)
: base(type)
{
if (getEnumeratorMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type))));
if (itemType == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type))));
CollectionDataContractAttribute collectionContractAttribute;
this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute);
Init(kind, itemType, collectionContractAttribute);
this.getEnumeratorMethod = getEnumeratorMethod;
this.serializationExceptionMessage = serializationExceptionMessage;
this.deserializationExceptionMessage = deserializationExceptionMessage;
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor)
: this(type, kind, itemType, getEnumeratorMethod, (string)null, (string)null)
{
if (addMethod == null && !type.IsInterface)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type))));
this.addMethod = addMethod;
this.constructor = constructor;
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)
{
this.isConstructorCheckRequired = isConstructorCheckRequired;
}
internal CollectionDataContractCriticalHelper(Type type, string invalidCollectionInSharedContractMessage)
: base(type)
{
Init(CollectionKind.Collection, null /*itemType*/, null);
this.invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage;
}
internal CollectionKind Kind
{
get { return kind; }
}
internal Type ItemType
{
get { return itemType; }
}
internal DataContract ItemContract
{
get
{
if (itemContract == null && UnderlyingType != null)
{
if (IsDictionary)
{
if (String.CompareOrdinal(KeyName, ValueName) == 0)
{
DataContract.ThrowInvalidDataContractException(
SR.GetString(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName),
UnderlyingType);
}
itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName });
// Ensure that DataContract gets added to the static DataContract cache for dictionary items
DataContract.GetDataContract(ItemType);
}
else
{
itemContract = DataContract.GetDataContract(ItemType);
}
}
return itemContract;
}
set
{
itemContract = value;
}
}
internal DataContract SharedTypeContract
{
get { return sharedTypeContract; }
set { sharedTypeContract = value; }
}
internal string ItemName
{
get { return itemName; }
set { itemName = value; }
}
internal bool IsConstructorCheckRequired
{
get { return isConstructorCheckRequired; }
set { isConstructorCheckRequired = value; }
}
public XmlDictionaryString CollectionItemName
{
get { return collectionItemName; }
}
internal string KeyName
{
get { return keyName; }
set { keyName = value; }
}
internal string ValueName
{
get { return valueName; }
set { valueName = value; }
}
internal bool IsDictionary
{
get { return KeyName != null; }
}
public string SerializationExceptionMessage
{
get { return serializationExceptionMessage; }
}
public string DeserializationExceptionMessage
{
get { return deserializationExceptionMessage; }
}
public XmlDictionaryString ChildElementNamespace
{
get { return childElementNamespace; }
set { childElementNamespace = value; }
}
internal bool IsItemTypeNullable
{
get { return isItemTypeNullable; }
set { isItemTypeNullable = value; }
}
internal MethodInfo GetEnumeratorMethod
{
get { return getEnumeratorMethod; }
}
internal MethodInfo AddMethod
{
get { return addMethod; }
}
internal ConstructorInfo Constructor
{
get { return constructor; }
}
internal override DataContractDictionary KnownDataContracts
{
get
{
if (!isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!isKnownTypeAttributeChecked)
{
knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Thread.MemoryBarrier();
isKnownTypeAttributeChecked = true;
}
}
}
return knownDataContracts;
}
set { knownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage
{
get { return invalidCollectionInSharedContractMessage; }
}
internal bool ItemNameSetExplicit
{
get { return itemNameSetExplicit; }
}
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
{
get { return xmlFormatWriterDelegate; }
set { xmlFormatWriterDelegate = value; }
}
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
{
get { return xmlFormatReaderDelegate; }
set { xmlFormatReaderDelegate = value; }
}
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
{
get { return xmlFormatGetOnlyCollectionReaderDelegate; }
set { xmlFormatGetOnlyCollectionReaderDelegate = value; }
}
}
DataContract GetSharedTypeContract(Type type)
{
if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
{
return this;
}
// ClassDataContract.IsNonAttributedTypeValidForSerialization does not need to be called here. It should
// never pass because it returns false for types that implement any of CollectionDataContract.KnownInterfaces
if (type.IsSerializable || type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return new ClassDataContract(type);
}
return null;
}
internal static bool IsCollectionInterface(Type type)
{
if (type.IsGenericType)
type = type.GetGenericTypeDefinition();
return ((IList<Type>)KnownInterfaces).Contains(type);
}
internal static bool IsCollection(Type type)
{
Type itemType;
return IsCollection(type, out itemType);
}
internal static bool IsCollection(Type type, out Type itemType)
{
return IsCollectionHelper(type, out itemType, true /*constructorRequired*/);
}
internal static bool IsCollection(Type type, bool constructorRequired, bool skipIfReadOnlyContract)
{
Type itemType;
return IsCollectionHelper(type, out itemType, constructorRequired, skipIfReadOnlyContract);
}
static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired, bool skipIfReadOnlyContract = false)
{
if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null)
{
itemType = type.GetElementType();
return true;
}
DataContract dataContract;
return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired, skipIfReadOnlyContract);
}
internal static bool TryCreate(Type type, out DataContract dataContract)
{
Type itemType;
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/);
}
internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
}
internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType)
{
InterfaceMapping mapping = type.GetInterfaceMap(interfaceType);
for (int i = 0; i < mapping.TargetMethods.Length; i++)
{
if (mapping.InterfaceMethods[i].Name == name)
return mapping.InterfaceMethods[i];
}
return null;
}
static bool IsArraySegment(Type t)
{
return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.Globalization, FxCop.Rule.DoNotPassLiteralsAsLocalizedParameters, Justification = "Private code.")]
static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired, bool skipIfReadOnlyContract = false)
{
dataContract = null;
itemType = Globals.TypeOfObject;
if (DataContract.GetBuiltInDataContract(type) != null)
{
return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/,
SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract);
}
MethodInfo addMethod, getEnumeratorMethod;
bool hasCollectionDataContract = IsCollectionDataContract(type);
bool isReadOnlyContract = false;
string serializationExceptionMessage = null, deserializationExceptionMessage = null;
Type baseType = type.BaseType;
bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject
&& baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false;
// Avoid creating an invalid collection contract for Serializable types since we can create a ClassDataContract instead
bool createContractWithException = isBaseTypeCollection && !type.IsSerializable;
if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeCannotHaveDataContract, null, ref dataContract);
}
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type))
{
return false;
}
if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (type.IsInterface)
{
Type interfaceTypeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
addMethod = null;
if (type.IsGenericType)
{
Type[] genericArgs = type.GetGenericArguments();
if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric)
{
itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs);
addMethod = type.GetMethod(Globals.AddMethodName);
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName);
}
else
{
itemType = genericArgs[0];
if (interfaceTypeToCheck == Globals.TypeOfICollectionGeneric || interfaceTypeToCheck == Globals.TypeOfIListGeneric)
{
addMethod = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType).GetMethod(Globals.AddMethodName);
}
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName);
}
}
else
{
if (interfaceTypeToCheck == Globals.TypeOfIDictionary)
{
itemType = typeof(KeyValue<object, object>);
addMethod = type.GetMethod(Globals.AddMethodName);
}
else
{
itemType = Globals.TypeOfObject;
if (interfaceTypeToCheck == Globals.TypeOfIList)
{
addMethod = Globals.TypeOfIList.GetMethod(Globals.AddMethodName);
}
}
getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName);
}
if (tryCreate)
dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/);
return true;
}
}
}
ConstructorInfo defaultCtor = null;
if (!type.IsValueType)
{
defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null);
if (defaultCtor == null && constructorRequired)
{
// All collection types could be considered read-only collections except collection types that are marked [Serializable].
// Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons.
// DataContract types and POCO types cannot be collection types, so they don't need to be factored in
if (type.IsSerializable)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract);
}
else
{
isReadOnlyContract = true;
GetReadOnlyCollectionExceptionMessages(type, hasCollectionDataContract, SR.CollectionTypeDoesNotHaveDefaultCtor, null, out serializationExceptionMessage, out deserializationExceptionMessage);
}
}
}
Type knownInterfaceType = null;
CollectionKind kind = CollectionKind.None;
bool multipleDefinitions = false;
Type[] interfaceTypes = type.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
Type interfaceTypeToCheck = interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
CollectionKind currentKind = (CollectionKind)(i + 1);
if (kind == CollectionKind.None || currentKind < kind)
{
kind = currentKind;
knownInterfaceType = interfaceType;
multipleDefinitions = false;
}
else if ((kind & currentKind) == currentKind)
multipleDefinitions = true;
break;
}
}
}
if (kind == CollectionKind.None)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable)
{
if (multipleDefinitions)
knownInterfaceType = Globals.TypeOfIEnumerable;
itemType = knownInterfaceType.IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject;
GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType },
false /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
if (addMethod == null)
{
// All collection types could be considered read-only collections except collection types that are marked [Serializable].
// Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons.
// DataContract types and POCO types cannot be collection types, so they don't need to be factored in.
if (type.IsSerializable || skipIfReadOnlyContract)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException && !skipIfReadOnlyContract,
SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract);
}
else
{
isReadOnlyContract = true;
GetReadOnlyCollectionExceptionMessages(type, hasCollectionDataContract, SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), out serializationExceptionMessage, out deserializationExceptionMessage);
}
}
if (tryCreate)
{
dataContract = isReadOnlyContract ?
new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, serializationExceptionMessage, deserializationExceptionMessage) :
new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
}
else
{
if (multipleDefinitions)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract);
}
Type[] addMethodTypeArray = null;
switch (kind)
{
case CollectionKind.GenericDictionary:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
bool isOpenGeneric = knownInterfaceType.IsGenericTypeDefinition
|| (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter);
itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.Dictionary:
addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.GenericList:
case CollectionKind.GenericCollection:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
itemType = addMethodTypeArray[0];
break;
case CollectionKind.List:
itemType = Globals.TypeOfObject;
addMethodTypeArray = new Type[] { itemType };
break;
}
if (tryCreate)
{
GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray,
true /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
dataContract = isReadOnlyContract ?
new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, serializationExceptionMessage, deserializationExceptionMessage) :
new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
}
return !(isReadOnlyContract && skipIfReadOnlyContract);
}
internal static bool IsCollectionDataContract(Type type)
{
return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false);
}
static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract)
{
if (hasCollectionDataContract)
{
if (tryCreate)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.GetString(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param)));
return true;
}
if (createContractWithException)
{
if (tryCreate)
dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.GetString(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param));
return true;
}
return false;
}
static void GetReadOnlyCollectionExceptionMessages(Type type, bool hasCollectionDataContract, string message, string param, out string serializationExceptionMessage, out string deserializationExceptionMessage)
{
serializationExceptionMessage = GetInvalidCollectionMessage(message, SR.GetString(hasCollectionDataContract ? SR.InvalidCollectionDataContract : SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param);
deserializationExceptionMessage = GetInvalidCollectionMessage(message, SR.GetString(SR.ReadOnlyCollectionDeserialization, DataContract.GetClrTypeFullName(type)), param);
}
static string GetInvalidCollectionMessage(string message, string nestedMessage, string param)
{
return (param == null) ? SR.GetString(message, nestedMessage) : SR.GetString(message, nestedMessage, param);
}
static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod)
{
InterfaceMapping mapping = type.GetInterfaceMap(interfaceType);
for (int i = 0; i < mapping.TargetMethods.Length; i++)
{
if (mapping.InterfaceMethods[i].Name == Globals.AddMethodName)
addMethod = mapping.InterfaceMethods[i];
else if (mapping.InterfaceMethods[i].Name == Globals.GetEnumeratorMethodName)
getEnumeratorMethod = mapping.InterfaceMethods[i];
}
}
static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod)
{
addMethod = getEnumeratorMethod = null;
if (addMethodOnInterface)
{
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, null, addMethodTypeArray, null);
if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0])
{
FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
Type[] parentInterfaceTypes = interfaceType.GetInterfaces();
foreach (Type parentInterfaceType in parentInterfaceTypes)
{
if (IsKnownInterface(parentInterfaceType))
{
FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
break;
}
}
}
}
}
}
else
{
// GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, addMethodTypeArray, null);
}
if (getEnumeratorMethod == null)
{
getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType))
{
Type ienumerableInterface = interfaceType.GetInterface("System.Collections.Generic.IEnumerable*");
if (ienumerableInterface == null)
ienumerableInterface = Globals.TypeOfIEnumerable;
getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface);
}
}
}
static bool IsKnownInterface(Type type)
{
Type typeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
foreach (Type knownInterfaceType in KnownInterfaces)
{
if (typeToCheck == knownInterfaceType)
{
return true;
}
}
return false;
}
[Fx.Tag.SecurityNote(Critical = "Sets critical properties on CollectionDataContract .",
Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
internal override DataContract BindGenericParameters(DataContract[] paramContracts, Dictionary<DataContract, DataContract> boundContracts)
{
DataContract boundContract;
if (boundContracts.TryGetValue(this, out boundContract))
return boundContract;
CollectionDataContract boundCollectionContract = new CollectionDataContract(Kind);
boundContracts.Add(this, boundCollectionContract);
boundCollectionContract.ItemContract = this.ItemContract.BindGenericParameters(paramContracts, boundContracts);
boundCollectionContract.IsItemTypeNullable = !boundCollectionContract.ItemContract.IsValueType;
boundCollectionContract.ItemName = ItemNameSetExplicit ? this.ItemName : boundCollectionContract.ItemContract.StableName.Name;
boundCollectionContract.KeyName = this.KeyName;
boundCollectionContract.ValueName = this.ValueName;
boundCollectionContract.StableName = CreateQualifiedName(DataContract.ExpandGenericParameters(XmlConvert.DecodeName(this.StableName.Name), new GenericNameProvider(DataContract.GetClrTypeFullName(this.UnderlyingType), paramContracts)),
IsCollectionDataContract(UnderlyingType) ? this.StableName.Namespace : DataContract.GetCollectionNamespace(boundCollectionContract.ItemContract.StableName.Namespace));
return boundCollectionContract;
}
internal override DataContract GetValidContract(SerializationMode mode)
{
if (mode == SerializationMode.SharedType)
{
if (SharedTypeContract == null)
DataContract.ThrowTypeNotSerializable(UnderlyingType);
return SharedTypeContract;
}
ThrowIfInvalid();
return this;
}
void ThrowIfInvalid()
{
if (InvalidCollectionInSharedContractMessage != null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage));
}
internal override DataContract GetValidContract()
{
if (this.IsConstructorCheckRequired)
{
CheckConstructor();
}
return this;
}
[Fx.Tag.SecurityNote(Critical = "Sets the critical IsConstructorCheckRequired property on CollectionDataContract.",
Safe = "Does not leak anything.")]
[SecuritySafeCritical]
void CheckConstructor()
{
if (this.Constructor == null)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType))));
}
else
{
this.IsConstructorCheckRequired = false;
}
}
internal override bool IsValidContract(SerializationMode mode)
{
if (mode == SerializationMode.SharedType)
return (SharedTypeContract != null);
return (InvalidCollectionInSharedContractMessage == null);
}
[Fx.Tag.SecurityNote(Miscellaneous =
"RequiresReview - Calculates whether this collection requires MemberAccessPermission for deserialization."
+ " Since this information is used to determine whether to give the generated code access"
+ " permissions to private members, any changes to the logic should be reviewed.")]
internal bool RequiresMemberAccessForRead(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
if (ConstructorRequiresMemberAccess(Constructor))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustCollectionContractNoPublicConstructor,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.AddMethod))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustCollectionContractAddMethodNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.AddMethod.Name),
securityException));
}
return true;
}
return false;
}
[Fx.Tag.SecurityNote(Miscellaneous =
"RequiresReview - Calculates whether this collection requires MemberAccessPermission for serialization."
+ " Since this information is used to determine whether to give the generated code access"
+ " permissions to private members, any changes to the logic should be reviewed.")]
internal bool RequiresMemberAccessForWrite(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
return false;
}
internal override bool Equals(object other, Dictionary<DataContractPairKey, object> checkedContracts)
{
if (IsEqualOrChecked(other, checkedContracts))
return true;
if (base.Equals(other, checkedContracts))
{
CollectionDataContract dataContract = other as CollectionDataContract;
if (dataContract != null)
{
bool thisItemTypeIsNullable = (ItemContract == null) ? false : !ItemContract.IsValueType;
bool otherItemTypeIsNullable = (dataContract.ItemContract == null) ? false : !dataContract.ItemContract.IsValueType;
return ItemName == dataContract.ItemName &&
(IsItemTypeNullable || thisItemTypeIsNullable) == (dataContract.IsItemTypeNullable || otherItemTypeIsNullable) &&
ItemContract.Equals(dataContract.ItemContract, checkedContracts);
}
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
XmlFormatWriterDelegate(xmlWriter, obj, context, this);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
xmlReader.Read();
object o = null;
if (context.IsGetOnlyCollection)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
else
{
o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
xmlReader.ReadEndElement();
return o;
}
public class DictionaryEnumerator : IEnumerator<KeyValue<object, object>>
{
IDictionaryEnumerator enumerator;
public DictionaryEnumerator(IDictionaryEnumerator enumerator)
{
this.enumerator = enumerator;
}
public void Dispose()
{
}
public bool MoveNext()
{
return enumerator.MoveNext();
}
public KeyValue<object, object> Current
{
get { return new KeyValue<object, object>(enumerator.Key, enumerator.Value); }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
enumerator.Reset();
}
}
public class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>>
{
IEnumerator<KeyValuePair<K, V>> enumerator;
public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator)
{
this.enumerator = enumerator;
}
public void Dispose()
{
}
public bool MoveNext()
{
return enumerator.MoveNext();
}
public KeyValue<K, V> Current
{
get
{
KeyValuePair<K, V> current = enumerator.Current;
return new KeyValue<K, V>(current.Key, current.Value);
}
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
enumerator.Reset();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using Microsoft.Extensions.Logging;
using Orleans.Messaging;
using Orleans.Serialization;
using System.Threading.Tasks;
namespace Orleans.Runtime.Messaging
{
internal class IncomingMessageAcceptor : DedicatedAsynchAgent
{
private readonly ConcurrentObjectPool<SaeaPoolWrapper> receiveEventArgsPool;
private const int SocketBufferSize = 1024 * 128; // 128 kb
private const int PreambleMaxSize = 1024 * 4; // 4 kb
private readonly IPEndPoint listenAddress;
private Action<Message> sniffIncomingMessageHandler;
private readonly LingerOption receiveLingerOption = new LingerOption(true, 0);
internal Socket AcceptingSocket;
protected MessageCenter MessageCenter;
protected HashSet<Socket> OpenReceiveSockets;
private bool isStopping = false;
protected readonly MessageFactory MessageFactory;
private static readonly CounterStatistic allocatedSocketEventArgsCounter
= CounterStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_ALLOCATED_SOCKET_EVENT_ARGS, false);
private readonly CounterStatistic checkedOutSocketEventArgsCounter;
private readonly CounterStatistic checkedInSocketEventArgsCounter;
private readonly SerializationManager serializationManager;
public Action<Message> SniffIncomingMessage
{
set
{
if (sniffIncomingMessageHandler != null)
throw new InvalidOperationException("IncomingMessageAcceptor SniffIncomingMessage already set");
sniffIncomingMessageHandler = value;
}
}
private const int LISTEN_BACKLOG_SIZE = 1024;
protected SocketDirection SocketDirection { get; private set; }
// Used for holding enough info to handle receive completion
internal IncomingMessageAcceptor(MessageCenter msgCtr, IPEndPoint here, SocketDirection socketDirection, MessageFactory messageFactory, SerializationManager serializationManager,
ExecutorService executorService, ILoggerFactory loggerFactory)
:base(executorService, loggerFactory)
{
this.loggerFactory = loggerFactory;
Log = loggerFactory.CreateLogger<IncomingMessageAcceptor>();
MessageCenter = msgCtr;
listenAddress = here;
this.MessageFactory = messageFactory;
this.receiveEventArgsPool = new ConcurrentObjectPool<SaeaPoolWrapper>(() => this.CreateSocketReceiveAsyncEventArgsPoolWrapper());
this.serializationManager = serializationManager;
if (here == null)
listenAddress = MessageCenter.MyAddress.Endpoint;
AcceptingSocket = MessageCenter.SocketManager.GetAcceptingSocketForEndpoint(listenAddress);
Log.Info(ErrorCode.Messaging_IMA_OpenedListeningSocket, "Opened a listening socket at address " + AcceptingSocket.LocalEndPoint);
OpenReceiveSockets = new HashSet<Socket>();
OnFault = FaultBehavior.CrashOnFault;
SocketDirection = socketDirection;
checkedOutSocketEventArgsCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_CHECKED_OUT_SOCKET_EVENT_ARGS, false);
checkedInSocketEventArgsCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_CHECKED_IN_SOCKET_EVENT_ARGS, false);
IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_IN_USE_SOCKET_EVENT_ARGS,
() => checkedOutSocketEventArgsCounter.GetCurrentValue() - checkedInSocketEventArgsCounter.GetCurrentValue());
}
protected override void Run()
{
try
{
AcceptingSocket.Listen(LISTEN_BACKLOG_SIZE);
StartAccept(null);
}
catch (Exception ex)
{
Log.Error(ErrorCode.MessagingAcceptAsyncSocketException, "Exception beginning accept on listening socket", ex);
throw;
}
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Started accepting connections.");
}
public override void Stop()
{
base.Stop();
this.isStopping = true;
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Disconnecting the listening socket");
SocketManager.CloseSocket(AcceptingSocket);
Socket[] temp;
lock (Lockable)
{
temp = new Socket[OpenReceiveSockets.Count];
OpenReceiveSockets.CopyTo(temp);
}
foreach (var socket in temp)
{
SafeCloseSocket(socket);
}
lock (Lockable)
{
ClearSockets();
}
}
protected virtual bool RecordOpenedSocket(Socket sock)
{
GrainId client;
if (!ReceiveSocketPreample(sock, false, out client)) return false;
NetworkingStatisticsGroup.OnOpenedReceiveSocket();
return true;
}
protected bool ReceiveSocketPreample(Socket sock, bool expectProxiedConnection, out GrainId client)
{
client = null;
if (Cts.IsCancellationRequested) return false;
if (!ReadConnectionPreamble(sock, out client))
{
return false;
}
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace(ErrorCode.MessageAcceptor_Connection, "Received connection from {0} at source address {1}", client, sock.RemoteEndPoint.ToString());
if (expectProxiedConnection)
{
// Proxied Gateway Connection - must have sender id
if (client.Equals(Constants.SiloDirectConnectionId))
{
Log.Error(ErrorCode.MessageAcceptor_NotAProxiedConnection, $"Gateway received unexpected non-proxied connection from {client} at source address {sock.RemoteEndPoint}");
return false;
}
}
else
{
// Direct connection - should not have sender id
if (!client.Equals(Constants.SiloDirectConnectionId))
{
Log.Error(ErrorCode.MessageAcceptor_UnexpectedProxiedConnection, $"Silo received unexpected proxied connection from {client} at source address {sock.RemoteEndPoint}");
return false;
}
}
lock (Lockable)
{
OpenReceiveSockets.Add(sock);
}
return true;
}
private bool ReadConnectionPreamble(Socket socket, out GrainId grainId)
{
grainId = null;
byte[] buffer = null;
try
{
buffer = ReadFromSocket(socket, sizeof(int)); // Read the size
if (buffer == null) return false;
Int32 size = BitConverter.ToInt32(buffer, 0);
if (size > 0)
{
buffer = ReadFromSocket(socket, size); // Receive the client ID
if (buffer == null) return false;
grainId = GrainIdExtensions.FromByteArray(buffer);
}
return true;
}
catch (Exception exc)
{
Log.Error(ErrorCode.GatewayFailedToParse,
$"Failed to convert the data that read from the socket. buffer = {Utils.EnumerableToString(buffer)}, from endpoint {socket.RemoteEndPoint}.", exc);
return false;
}
}
private byte[] ReadFromSocket(Socket sock, int expected)
{
if (expected > PreambleMaxSize)
{
Log.Warn(ErrorCode.GatewayAcceptor_InvalidSize,
"Invalid expected size {0} while receiving connection preamble data from endpoint {1}.", expected, sock.RemoteEndPoint);
return null;
}
var buffer = new byte[expected];
int offset = 0;
while (offset < buffer.Length)
{
try
{
int bytesRead = sock.Receive(buffer, offset, buffer.Length - offset, SocketFlags.None);
if (bytesRead == 0)
{
Log.Warn(ErrorCode.GatewayAcceptor_SocketClosed,
"Remote socket closed while receiving connection preamble data from endpoint {0}.", sock.RemoteEndPoint);
return null;
}
offset += bytesRead;
}
catch (Exception ex)
{
Log.Warn(ErrorCode.GatewayAcceptor_ExceptionReceiving,
"Exception receiving connection preamble data from endpoint " + sock.RemoteEndPoint, ex);
return null;
}
}
return buffer;
}
protected virtual void RecordClosedSocket(Socket sock)
{
if (TryRemoveClosedSocket(sock))
NetworkingStatisticsGroup.OnClosedReceivingSocket();
}
protected bool TryRemoveClosedSocket(Socket sock)
{
lock (Lockable)
{
return OpenReceiveSockets.Remove(sock);
}
}
protected virtual void ClearSockets()
{
lock (Lockable)
{
OpenReceiveSockets.Clear();
}
}
/// <summary>
/// Begins an operation to accept a connection request from the client.
/// </summary>
/// <param name="acceptEventArg">The context object to use when issuing
/// the accept operation on the server's listening socket.</param>
private void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
if (acceptEventArg == null)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.UserToken = this;
acceptEventArg.Completed += OnAcceptCompleted;
}
else
{
// We have handed off the connection info from the
// accepting socket to the receiving socket. So, now we will clear
// the socket info from that object, so it will be
// ready for a new socket
acceptEventArg.AcceptSocket = null;
}
// Socket.AcceptAsync begins asynchronous operation to accept the connection.
// Note the listening socket will pass info to the SocketAsyncEventArgs
// object that has the Socket that does the accept operation.
// If you do not create a Socket object and put it in the SAEA object
// before calling AcceptAsync and use the AcceptSocket property to get it,
// then a new Socket object will be created by .NET.
try
{
// AcceptAsync returns true if the I / O operation is pending.The SocketAsyncEventArgs.Completed event
// on the e parameter will be raised upon completion of the operation.Returns false if the I/O operation
// completed synchronously. The SocketAsyncEventArgs.Completed event on the e parameter will not be raised
// and the e object passed as a parameter may be examined immediately after the method call returns to retrieve
// the result of the operation.
while (!AcceptingSocket.AcceptAsync(acceptEventArg))
{
ProcessAccept(acceptEventArg, true);
}
}
catch (SocketException ex)
{
Log.Warn(ErrorCode.MessagingAcceptAsyncSocketException, "Socket error on accepting socket during AcceptAsync {0}", ex.SocketErrorCode);
RestartAcceptingSocket();
}
catch (ObjectDisposedException)
{
// Socket was closed, but we're not shutting down; we need to open a new socket and start over...
// Close the old socket and open a new one
Log.Warn(ErrorCode.MessagingAcceptingSocketClosed, "Accepting socket was closed when not shutting down");
RestartAcceptingSocket();
}
catch (Exception ex)
{
// There was a network error. We need to get a new accepting socket and re-issue an accept before we continue.
// Close the old socket and open a new one
Log.Warn(ErrorCode.MessagingAcceptAsyncSocketException, "Exception on accepting socket during AcceptAsync", ex);
RestartAcceptingSocket();
}
}
private void OnAcceptCompleted(object sender, SocketAsyncEventArgs e)
{
((IncomingMessageAcceptor)e.UserToken).ProcessAccept(e, false);
}
/// <summary>
/// Process the accept for the socket listener.
/// </summary>
/// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param>
/// <param name="completedSynchronously">Shows whether AcceptAsync completed synchronously,
/// if true - the next accept operation woun't be started. Used for avoiding potential stack overflows.</param>
private void ProcessAccept(SocketAsyncEventArgs e, bool completedSynchronously)
{
var ima = e.UserToken as IncomingMessageAcceptor;
try
{
if (ima == null)
{
Log.Warn(ErrorCode.Messaging_IMA_AcceptCallbackUnexpectedState,
"AcceptCallback invoked with an unexpected async state of type {0}",
e.UserToken?.GetType().ToString() ?? "null");
return;
}
if (e.SocketError != SocketError.Success)
{
RestartAcceptingSocket();
return;
}
// First check to see if we're shutting down, in which case there's no point in doing anything other
// than closing the accepting socket and returning.
if (ima.Cts == null || ima.Cts.IsCancellationRequested)
{
SocketManager.CloseSocket(ima.AcceptingSocket);
ima.Log.Info(ErrorCode.Messaging_IMA_ClosingSocket, "Closing accepting socket during shutdown");
return;
}
Socket sock = e.AcceptSocket;
if (sock.Connected)
{
if (ima.Log.IsEnabled(LogLevel.Debug)) ima.Log.Debug("Received a connection from {0}", sock.RemoteEndPoint);
// Finally, process the incoming request:
// Prep the socket so it will reset on close
sock.LingerState = receiveLingerOption;
Task.Factory.StartNew(() =>
{
// Add the socket to the open socket collection
if (ima.RecordOpenedSocket(sock))
{
// Get the socket for the accepted client connection and put it into the
// ReadEventArg object user token.
var readEventArgs = GetSocketReceiveAsyncEventArgs(sock);
StartReceiveAsync(sock, readEventArgs, ima);
}
else
{
ima.SafeCloseSocket(sock);
}
}).Ignore();
}
// The next accept will be started in the caller method
if (completedSynchronously)
{
return;
}
// Start a new Accept
StartAccept(e);
}
catch (Exception ex)
{
var logger = ima?.Log ?? this.Log;
logger.Error(ErrorCode.Messaging_IMA_ExceptionAccepting, "Unexpected exception in IncomingMessageAccepter.AcceptCallback", ex);
RestartAcceptingSocket();
}
}
private void StartReceiveAsync(Socket sock, SocketAsyncEventArgs readEventArgs, IncomingMessageAcceptor ima)
{
try
{
// Set up the async receive
if (!sock.ReceiveAsync(readEventArgs))
{
ProcessReceive(readEventArgs);
}
}
catch (Exception exception)
{
var socketException = exception as SocketException;
var context = readEventArgs.UserToken as ReceiveCallbackContext;
ima.Log.Warn(ErrorCode.Messaging_IMA_NewBeginReceiveException,
$"Exception on new socket during ReceiveAsync with RemoteEndPoint " +
$"{socketException?.SocketErrorCode}: {context?.RemoteEndPoint}", exception);
ima.SafeCloseSocket(sock);
FreeSocketAsyncEventArgs(readEventArgs);
}
}
private SocketAsyncEventArgs GetSocketReceiveAsyncEventArgs(Socket sock)
{
var saea = receiveEventArgsPool.Allocate();
var token = ((ReceiveCallbackContext) saea.SocketAsyncEventArgs.UserToken);
token.IMA = this;
token.Socket = sock;
checkedOutSocketEventArgsCounter.Increment();
return saea.SocketAsyncEventArgs;
}
private SaeaPoolWrapper CreateSocketReceiveAsyncEventArgsPoolWrapper()
{
SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs();
readEventArgs.Completed += OnReceiveCompleted;
var buffer = new byte[SocketBufferSize];
// SocketAsyncEventArgs and ReceiveCallbackContext's buffer shares the same buffer list with pinned arrays.
readEventArgs.SetBuffer(buffer, 0, buffer.Length);
var poolWrapper = new SaeaPoolWrapper(readEventArgs);
// Creates with incomplete state: IMA should be set before using
readEventArgs.UserToken = new ReceiveCallbackContext(poolWrapper, this.MessageFactory, this.serializationManager, this.loggerFactory);
allocatedSocketEventArgsCounter.Increment();
return poolWrapper;
}
private void FreeSocketAsyncEventArgs(SocketAsyncEventArgs args)
{
var receiveToken = (ReceiveCallbackContext) args.UserToken;
receiveToken.Reset();
args.AcceptSocket = null;
checkedInSocketEventArgsCounter.Increment();
receiveEventArgsPool.Free(receiveToken.SaeaPoolWrapper);
}
private static void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)
{
if (e.LastOperation != SocketAsyncOperation.Receive)
{
throw new ArgumentException("The last operation completed on the socket was not a receive");
}
var rcc = e.UserToken as ReceiveCallbackContext;
if (rcc.IMA.Log.IsEnabled(LogLevel.Trace)) rcc.IMA.Log.Trace("Socket receive completed from remote " + e.RemoteEndPoint);
rcc.IMA.ProcessReceive(e);
}
/// <summary>
/// This method is invoked when an asynchronous receive operation completes.
/// If the remote host closed the connection, then the socket is closed.
/// </summary>
/// <param name="e">SocketAsyncEventArg associated with the completed receive operation.</param>
private void ProcessReceive(SocketAsyncEventArgs e)
{
var rcc = e.UserToken as ReceiveCallbackContext;
// If no data was received, close the connection. This is a normal
// situation that shows when the remote host has finished sending data.
if (e.BytesTransferred <= 0)
{
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Closing recieving socket: " + e.RemoteEndPoint);
rcc.IMA.SafeCloseSocket(rcc.Socket);
FreeSocketAsyncEventArgs(e);
return;
}
if (e.SocketError != SocketError.Success)
{
Log.Warn(ErrorCode.Messaging_IMA_NewBeginReceiveException,
$"Socket error on new socket during ReceiveAsync with RemoteEndPoint: {e.SocketError}");
rcc.IMA.SafeCloseSocket(rcc.Socket);
FreeSocketAsyncEventArgs(e);
return;
}
Socket sock = rcc.Socket;
try
{
rcc.ProcessReceived(e);
}
catch (Exception ex)
{
rcc.IMA.Log.Error(ErrorCode.Messaging_IMA_BadBufferReceived,
$"ProcessReceivedBuffer exception with RemoteEndPoint {rcc.RemoteEndPoint}: ", ex);
// There was a problem with the buffer, presumably data corruption, so give up
rcc.IMA.SafeCloseSocket(rcc.Socket);
FreeSocketAsyncEventArgs(e);
// And we're done
return;
}
StartReceiveAsync(sock, e, rcc.IMA);
}
protected virtual void HandleMessage(Message msg, Socket receivedOnSocket)
{
// See it's a Ping message, and if so, short-circuit it
object pingObj;
var requestContext = msg.RequestContextData;
if (requestContext != null &&
requestContext.TryGetValue(RequestContext.PING_APPLICATION_HEADER, out pingObj) &&
pingObj is bool &&
(bool)pingObj)
{
MessagingStatisticsGroup.OnPingReceive(msg.SendingSilo);
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Responding to Ping from {0}", msg.SendingSilo);
if (!msg.TargetSilo.Equals(MessageCenter.MyAddress)) // got ping that is not destined to me. For example, got a ping to my older incarnation.
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message rejection = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable,
$"The target silo is no longer active: target was {msg.TargetSilo.ToLongString()}, but this silo is {MessageCenter.MyAddress.ToLongString()}. " +
$"The rejected ping message is {msg}.");
MessageCenter.OutboundQueue.SendMessage(rejection);
}
else
{
var response = this.MessageFactory.CreateResponseMessage(msg);
response.BodyObject = Response.Done;
MessageCenter.SendMessage(response);
}
return;
}
// sniff message headers for directory cache management
sniffIncomingMessageHandler?.Invoke(msg);
// Don't process messages that have already timed out
if (msg.IsExpired)
{
msg.DropExpiredMessage(MessagingStatisticsGroup.Phase.Receive);
return;
}
// If we've stopped application message processing, then filter those out now
// Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here.
if (MessageCenter.IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && !Constants.SystemMembershipTableId.Equals(msg.SendingGrain))
{
// We reject new requests, and drop all other messages
if (msg.Direction != Message.Directions.Request) return;
MessagingStatisticsGroup.OnRejectedMessage(msg);
var reject = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, "Silo stopping");
MessageCenter.SendMessage(reject);
return;
}
// Make sure the message is for us. Note that some control messages may have no target
// information, so a null target silo is OK.
if ((msg.TargetSilo == null) || msg.TargetSilo.Matches(MessageCenter.MyAddress))
{
// See if it's a message for a client we're proxying.
if (MessageCenter.IsProxying && MessageCenter.TryDeliverToProxy(msg)) return;
// Nope, it's for us
MessageCenter.InboundQueue.PostMessage(msg);
return;
}
if (!msg.TargetSilo.Endpoint.Equals(MessageCenter.MyAddress.Endpoint))
{
// If the message is for some other silo altogether, then we need to forward it.
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Forwarding message {0} from {1} to silo {2}", msg.Id, msg.SendingSilo, msg.TargetSilo);
MessageCenter.OutboundQueue.SendMessage(msg);
return;
}
// If the message was for this endpoint but an older epoch, then reject the message
// (if it was a request), or drop it on the floor if it was a response or one-way.
if (msg.Direction == Message.Directions.Request)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message rejection = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Transient,
string.Format("The target silo is no longer active: target was {0}, but this silo is {1}. The rejected message is {2}.",
msg.TargetSilo.ToLongString(), MessageCenter.MyAddress.ToLongString(), msg));
MessageCenter.OutboundQueue.SendMessage(rejection);
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Rejecting an obsolete request; target was {0}, but this silo is {1}. The rejected message is {2}.",
msg.TargetSilo.ToLongString(), MessageCenter.MyAddress.ToLongString(), msg);
}
}
private void RestartAcceptingSocket()
{
try
{
if (this.isStopping)
{
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("System is stopping, I will not restart the accepting socket");
return;
}
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Restarting of the accepting socket");
SocketManager.CloseSocket(AcceptingSocket);
AcceptingSocket = MessageCenter.SocketManager.GetAcceptingSocketForEndpoint(listenAddress);
AcceptingSocket.Listen(LISTEN_BACKLOG_SIZE);
StartAccept(null);
}
catch (Exception ex)
{
Log.Error(ErrorCode.Runtime_Error_100016, "Unable to create a new accepting socket", ex);
throw;
}
}
private void SafeCloseSocket(Socket sock)
{
RecordClosedSocket(sock);
SocketManager.CloseSocket(sock);
}
private class ReceiveCallbackContext
{
private readonly MessageFactory messageFactory;
private readonly IncomingMessageBuffer _buffer;
private Socket socket;
public Socket Socket {
get { return socket; }
internal set
{
socket = value;
RemoteEndPoint = socket.RemoteEndPoint;
}
}
public EndPoint RemoteEndPoint { get; private set; }
public IncomingMessageAcceptor IMA { get; internal set; }
public SaeaPoolWrapper SaeaPoolWrapper { get; }
public ReceiveCallbackContext(SaeaPoolWrapper poolWrapper, MessageFactory messageFactory, SerializationManager serializationManager, ILoggerFactory loggerFactory)
{
this.messageFactory = messageFactory;
SaeaPoolWrapper = poolWrapper;
_buffer = new IncomingMessageBuffer(loggerFactory, serializationManager);
}
public void ProcessReceived(SocketAsyncEventArgs e)
{
try
{
_buffer.UpdateReceivedData(e.Buffer, e.BytesTransferred);
while (true)
{
Message msg = null;
try
{
if (!this._buffer.TryDecodeMessage(out msg)) break;
this.IMA.HandleMessage(msg, this.Socket);
}
catch (Exception exception)
{
// If deserialization completely failed or the message was one-way, rethrow the exception
// so that it can be handled at another level.
if (msg?.Headers == null || msg.Direction != Message.Directions.Request)
{
throw;
}
// The message body was not successfully decoded, but the headers were.
// Send a fast fail to the caller.
MessagingStatisticsGroup.OnRejectedMessage(msg);
var response = this.messageFactory.CreateResponseMessage(msg);
response.Result = Message.ResponseTypes.Error;
response.BodyObject = Response.ExceptionResponse(exception);
// Send the error response and continue processing the next message.
this.IMA.MessageCenter.SendMessage(response);
}
}
}
catch (Exception exc)
{
try
{
// Log details of receive state machine
IMA.Log.Error(ErrorCode.MessagingProcessReceiveBufferException,
$"Exception trying to process {e.BytesTransferred} bytes from endpoint {RemoteEndPoint}",
exc);
}
catch (Exception) { }
_buffer.Reset(); // Reset back to a hopefully good base state
throw;
}
}
public void Reset()
{
_buffer.Reset();
}
}
private class SaeaPoolWrapper : PooledResource<SaeaPoolWrapper>
{
public SocketAsyncEventArgs SocketAsyncEventArgs { get; }
public SaeaPoolWrapper(SocketAsyncEventArgs socketAsyncEventArgs)
{
SocketAsyncEventArgs = socketAsyncEventArgs;
}
}
}
}
| |
#if !BESTHTTP_DISABLE_SOCKETIO
using System;
using System.Collections.Generic;
namespace BestHTTP.SocketIO
{
using BestHTTP.JSON;
/// <summary>
/// This class able to fill it's properties by starting a HTTP request and parsing its result. After a successfull response it will store the parsed data.
/// </summary>
public sealed class HandshakeData
{
#region Public Handshake Data
/// <summary>
/// Session ID of this connection.
/// </summary>
public string Sid { get; private set; }
/// <summary>
/// List of possible updgrades.
/// </summary>
public List<string> Upgrades { get; private set; }
/// <summary>
/// What interval we have to set a ping message.
/// </summary>
public TimeSpan PingInterval { get; private set; }
/// <summary>
/// What time have to pass without an answer to our ping request when we can consider the connection disconnected.
/// </summary>
public TimeSpan PingTimeout { get; private set; }
#endregion
#region Public Misc Properties
/// <summary>
/// The SocketManager instance that this handshake data is bound to.
/// </summary>
public SocketManager Manager { get; private set; }
/// <summary>
/// Event handler that called when the handshake data received and parsed successfully.
/// </summary>
public Action<HandshakeData> OnReceived;
/// <summary>
/// Event handler that called when an error happens.
/// </summary>
public Action<HandshakeData, string> OnError;
#endregion
private HTTPRequest HandshakeRequest;
public HandshakeData(SocketManager manager)
{
this.Manager = manager;
}
/// <summary>
/// Internal function, this will start a regular GET request to the server to receive the handshake data.
/// </summary>
internal void Start()
{
if (HandshakeRequest != null)
return;
HandshakeRequest = new HTTPRequest(new Uri(string.Format("{0}?EIO={1}&transport=polling&t={2}-{3}{4}&b64=true",
Manager.Uri.ToString(),
SocketManager.MinProtocolVersion,
Manager.Timestamp,
Manager.RequestCounter++,
Manager.Options.BuildQueryParams())),
OnHandshakeCallback);
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
// Don't even try to cache it
HandshakeRequest.DisableCache = true;
#endif
HandshakeRequest.Send();
HTTPManager.Logger.Information("HandshakeData", "Handshake request sent");
}
/// <summary>
/// Internal function to be able to abort the request if necessary.
/// </summary>
internal void Abort()
{
if (HandshakeRequest != null)
HandshakeRequest.Abort();
HandshakeRequest = null;
OnReceived = null;
OnError = null;
}
/// <summary>
/// Private event handler that called when the handshake request finishes.
/// </summary>
private void OnHandshakeCallback(HTTPRequest req, HTTPResponse resp)
{
HandshakeRequest = null;
switch (req.State)
{
case HTTPRequestStates.Finished:
if (resp.IsSuccess)
{
HTTPManager.Logger.Information("HandshakeData", "Handshake data arrived: " + resp.DataAsText);
int idx = resp.DataAsText.IndexOf("{");
if (idx < 0)
{
RaiseOnError("Invalid handshake text: " + resp.DataAsText);
return;
}
var Handshake = Parse(resp.DataAsText.Substring(idx));
if (Handshake == null)
{
RaiseOnError("Parsing Handshake data failed: " + resp.DataAsText);
return;
}
if (OnReceived != null)
{
OnReceived(this);
OnReceived = null;
}
}
else
RaiseOnError(string.Format("Handshake request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
resp.StatusCode,
resp.Message,
resp.DataAsText,
req.CurrentUri));
break;
case HTTPRequestStates.Error:
RaiseOnError(req.Exception != null ? (req.Exception.Message + " " + req.Exception.StackTrace) : string.Empty);
break;
default:
RaiseOnError(req.State.ToString());
break;
}
}
#region Helper Methods
private void RaiseOnError(string err)
{
HTTPManager.Logger.Error("HandshakeData", "Handshake request failed with error: " + err);
if (OnError != null)
{
OnError(this, err);
OnError = null;
}
}
private HandshakeData Parse(string str)
{
bool success = false;
Dictionary<string, object> dict = Json.Decode(str, ref success) as Dictionary<string, object>;
if (!success)
return null;
try
{
this.Sid = GetString(dict, "sid");
this.Upgrades = GetStringList(dict, "upgrades");
this.PingInterval = TimeSpan.FromMilliseconds(GetInt(dict, "pingInterval"));
this.PingTimeout = TimeSpan.FromMilliseconds(GetInt(dict, "pingTimeout"));
}
catch
{
return null;
}
return this;
}
private static object Get(Dictionary<string, object> from, string key)
{
object value;
if (!from.TryGetValue(key, out value))
throw new System.Exception(string.Format("Can't get {0} from Handshake data!", key));
return value;
}
private static string GetString(Dictionary<string, object> from, string key)
{
return Get(from, key) as string;
}
private static List<string> GetStringList(Dictionary<string, object> from, string key)
{
List<object> value = Get(from, key) as List<object>;
List<string> result = new List<string>(value.Count);
for (int i = 0; i < value.Count; ++i)
{
string str = value[i] as string;
if (str != null)
result.Add(str);
}
return result;
}
private static int GetInt(Dictionary<string, object> from, string key)
{
return (int)(double)Get(from, key);
}
#endregion
}
}
#endif
| |
// Copyright (c) .NET Foundation. 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Infrastructure;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.SignalR.Messaging
{
internal class ScaleoutStream
{
private TaskCompletionSource<object> _taskCompletionSource;
private static Task _initializeDrainTask;
private TaskQueue _queue;
private StreamState _state;
private Exception _error;
private readonly int _size;
private readonly QueuingBehavior _queueBehavior;
private readonly ILogger _logger;
private readonly string _loggerPrefix;
private readonly IPerformanceCounterManager _perfCounters;
private readonly object _lockObj = new object();
public ScaleoutStream(ILogger logger, string loggerPrefix, QueuingBehavior queueBehavior, int size, IPerformanceCounterManager performanceCounters)
{
if (logger == null)
{
throw new ArgumentNullException("logger");
}
_logger = logger;
_loggerPrefix = loggerPrefix;
_size = size;
_perfCounters = performanceCounters;
_queueBehavior = queueBehavior;
InitializeCore();
}
private bool UsingTaskQueue
{
get
{
// Either you're always queuing or you're only queuing initially and you're in the initial state
return _queueBehavior == QueuingBehavior.Always ||
(_queueBehavior == QueuingBehavior.InitialOnly && _state == StreamState.Initial);
}
}
public void Open()
{
lock (_lockObj)
{
bool usingTaskQueue = UsingTaskQueue;
StreamState previousState;
if (ChangeState(StreamState.Open, out previousState))
{
_perfCounters.ScaleoutStreamCountOpen.Increment();
_perfCounters.ScaleoutStreamCountBuffering.Decrement();
_error = null;
if (usingTaskQueue)
{
EnsureQueueStarted();
if (previousState == StreamState.Initial && _queueBehavior == QueuingBehavior.InitialOnly)
{
_initializeDrainTask = Drain(_queue, _logger);
}
}
}
}
}
public Task Send(Func<object, Task> send, object state)
{
lock (_lockObj)
{
if (_error != null)
{
throw _error;
}
// If the queue is closed then stop sending
if (_state == StreamState.Closed)
{
throw new InvalidOperationException(Resources.Error_StreamClosed);
}
var context = new SendContext(this, send, state);
if (_initializeDrainTask != null && !_initializeDrainTask.IsCompleted)
{
// Wait on the draining of the queue before proceeding with the send
// NOTE: Calling .Wait() here is safe because the task wasn't created on an ASP.NET request thread
// and thus has no captured sync context
_initializeDrainTask.Wait();
}
if (UsingTaskQueue)
{
Task task = _queue.Enqueue(Send, context);
if (task == null)
{
// The task is null if the queue is full
throw new InvalidOperationException(Resources.Error_TaskQueueFull);
}
// Always observe the task in case the user doesn't handle it
return task.Catch(_logger);
}
return Send(context);
}
}
public void SetError(Exception error)
{
Log(LogLevel.Error, "Error has happened with the following exception: {0}.", error);
lock (_lockObj)
{
_perfCounters.ScaleoutErrorsTotal.Increment();
_perfCounters.ScaleoutErrorsPerSec.Increment();
Buffer();
_error = error;
}
}
public void Close()
{
Task task = TaskAsyncHelper.Empty;
lock (_lockObj)
{
if (ChangeState(StreamState.Closed))
{
_perfCounters.ScaleoutStreamCountOpen.RawValue = 0;
_perfCounters.ScaleoutStreamCountBuffering.RawValue = 0;
if (UsingTaskQueue)
{
// Ensure the queue is started
EnsureQueueStarted();
// Drain the queue to stop all sends
task = Drain(_queue, _logger);
}
}
}
if (UsingTaskQueue)
{
// Block until the queue is drained so no new work can be done
task.Wait();
}
}
private static Task Send(object state)
{
var context = (SendContext)state;
context.InvokeSend().Then(tcs =>
{
// Complete the task if the send is successful
tcs.TrySetResult(null);
},
context.TaskCompletionSource)
.Catch((ex, obj) =>
{
var ctx = (SendContext)obj;
ctx.Stream.Log(LogLevel.Error, "Send failed: {0}", ex);
lock (ctx.Stream._lockObj)
{
// Set the queue into buffering state
ctx.Stream.SetError(ex.InnerException);
// Otherwise just set this task as failed
ctx.TaskCompletionSource.TrySetUnwrappedException(ex);
}
},
context,
context.Stream._logger);
return context.TaskCompletionSource.Task;
}
private void Buffer()
{
lock (_lockObj)
{
if (ChangeState(StreamState.Buffering))
{
_perfCounters.ScaleoutStreamCountOpen.Decrement();
_perfCounters.ScaleoutStreamCountBuffering.Increment();
InitializeCore();
}
}
}
private void InitializeCore()
{
if (UsingTaskQueue)
{
Task task = DrainPreviousQueue();
_queue = new TaskQueue(task, _size);
_queue.QueueSizeCounter = _perfCounters.ScaleoutSendQueueLength;
}
}
private Task DrainPreviousQueue()
{
// If the tcs is null or complete then create a new one
if (_taskCompletionSource == null ||
_taskCompletionSource.Task.IsCompleted)
{
_taskCompletionSource = new TaskCompletionSource<object>();
}
if (_queue != null)
{
// Drain the queue when the new queue is open
return _taskCompletionSource.Task.Then((q, t) => Drain(q, t), _queue, _logger);
}
// Nothing to drain
return _taskCompletionSource.Task;
}
private void EnsureQueueStarted()
{
if (_taskCompletionSource != null)
{
_taskCompletionSource.TrySetResult(null);
}
}
private bool ChangeState(StreamState newState)
{
StreamState oldState;
return ChangeState(newState, out oldState);
}
private bool ChangeState(StreamState newState, out StreamState previousState)
{
previousState = _state;
// Do nothing if the state is closed
if (_state == StreamState.Closed)
{
return false;
}
if (_state != newState)
{
Log(LogLevel.Information, "Changed state from {0} to {1}", _state, newState);
_state = newState;
return true;
}
return false;
}
private static Task Drain(TaskQueue queue, ILogger logger)
{
if (queue == null)
{
return TaskAsyncHelper.Empty;
}
var tcs = new TaskCompletionSource<object>();
queue.Drain().Catch(logger).ContinueWith(task =>
{
tcs.SetResult(null);
});
return tcs.Task;
}
private void Log(LogLevel logLevel, string value, params object[] args)
{
switch (logLevel)
{
case LogLevel.Critical:
_logger.LogCritical(String.Format(value, args));
break;
case LogLevel.Error:
_logger.LogError(String.Format(value, args));
break;
case LogLevel.Warning:
_logger.LogWarning(String.Format(value, args));
break;
case LogLevel.Information:
_logger.LogInformation(String.Format(value, args));
break;
case LogLevel.Debug:
_logger.LogDebug(String.Format(value, args));
break;
case LogLevel.Trace:
_logger.LogTrace(String.Format(value, args));
break;
default:
break;
}
}
private class SendContext
{
private readonly Func<object, Task> _send;
private readonly object _state;
public readonly ScaleoutStream Stream;
public readonly TaskCompletionSource<object> TaskCompletionSource;
public SendContext(ScaleoutStream stream, Func<object, Task> send, object state)
{
Stream = stream;
TaskCompletionSource = new TaskCompletionSource<object>();
_send = send;
_state = state;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception flows to the caller")]
public Task InvokeSend()
{
try
{
return _send(_state);
}
catch (Exception ex)
{
return TaskAsyncHelper.FromError(ex);
}
}
}
private enum StreamState
{
Initial,
Open,
Buffering,
Closed
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace Microsoft.AspNetCore.Mvc.ActionConstraints
{
internal class ActionConstraintCache
{
private readonly IActionDescriptorCollectionProvider _collectionProvider;
private readonly IActionConstraintProvider[] _actionConstraintProviders;
private volatile InnerCache? _currentCache;
public ActionConstraintCache(
IActionDescriptorCollectionProvider collectionProvider,
IEnumerable<IActionConstraintProvider> actionConstraintProviders)
{
_collectionProvider = collectionProvider;
_actionConstraintProviders = actionConstraintProviders.OrderBy(item => item.Order).ToArray();
}
internal InnerCache CurrentCache
{
get
{
var current = _currentCache;
var actionDescriptors = _collectionProvider.ActionDescriptors;
if (current == null || current.Version != actionDescriptors.Version)
{
current = new InnerCache(actionDescriptors);
_currentCache = current;
}
return current;
}
}
public IReadOnlyList<IActionConstraint>? GetActionConstraints(HttpContext httpContext, ActionDescriptor action)
{
var cache = CurrentCache;
if (cache.Entries.TryGetValue(action, out var entry))
{
return GetActionConstraintsFromEntry(entry, httpContext, action);
}
if (action.ActionConstraints == null || action.ActionConstraints.Count == 0)
{
return null;
}
var items = new List<ActionConstraintItem>(action.ActionConstraints.Count);
for (var i = 0; i < action.ActionConstraints.Count; i++)
{
items.Add(new ActionConstraintItem(action.ActionConstraints[i]));
}
ExecuteProviders(httpContext, action, items);
var actionConstraints = ExtractActionConstraints(items);
var allActionConstraintsCached = true;
for (var i = 0; i < items.Count; i++)
{
var item = items[i];
if (!item.IsReusable)
{
item.Constraint = null;
allActionConstraintsCached = false;
}
}
if (allActionConstraintsCached)
{
entry = new CacheEntry(actionConstraints!);
}
else
{
entry = new CacheEntry(items);
}
cache.Entries.TryAdd(action, entry);
return actionConstraints;
}
private IReadOnlyList<IActionConstraint>? GetActionConstraintsFromEntry(CacheEntry entry, HttpContext httpContext, ActionDescriptor action)
{
Debug.Assert(entry.ActionConstraints != null || entry.Items != null);
if (entry.ActionConstraints != null)
{
return entry.ActionConstraints;
}
var items = new List<ActionConstraintItem>(entry.Items!.Count);
for (var i = 0; i < entry.Items.Count; i++)
{
var item = entry.Items[i];
if (item.IsReusable)
{
items.Add(item);
}
else
{
items.Add(new ActionConstraintItem(item.Metadata));
}
}
ExecuteProviders(httpContext, action, items);
return ExtractActionConstraints(items);
}
private void ExecuteProviders(HttpContext httpContext, ActionDescriptor action, List<ActionConstraintItem> items)
{
var context = new ActionConstraintProviderContext(httpContext, action, items);
for (var i = 0; i < _actionConstraintProviders.Length; i++)
{
_actionConstraintProviders[i].OnProvidersExecuting(context);
}
for (var i = _actionConstraintProviders.Length - 1; i >= 0; i--)
{
_actionConstraintProviders[i].OnProvidersExecuted(context);
}
}
private IReadOnlyList<IActionConstraint>? ExtractActionConstraints(List<ActionConstraintItem> items)
{
var count = 0;
for (var i = 0; i < items.Count; i++)
{
if (items[i].Constraint != null)
{
count++;
}
}
if (count == 0)
{
return null;
}
var actionConstraints = new IActionConstraint[count];
var actionConstraintIndex = 0;
for (var i = 0; i < items.Count; i++)
{
var actionConstraint = items[i].Constraint;
if (actionConstraint != null)
{
actionConstraints[actionConstraintIndex++] = actionConstraint;
}
}
return actionConstraints;
}
internal class InnerCache
{
private readonly ActionDescriptorCollection _actions;
public InnerCache(ActionDescriptorCollection actions)
{
_actions = actions;
}
public ConcurrentDictionary<ActionDescriptor, CacheEntry> Entries { get; } =
new ConcurrentDictionary<ActionDescriptor, CacheEntry>();
public int Version => _actions.Version;
}
internal readonly struct CacheEntry
{
public CacheEntry(IReadOnlyList<IActionConstraint> actionConstraints)
{
ActionConstraints = actionConstraints;
Items = null;
}
public CacheEntry(List<ActionConstraintItem> items)
{
Items = items;
ActionConstraints = null;
}
public IReadOnlyList<IActionConstraint>? ActionConstraints { get; }
public List<ActionConstraintItem>? Items { get; }
}
}
}
| |
/*
* 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 copyrightD
* 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.Generic;
using System.Text;
using OMV = OpenMetaverse;
namespace OpenSim.Region.PhysicsModule.BulletS
{
public abstract class BSLinkset
{
// private static string LogHeader = "[BULLETSIM LINKSET]";
public enum LinksetImplementation
{
Constraint = 0, // linkset tied together with constraints
Compound = 1, // linkset tied together as a compound object
Manual = 2 // linkset tied together manually (code moves all the pieces)
}
// Create the correct type of linkset for this child
public static BSLinkset Factory(BSScene physScene, BSPrimLinkable parent)
{
BSLinkset ret = null;
switch (parent.LinksetType)
{
case LinksetImplementation.Constraint:
ret = new BSLinksetConstraints(physScene, parent);
break;
case LinksetImplementation.Compound:
ret = new BSLinksetCompound(physScene, parent);
break;
case LinksetImplementation.Manual:
// ret = new BSLinksetManual(physScene, parent);
break;
default:
ret = new BSLinksetCompound(physScene, parent);
break;
}
if (ret == null)
{
physScene.Logger.ErrorFormat("[BULLETSIM LINKSET] Factory could not create linkset. Parent name={1}, ID={2}", parent.Name, parent.LocalID);
}
return ret;
}
public class BSLinkInfo
{
public BSPrimLinkable member;
public BSLinkInfo(BSPrimLinkable pMember)
{
member = pMember;
}
public virtual void ResetLink() { }
public virtual void SetLinkParameters(BSConstraint constrain) { }
// Returns 'true' if physical property updates from the child should be reported to the simulator
public virtual bool ShouldUpdateChildProperties() { return false; }
}
public LinksetImplementation LinksetImpl { get; protected set; }
public BSPrimLinkable LinksetRoot { get; protected set; }
protected BSScene m_physicsScene { get; private set; }
static int m_nextLinksetID = 1;
public int LinksetID { get; private set; }
// The children under the root in this linkset.
// protected HashSet<BSPrimLinkable> m_children;
protected Dictionary<BSPrimLinkable, BSLinkInfo> m_children;
// We lock the diddling of linkset classes to prevent any badness.
// This locks the modification of the instances of this class. Changes
// to the physical representation is done via the tainting mechenism.
protected object m_linksetActivityLock = new Object();
// We keep the prim's mass in the linkset structure since it could be dependent on other prims
public float LinksetMass { get; protected set; }
public virtual bool LinksetIsColliding { get { return false; } }
public OMV.Vector3 CenterOfMass
{
get { return ComputeLinksetCenterOfMass(); }
}
public OMV.Vector3 GeometricCenter
{
get { return ComputeLinksetGeometricCenter(); }
}
protected BSLinkset(BSScene scene, BSPrimLinkable parent)
{
// A simple linkset of one (no children)
LinksetID = m_nextLinksetID++;
// We create LOTS of linksets.
if (m_nextLinksetID <= 0)
m_nextLinksetID = 1;
m_physicsScene = scene;
LinksetRoot = parent;
m_children = new Dictionary<BSPrimLinkable, BSLinkInfo>();
LinksetMass = parent.RawMass;
Rebuilding = false;
RebuildScheduled = false;
parent.ClearDisplacement();
}
// Link to a linkset where the child knows the parent.
// Parent changing should not happen so do some sanity checking.
// We return the parent's linkset so the child can track its membership.
// Called at runtime.
public BSLinkset AddMeToLinkset(BSPrimLinkable child)
{
lock (m_linksetActivityLock)
{
// Don't add the root to its own linkset
if (!IsRoot(child))
AddChildToLinkset(child);
LinksetMass = ComputeLinksetMass();
}
return this;
}
// Remove a child from a linkset.
// Returns a new linkset for the child which is a linkset of one (just the
// orphened child).
// Called at runtime.
public BSLinkset RemoveMeFromLinkset(BSPrimLinkable child, bool inTaintTime)
{
lock (m_linksetActivityLock)
{
if (IsRoot(child))
{
// Cannot remove the root from a linkset.
return this;
}
RemoveChildFromLinkset(child, inTaintTime);
LinksetMass = ComputeLinksetMass();
}
// The child is down to a linkset of just itself
return BSLinkset.Factory(m_physicsScene, child);
}
// Return 'true' if the passed object is the root object of this linkset
public bool IsRoot(BSPrimLinkable requestor)
{
return (requestor.LocalID == LinksetRoot.LocalID);
}
public int NumberOfChildren { get { return m_children.Count; } }
// Return 'true' if this linkset has any children (more than the root member)
public bool HasAnyChildren { get { return (m_children.Count > 0); } }
// Return 'true' if this child is in this linkset
public bool HasChild(BSPrimLinkable child)
{
bool ret = false;
lock (m_linksetActivityLock)
{
ret = m_children.ContainsKey(child);
}
return ret;
}
// Perform an action on each member of the linkset including root prim.
// Depends on the action on whether this should be done at taint time.
public delegate bool ForEachMemberAction(BSPrimLinkable obj);
public virtual bool ForEachMember(ForEachMemberAction action)
{
bool ret = false;
lock (m_linksetActivityLock)
{
action(LinksetRoot);
foreach (BSPrimLinkable po in m_children.Keys)
{
if (action(po))
break;
}
}
return ret;
}
public bool TryGetLinkInfo(BSPrimLinkable child, out BSLinkInfo foundInfo)
{
bool ret = false;
BSLinkInfo found = null;
lock (m_linksetActivityLock)
{
ret = m_children.TryGetValue(child, out found);
}
foundInfo = found;
return ret;
}
// Perform an action on each member of the linkset including root prim.
// Depends on the action on whether this should be done at taint time.
public delegate bool ForEachLinkInfoAction(BSLinkInfo obj);
public virtual bool ForEachLinkInfo(ForEachLinkInfoAction action)
{
bool ret = false;
lock (m_linksetActivityLock)
{
foreach (BSLinkInfo po in m_children.Values)
{
if (action(po))
break;
}
}
return ret;
}
// Check the type of the link and return 'true' if the link is flexible and the
// updates from the child should be sent to the simulator so things change.
public virtual bool ShouldReportPropertyUpdates(BSPrimLinkable child)
{
bool ret = false;
BSLinkInfo linkInfo;
if (m_children.TryGetValue(child, out linkInfo))
{
ret = linkInfo.ShouldUpdateChildProperties();
}
return ret;
}
// Called after a simulation step to post a collision with this object.
// Return 'true' if linkset processed the collision. 'false' says the linkset didn't have
// anything to add for the collision and it should be passed through normal processing.
// Default processing for a linkset.
public virtual bool HandleCollide(uint collidingWith, BSPhysObject collidee,
OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth)
{
bool ret = false;
// prims in the same linkset cannot collide with each other
BSPrimLinkable convCollidee = collidee as BSPrimLinkable;
if (convCollidee != null && (LinksetID == convCollidee.Linkset.LinksetID))
{
// By returning 'true', we tell the caller the collision has been 'handled' so it won't
// do anything about this collision and thus, effectivily, ignoring the collision.
ret = true;
}
else
{
// Not a collision between members of the linkset. Must be a real collision.
// So the linkset root can know if there is a collision anywhere in the linkset.
LinksetRoot.SomeCollisionSimulationStep = m_physicsScene.SimulationStep;
}
return ret;
}
// I am the root of a linkset and a new child is being added
// Called while LinkActivity is locked.
protected abstract void AddChildToLinkset(BSPrimLinkable child);
// I am the root of a linkset and one of my children is being removed.
// Safe to call even if the child is not really in my linkset.
protected abstract void RemoveChildFromLinkset(BSPrimLinkable child, bool inTaintTime);
// When physical properties are changed the linkset needs to recalculate
// its internal properties.
// May be called at runtime or taint-time.
public virtual void Refresh(BSPrimLinkable requestor)
{
LinksetMass = ComputeLinksetMass();
}
// Flag denoting the linkset is in the process of being rebuilt.
// Used to know not the schedule a rebuild in the middle of a rebuild.
// Because of potential update calls that could want to schedule another rebuild.
protected bool Rebuilding { get; set; }
// Flag saying a linkset rebuild has been scheduled.
// This is turned on when the rebuild is requested and turned off when
// the rebuild is complete. Used to limit modifications to the
// linkset parameters while the linkset is in an intermediate state.
// Protected by a "lock(m_linsetActivityLock)" on the BSLinkset object
public bool RebuildScheduled { get; protected set; }
// The object is going dynamic (physical). Do any setup necessary
// for a dynamic linkset.
// Only the state of the passed object can be modified. The rest of the linkset
// has not yet been fully constructed.
// Return 'true' if any properties updated on the passed object.
// Called at taint-time!
public abstract bool MakeDynamic(BSPrimLinkable child);
public virtual bool AllPartsComplete
{
get {
bool ret = true;
this.ForEachMember((member) =>
{
if ((!member.IsInitialized) || member.IsIncomplete || member.PrimAssetState == BSPhysObject.PrimAssetCondition.Waiting)
{
ret = false;
return true; // exit loop
}
return false; // continue loop
});
return ret;
}
}
// The object is going static (non-physical). Do any setup necessary
// for a static linkset.
// Return 'true' if any properties updated on the passed object.
// Called at taint-time!
public abstract bool MakeStatic(BSPrimLinkable child);
// Called when a parameter update comes from the physics engine for any object
// of the linkset is received.
// Passed flag is update came from physics engine (true) or the user (false).
// Called at taint-time!!
public abstract void UpdateProperties(UpdatedProperties whichUpdated, BSPrimLinkable physObject);
// Routine used when rebuilding the body of the root of the linkset
// Destroy all the constraints have have been made to root.
// This is called when the root body is changing.
// Returns 'true' of something was actually removed and would need restoring
// Called at taint-time!!
public abstract bool RemoveDependencies(BSPrimLinkable child);
// ================================================================
// Some physical setting happen to all members of the linkset
public virtual void SetPhysicalFriction(float friction)
{
ForEachMember((member) =>
{
if (member.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetFriction(member.PhysBody, friction);
return false; // 'false' says to continue looping
}
);
}
public virtual void SetPhysicalRestitution(float restitution)
{
ForEachMember((member) =>
{
if (member.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetRestitution(member.PhysBody, restitution);
return false; // 'false' says to continue looping
}
);
}
public virtual void SetPhysicalGravity(OMV.Vector3 gravity)
{
ForEachMember((member) =>
{
if (member.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetGravity(member.PhysBody, gravity);
return false; // 'false' says to continue looping
}
);
}
public virtual void ComputeAndSetLocalInertia(OMV.Vector3 inertiaFactor, float linksetMass)
{
ForEachMember((member) =>
{
if (member.PhysBody.HasPhysicalBody)
{
OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, linksetMass);
member.Inertia = inertia * inertiaFactor;
m_physicsScene.PE.SetMassProps(member.PhysBody, linksetMass, member.Inertia);
m_physicsScene.PE.UpdateInertiaTensor(member.PhysBody);
DetailLog("{0},BSLinkset.ComputeAndSetLocalInertia,m.mass={1}, inertia={2}", member.LocalID, linksetMass, member.Inertia);
}
return false; // 'false' says to continue looping
}
);
}
public virtual void SetPhysicalCollisionFlags(CollisionFlags collFlags)
{
ForEachMember((member) =>
{
if (member.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetCollisionFlags(member.PhysBody, collFlags);
return false; // 'false' says to continue looping
}
);
}
public virtual void AddToPhysicalCollisionFlags(CollisionFlags collFlags)
{
ForEachMember((member) =>
{
if (member.PhysBody.HasPhysicalBody)
m_physicsScene.PE.AddToCollisionFlags(member.PhysBody, collFlags);
return false; // 'false' says to continue looping
}
);
}
public virtual void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags)
{
ForEachMember((member) =>
{
if (member.PhysBody.HasPhysicalBody)
m_physicsScene.PE.RemoveFromCollisionFlags(member.PhysBody, collFlags);
return false; // 'false' says to continue looping
}
);
}
// ================================================================
protected virtual float ComputeLinksetMass()
{
float mass = LinksetRoot.RawMass;
if (HasAnyChildren)
{
lock (m_linksetActivityLock)
{
foreach (BSPrimLinkable bp in m_children.Keys)
{
mass += bp.RawMass;
}
}
}
return mass;
}
// Computes linkset's center of mass in world coordinates.
protected virtual OMV.Vector3 ComputeLinksetCenterOfMass()
{
OMV.Vector3 com;
lock (m_linksetActivityLock)
{
com = LinksetRoot.Position * LinksetRoot.RawMass;
float totalMass = LinksetRoot.RawMass;
foreach (BSPrimLinkable bp in m_children.Keys)
{
com += bp.Position * bp.RawMass;
totalMass += bp.RawMass;
}
if (totalMass != 0f)
com /= totalMass;
}
return com;
}
protected virtual OMV.Vector3 ComputeLinksetGeometricCenter()
{
OMV.Vector3 com;
lock (m_linksetActivityLock)
{
com = LinksetRoot.Position;
foreach (BSPrimLinkable bp in m_children.Keys)
{
com += bp.Position;
}
com /= (m_children.Count + 1);
}
return com;
}
#region Extension
public virtual object Extension(string pFunct, params object[] pParams)
{
return null;
}
#endregion // Extension
// Invoke the detailed logger and output something if it's enabled.
protected void DetailLog(string msg, params Object[] args)
{
if (m_physicsScene.PhysicsLogging.Enabled)
m_physicsScene.DetailLog(msg, args);
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright [email protected]
// Copyright iced contributors
#if GAS || INTEL || MASM || NASM
using System;
using System.Runtime.CompilerServices;
using System.Text;
namespace Iced.Intel {
[Flags]
enum NumberFormatterFlags {
None = 0,
AddMinusSign = 0x00000001,
LeadingZeroes = 0x00000002,
SmallHexNumbersInDecimal = 0x00000004,
}
readonly struct NumberFormatter {
const ulong SmallPositiveNumber = 9;
readonly StringBuilder sb;
public NumberFormatter(bool dummy) {
const int CAP =
2 +// "0b"
64 +// 64 bin digits
(16 - 1);// # digit separators if group size == 4 and digit sep is one char
sb = new StringBuilder(CAP);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void ToHexadecimal(StringBuilder sb, ulong value, int digitGroupSize, string? digitSeparator, int digits, bool upper, bool leadingZero) {
if (digits == 0) {
digits = 1;
for (ulong tmp = value; ;) {
tmp >>= 4;
if (tmp == 0)
break;
digits++;
}
}
int hexHigh = upper ? 'A' - 10 : 'a' - 10;
if (leadingZero && digits < 17 && (int)((value >> ((digits - 1) << 2)) & 0xF) > 9)
digits++;// Another 0
bool useDigitSep = digitGroupSize > 0 && !string.IsNullOrEmpty(digitSeparator);
for (int i = 0; i < digits; i++) {
int index = digits - i - 1;
int digit = index >= 16 ? 0 : (int)((value >> (index << 2)) & 0xF);
if (digit > 9)
sb.Append((char)(digit + hexHigh));
else
sb.Append((char)(digit + '0'));
if (useDigitSep && index > 0 && (index % digitGroupSize) == 0)
sb.Append(digitSeparator!);
}
}
static readonly ulong[] divs = new ulong[] {
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000,
100000000000000000,
1000000000000000000,
10000000000000000000,
};
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void ToDecimal(StringBuilder sb, ulong value, int digitGroupSize, string? digitSeparator, int digits) {
if (digits == 0) {
digits = 1;
for (ulong tmp = value; ;) {
tmp /= 10;
if (tmp == 0)
break;
digits++;
}
}
bool useDigitSep = digitGroupSize > 0 && !string2.IsNullOrEmpty(digitSeparator);
var divs = NumberFormatter.divs;
for (int i = 0; i < digits; i++) {
int index = digits - i - 1;
if ((uint)index < (uint)divs.Length) {
int digit = (int)(value / divs[index] % 10);
sb.Append((char)(digit + '0'));
}
else
sb.Append('0');
if (useDigitSep && index > 0 && (index % digitGroupSize) == 0)
sb.Append(digitSeparator!);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void ToOctal(StringBuilder sb, ulong value, int digitGroupSize, string? digitSeparator, int digits, string? prefix) {
if (digits == 0) {
digits = 1;
for (ulong tmp = value; ;) {
tmp >>= 3;
if (tmp == 0)
break;
digits++;
}
}
if (!string.IsNullOrEmpty(prefix)) {
// The prefix is part of the number so that a digit separator can be placed
// between the "prefix" and the rest of the number, eg. "0" + "1234" with
// digit separator "`" and group size = 2 is "0`12`34" and not "012`34".
// Other prefixes, eg. "0o" prefix: 0o12`34 and never 0o`12`34.
if (prefix == "0") {
if (digits < 23 && (int)((value >> (digits - 1) * 3) & 7) != 0)
digits++;// Another 0
}
else
sb.Append(prefix);
}
bool useDigitSep = digitGroupSize > 0 && !string2.IsNullOrEmpty(digitSeparator);
for (int i = 0; i < digits; i++) {
int index = digits - i - 1;
int digit = index >= 22 ? 0 : (int)((value >> index * 3) & 7);
sb.Append((char)(digit + '0'));
if (useDigitSep && index > 0 && (index % digitGroupSize) == 0)
sb.Append(digitSeparator!);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void ToBinary(StringBuilder sb, ulong value, int digitGroupSize, string? digitSeparator, int digits) {
if (digits == 0) {
digits = 1;
for (ulong tmp = value; ;) {
tmp >>= 1;
if (tmp == 0)
break;
digits++;
}
}
bool useDigitSep = digitGroupSize > 0 && !string2.IsNullOrEmpty(digitSeparator);
for (int i = 0; i < digits; i++) {
int index = digits - i - 1;
int digit = index >= 64 ? 0 : (int)((value >> index) & 1);
sb.Append((char)(digit + '0'));
if (useDigitSep && index > 0 && (index % digitGroupSize) == 0)
sb.Append(digitSeparator!);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static NumberFormatterFlags GetFlags(bool leadingZeroes, bool smallHexNumbersInDecimal) {
var flags = NumberFormatterFlags.None;
if (leadingZeroes)
flags |= NumberFormatterFlags.LeadingZeroes;
if (smallHexNumbersInDecimal)
flags |= NumberFormatterFlags.SmallHexNumbersInDecimal;
return flags;
}
public string FormatInt8(FormatterOptions formatterOptions, in NumberFormattingOptions options, sbyte value) {
var flags = GetFlags(options.LeadingZeroes, options.SmallHexNumbersInDecimal);
if (value < 0) {
flags |= NumberFormatterFlags.AddMinusSign;
value = (sbyte)-value;
}
return FormatUnsignedInteger(formatterOptions, options, (byte)value, 8, flags);
}
public string FormatInt16(FormatterOptions formatterOptions, in NumberFormattingOptions options, short value) {
var flags = GetFlags(options.LeadingZeroes, options.SmallHexNumbersInDecimal);
if (value < 0) {
flags |= NumberFormatterFlags.AddMinusSign;
value = (short)-value;
}
return FormatUnsignedInteger(formatterOptions, options, (ushort)value, 16, flags);
}
public string FormatInt32(FormatterOptions formatterOptions, in NumberFormattingOptions options, int value) {
var flags = GetFlags(options.LeadingZeroes, options.SmallHexNumbersInDecimal);
if (value < 0) {
flags |= NumberFormatterFlags.AddMinusSign;
value = -value;
}
return FormatUnsignedInteger(formatterOptions, options, (uint)value, 32, flags);
}
public string FormatInt64(FormatterOptions formatterOptions, in NumberFormattingOptions options, long value) {
var flags = GetFlags(options.LeadingZeroes, options.SmallHexNumbersInDecimal);
if (value < 0) {
flags |= NumberFormatterFlags.AddMinusSign;
value = -value;
}
return FormatUnsignedInteger(formatterOptions, options, (ulong)value, 64, flags);
}
public string FormatUInt8(FormatterOptions formatterOptions, in NumberFormattingOptions options, byte value) => FormatUnsignedInteger(formatterOptions, options, value, 8, GetFlags(options.LeadingZeroes, options.SmallHexNumbersInDecimal));
public string FormatUInt16(FormatterOptions formatterOptions, in NumberFormattingOptions options, ushort value) => FormatUnsignedInteger(formatterOptions, options, value, 16, GetFlags(options.LeadingZeroes, options.SmallHexNumbersInDecimal));
public string FormatUInt32(FormatterOptions formatterOptions, in NumberFormattingOptions options, uint value) => FormatUnsignedInteger(formatterOptions, options, value, 32, GetFlags(options.LeadingZeroes, options.SmallHexNumbersInDecimal));
public string FormatUInt64(FormatterOptions formatterOptions, in NumberFormattingOptions options, ulong value) => FormatUnsignedInteger(formatterOptions, options, value, 64, GetFlags(options.LeadingZeroes, options.SmallHexNumbersInDecimal));
public string FormatUInt16(FormatterOptions formatterOptions, in NumberFormattingOptions options, ushort value, bool leadingZeroes) => FormatUnsignedInteger(formatterOptions, options, value, 16, GetFlags(leadingZeroes, options.SmallHexNumbersInDecimal));
public string FormatUInt32(FormatterOptions formatterOptions, in NumberFormattingOptions options, uint value, bool leadingZeroes) => FormatUnsignedInteger(formatterOptions, options, value, 32, GetFlags(leadingZeroes, options.SmallHexNumbersInDecimal));
public string FormatUInt64(FormatterOptions formatterOptions, in NumberFormattingOptions options, ulong value, bool leadingZeroes) => FormatUnsignedInteger(formatterOptions, options, value, 64, GetFlags(leadingZeroes, options.SmallHexNumbersInDecimal));
static readonly string[] smallDecimalValues = new string[(int)SmallPositiveNumber + 1] {
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
};
string FormatUnsignedInteger(FormatterOptions formatterOptions, in NumberFormattingOptions options, ulong value, int valueSize, NumberFormatterFlags flags) {
sb.Clear();
if ((flags & NumberFormatterFlags.AddMinusSign) != 0)
sb.Append('-');
string? suffix;
switch (options.NumberBase) {
case NumberBase.Hexadecimal:
if ((flags & NumberFormatterFlags.SmallHexNumbersInDecimal) != 0 && value <= SmallPositiveNumber) {
if (string.IsNullOrEmpty(formatterOptions.DecimalPrefix) && string.IsNullOrEmpty(formatterOptions.DecimalSuffix))
return smallDecimalValues[(int)value];
if (!string.IsNullOrEmpty(formatterOptions.DecimalPrefix))
sb.Append(formatterOptions.DecimalPrefix);
sb.Append(smallDecimalValues[(int)value]);
suffix = formatterOptions.DecimalSuffix;
}
else {
if (!string.IsNullOrEmpty(options.Prefix))
sb.Append(options.Prefix);
ToHexadecimal(sb, value, options.DigitGroupSize, options.DigitSeparator, (flags & NumberFormatterFlags.LeadingZeroes) != 0 ? (valueSize + 3) >> 2 : 0, options.UppercaseHex, options.AddLeadingZeroToHexNumbers && string.IsNullOrEmpty(options.Prefix));
suffix = options.Suffix;
}
break;
case NumberBase.Decimal:
if (!string.IsNullOrEmpty(options.Prefix))
sb.Append(options.Prefix);
ToDecimal(sb, value, options.DigitGroupSize, options.DigitSeparator, 0);
suffix = options.Suffix;
break;
case NumberBase.Octal:
ToOctal(sb, value, options.DigitGroupSize, options.DigitSeparator, (flags & NumberFormatterFlags.LeadingZeroes) != 0 ? (valueSize + 2) / 3 : 0, options.Prefix);
suffix = options.Suffix;
break;
case NumberBase.Binary:
if (!string.IsNullOrEmpty(options.Prefix))
sb.Append(options.Prefix);
ToBinary(sb, value, options.DigitGroupSize, options.DigitSeparator, (flags & NumberFormatterFlags.LeadingZeroes) != 0 ? valueSize : 0);
suffix = options.Suffix;
break;
default:
throw new InvalidOperationException();
}
if (!string.IsNullOrEmpty(suffix))
sb.Append(suffix);
return sb.ToString();
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using BitDiffer.Common.Model;
using BitDiffer.Common.Misc;
namespace BitDiffer.Common.Utility
{
public class CodeStringBuilder
{
private AppendMode _mode = AppendMode.Both;
private StringBuilder _sbText = new StringBuilder(25);
private StringBuilder _sbHtml = new StringBuilder(75);
public CodeStringBuilder()
{
}
public CodeStringBuilder(AppendMode mode)
{
_mode = mode;
}
public AppendMode Mode
{
get { return _mode; }
set { _mode = value; }
}
public void AppendText(string text)
{
AppendText(text, null);
}
public void AppendKeyword(string keyword)
{
AppendText(keyword, "keyword");
}
public void AppendVisibility(Visibility visibility)
{
AppendText(VisibilityUtil.GetVisibilityString(visibility), "visibility");
}
public void AppendType(Type type)
{
AppendType(type, true);
}
public void AppendType(Type type, bool includeNamespace)
{
string typeAsKeyword = GetTypeNameAsKeyword(type);
if (typeAsKeyword != null)
{
AppendKeyword(typeAsKeyword);
return;
}
if (type.IsGenericParameter && !type.IsGenericType)
{
AppendText(type.Name);
return;
}
// Dont show the namespaces on user types in the UI - but keep them in text, for comparison and reports
if (includeNamespace)
{
AppendMode restore = _mode;
_mode &= ~AppendMode.Html;
AppendText(type.Namespace);
AppendText(".");
_mode = restore;
}
if (type.IsGenericType)
{
AppendGeneric(type.Name, type.GetGenericArguments(), "usertype");
}
else
{
AppendText(type.Name, "usertype");
}
}
public void AppendText(string word, string css)
{
if ((_mode & AppendMode.Text) != 0)
{
_sbText.Append(word);
}
if ((_mode & AppendMode.Html) != 0)
{
if (css != null)
{
_sbHtml.Append("<span class='");
_sbHtml.Append(css);
_sbHtml.Append("'>");
}
_sbHtml.Append(HtmlEncode(word));
if (css != null)
{
_sbHtml.Append("</span>");
}
}
}
public void AppendNewline()
{
if ((_mode & AppendMode.Text) != 0)
{
_sbText.Append(Environment.NewLine);
}
if ((_mode & AppendMode.Html) != 0)
{
_sbHtml.Append("<br>");
}
}
public void AppendIndent()
{
if ((_mode & AppendMode.Text) != 0)
{
_sbText.Append(" ");
}
if ((_mode & AppendMode.Html) != 0)
{
_sbHtml.Append(" ");
}
}
public void AppendParameter(ParameterInfo pi)
{
AppendParameterType(pi);
// Dont use parameter names in comparing declarations
AppendMode restore = _mode;
_mode &= ~AppendMode.Text;
if (pi.Name != null)
{
AppendText(" ");
AppendText(pi.Name);
}
AppendParameterValue(pi.RawDefaultValue);
_mode = restore;
}
public void AppendParameterType(ParameterInfo pi)
{
if (pi.IsIn && pi.IsOut)
{
AppendKeyword("ref ");
}
else if (pi.IsOut)
{
AppendKeyword("out ");
}
AppendType(pi.ParameterType);
}
public void AppendRawHtml(string html)
{
_sbHtml.Append(html);
}
public void AppendGenericRestrictions(Type type)
{
if (!type.IsGenericTypeDefinition)
{
return;
}
AppendGenericRestrictions(type.GetGenericArguments());
}
public void AppendGenericRestrictions(MethodBase mi)
{
AppendGenericRestrictions(mi.GetGenericArguments());
}
internal void AppendGenericRestrictions(Type[] arguments)
{
if (arguments == null || arguments.Length == 0)
{
return;
}
foreach (Type arg in arguments)
{
Type[] constraints = arg.GetGenericParameterConstraints();
if (constraints == null || constraints.Length == 0)
{
return;
}
AppendKeyword(" where ");
AppendText(arg.Name);
AppendText(" : ");
if ((arg.GenericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0)
{
AppendKeyword("class");
AppendText(", ");
}
if ((arg.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
{
AppendKeyword("struct");
AppendText(", ");
}
if ((arg.GenericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0)
{
AppendKeyword("new");
AppendText("(), ");
}
foreach (Type constraint in constraints)
{
AppendType(constraint);
AppendText(", ");
}
RemoveCharsFromEnd(2);
}
}
public void AppendParameterValue(object value)
{
if ((value == null) || (value.GetType() == typeof(DBNull)))
{
return;
}
AppendText(" = ");
AppendQuotedValue(value);
}
public void AppendQuotedValue(object value)
{
if (value == null)
{
AppendText("null");
}
else if (value is string)
{
AppendText("\"" + value.ToString() + "\"", "string");
}
else if (value is char)
{
AppendText("'" + value.ToString() + "'", "string");
}
else
{
AppendText(value.ToString());
}
}
public void AppendBaseClasses(Type type)
{
if (((type.BaseType == null) || (type.BaseType == typeof(object))) && (type.GetInterfaces().Length == 0))
{
return;
}
// Dont use base types in comparing declarations.. someday, would be good to do a more intelligent compare (implemented interfaces removed is possibly a breaking change?)
AppendMode restore = _mode;
_mode &= ~AppendMode.Text;
AppendText(" : ");
if ((type.BaseType != null) && (type.BaseType != typeof(object)))
{
AppendType(type.BaseType);
AppendText(", ");
}
foreach (Type intf in type.GetInterfaces())
{
AppendType(intf);
AppendText(", ");
}
RemoveCharsFromEnd(2);
_mode = restore;
}
public void RemoveCharsFromEnd(int count)
{
if ((_mode & AppendMode.Text) != 0)
{
_sbText.Remove(_sbText.Length - count, count);
}
if ((_mode & AppendMode.Html) != 0)
{
_sbHtml.Remove(_sbHtml.Length - count, count);
}
}
private string HtmlEncode(string text)
{
text = text.Replace("<", "<");
text = text.Replace(">", ">");
return text;
}
private string GetTypeNameAsKeyword(Type type)
{
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
string baseType = GetTypeNameAsKeyword(Nullable.GetUnderlyingType(type));
if (baseType != null)
{
return baseType + "?";
}
}
}
else
{
if (type == typeof(void))
{
return "void";
}
if (type == typeof(string))
{
return "string";
}
else if (type == typeof(int))
{
return "int";
}
else if (type == typeof(long))
{
return "long";
}
else if (type == typeof(char))
{
return "char";
}
else if (type == typeof(bool))
{
return "bool";
}
else if (type == typeof(byte))
{
return "byte";
}
else if (type == typeof(DateTime))
{
return "DateTime";
}
else if (type == typeof(decimal))
{
return "decimal";
}
else if (type == typeof(double))
{
return "double";
}
else if (type == typeof(uint))
{
return "uint";
}
else if (type == typeof(ulong))
{
return "ulong";
}
else if (type == typeof(object))
{
return "object";
}
}
return null;
}
private void AppendGeneric(string name, Type[] genericArguments, string css)
{
if ((genericArguments == null) || (genericArguments.Length == 0))
{
System.Diagnostics.Debug.Assert(false);
return;
}
int apos = name.IndexOf('`');
if (apos > 0)
{
AppendText(name.Substring(0, apos), css);
}
else
{
AppendText(name, css);
}
AppendText("<");
foreach (Type gentype in genericArguments)
{
AppendType(gentype);
AppendText(", ");
}
RemoveCharsFromEnd(2);
AppendText(">");
}
public void AppendMethodName(MethodBase mi)
{
if (!mi.IsGenericMethod)
{
AppendText(mi.Name);
return;
}
AppendGeneric(mi.Name, mi.GetGenericArguments(), null);
}
public override string ToString()
{
return _sbText.ToString();
}
public virtual string ToHtmlString()
{
return _sbHtml.ToString();
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Practices.Prism;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.Prism.Composition.Tests.Modularity
{
[TestClass]
public class ModuleCatalogFixture
{
[TestMethod]
public void CanCreateCatalogFromList()
{
var moduleInfo = new ModuleInfo("MockModule", "type");
List<ModuleInfo> moduleInfos = new List<ModuleInfo> { moduleInfo };
var moduleCatalog = new ModuleCatalog(moduleInfos);
Assert.AreEqual(1, moduleCatalog.Modules.Count());
Assert.AreEqual(moduleInfo, moduleCatalog.Modules.ElementAt(0));
}
[TestMethod]
public void CanGetDependenciesForModule()
{
// A <- B
var moduleInfoA = CreateModuleInfo("A");
var moduleInfoB = CreateModuleInfo("B", "A");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
, moduleInfoB
};
var moduleCatalog = new ModuleCatalog(moduleInfos);
IEnumerable<ModuleInfo> dependentModules = moduleCatalog.GetDependentModules(moduleInfoB);
Assert.AreEqual(1, dependentModules.Count());
Assert.AreEqual(moduleInfoA, dependentModules.ElementAt(0));
}
[TestMethod]
public void CanCompleteListWithTheirDependencies()
{
// A <- B <- C
var moduleInfoA = CreateModuleInfo("A");
var moduleInfoB = CreateModuleInfo("B", "A");
var moduleInfoC = CreateModuleInfo("C", "B");
var moduleInfoOrphan = CreateModuleInfo("X", "B");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
, moduleInfoB
, moduleInfoC
, moduleInfoOrphan
};
var moduleCatalog = new ModuleCatalog(moduleInfos);
IEnumerable<ModuleInfo> dependantModules = moduleCatalog.CompleteListWithDependencies(new[] { moduleInfoC });
Assert.AreEqual(3, dependantModules.Count());
Assert.IsTrue(dependantModules.Contains(moduleInfoA));
Assert.IsTrue(dependantModules.Contains(moduleInfoB));
Assert.IsTrue(dependantModules.Contains(moduleInfoC));
}
[TestMethod]
[ExpectedException(typeof(CyclicDependencyFoundException))]
public void ShouldThrowOnCyclicDependency()
{
// A <- B <- C <- A
var moduleInfoA = CreateModuleInfo("A", "C");
var moduleInfoB = CreateModuleInfo("B", "A");
var moduleInfoC = CreateModuleInfo("C", "B");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
, moduleInfoB
, moduleInfoC
};
new ModuleCatalog(moduleInfos).Validate();
}
[TestMethod]
[ExpectedException(typeof(DuplicateModuleException))]
public void ShouldThrowOnDuplicateModule()
{
var moduleInfoA1 = CreateModuleInfo("A");
var moduleInfoA2 = CreateModuleInfo("A");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA1
, moduleInfoA2
};
new ModuleCatalog(moduleInfos).Validate();
}
[TestMethod]
[ExpectedException(typeof(ModularityException))]
public void ShouldThrowOnMissingDependency()
{
var moduleInfoA = CreateModuleInfo("A", "B");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
};
new ModuleCatalog(moduleInfos).Validate();
}
[TestMethod]
public void CanAddModules()
{
var catalog = new ModuleCatalog();
catalog.AddModule(typeof(MockModule));
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName);
}
[TestMethod]
public void CanAddGroups()
{
var catalog = new ModuleCatalog();
ModuleInfo moduleInfo = new ModuleInfo();
ModuleInfoGroup group = new ModuleInfoGroup { moduleInfo };
catalog.Items.Add(group);
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreSame(moduleInfo, catalog.Modules.ElementAt(0));
}
[TestMethod]
public void ShouldAggregateGroupsAndLooseModuleInfos()
{
var catalog = new ModuleCatalog();
ModuleInfo moduleInfo1 = new ModuleInfo();
ModuleInfo moduleInfo2 = new ModuleInfo();
ModuleInfo moduleInfo3 = new ModuleInfo();
catalog.Items.Add(new ModuleInfoGroup() { moduleInfo1 });
catalog.Items.Add(new ModuleInfoGroup() { moduleInfo2 });
catalog.AddModule(moduleInfo3);
Assert.AreEqual(3, catalog.Modules.Count());
Assert.IsTrue(catalog.Modules.Contains(moduleInfo1));
Assert.IsTrue(catalog.Modules.Contains(moduleInfo2));
Assert.IsTrue(catalog.Modules.Contains(moduleInfo3));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CompleteListWithDependenciesThrowsWithNull()
{
var catalog = new ModuleCatalog();
catalog.CompleteListWithDependencies(null);
}
[TestMethod]
public void LooseModuleIfDependentOnModuleInGroupThrows()
{
var catalog = new ModuleCatalog();
catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") });
catalog.AddModule(CreateModuleInfo("ModuleB", "ModuleA"));
try
{
catalog.Validate();
}
catch (Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(ModularityException));
Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName);
return;
}
Assert.Fail("Exception not thrown.");
}
[TestMethod]
public void ModuleInGroupDependsOnModuleInOtherGroupThrows()
{
var catalog = new ModuleCatalog();
catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") });
catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleB", "ModuleA") });
try
{
catalog.Validate();
}
catch (Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(ModularityException));
Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName);
return;
}
Assert.Fail("Exception not thrown.");
}
[TestMethod]
public void ShouldRevalidateWhenAddingNewModuleIfValidated()
{
var testableCatalog = new TestableModuleCatalog();
testableCatalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") });
testableCatalog.Validate();
testableCatalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleB") });
Assert.IsTrue(testableCatalog.ValidateCalled);
}
[TestMethod]
public void ModuleInGroupCanDependOnModuleInSameGroup()
{
var catalog = new ModuleCatalog();
var moduleA = CreateModuleInfo("ModuleA");
var moduleB = CreateModuleInfo("ModuleB", "ModuleA");
catalog.Items.Add(new ModuleInfoGroup()
{
moduleA,
moduleB
});
var moduleBDependencies = catalog.GetDependentModules(moduleB);
Assert.AreEqual(1, moduleBDependencies.Count());
Assert.AreEqual(moduleA, moduleBDependencies.First());
}
[TestMethod]
public void StartupModuleDependentOnAnOnDemandModuleThrows()
{
var catalog = new ModuleCatalog();
var moduleOnDemand = CreateModuleInfo("ModuleA");
moduleOnDemand.InitializationMode = InitializationMode.OnDemand;
catalog.AddModule(moduleOnDemand);
catalog.AddModule(CreateModuleInfo("ModuleB", "ModuleA"));
try
{
catalog.Validate();
}
catch (Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(ModularityException));
Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName);
return;
}
Assert.Fail("Exception not thrown.");
}
[TestMethod]
public void ShouldReturnInCorrectRetrieveOrderWhenCompletingListWithDependencies()
{
// A <- B <- C <- D, C <- X
var moduleA = CreateModuleInfo("A");
var moduleB = CreateModuleInfo("B", "A");
var moduleC = CreateModuleInfo("C", "B");
var moduleD = CreateModuleInfo("D", "C");
var moduleX = CreateModuleInfo("X", "C");
var moduleCatalog = new ModuleCatalog();
// Add the modules in random order
moduleCatalog.AddModule(moduleB);
moduleCatalog.AddModule(moduleA);
moduleCatalog.AddModule(moduleD);
moduleCatalog.AddModule(moduleX);
moduleCatalog.AddModule(moduleC);
var dependantModules = moduleCatalog.CompleteListWithDependencies(new[] { moduleD, moduleX }).ToList();
Assert.AreEqual(5, dependantModules.Count);
Assert.IsTrue(dependantModules.IndexOf(moduleA) < dependantModules.IndexOf(moduleB));
Assert.IsTrue(dependantModules.IndexOf(moduleB) < dependantModules.IndexOf(moduleC));
Assert.IsTrue(dependantModules.IndexOf(moduleC) < dependantModules.IndexOf(moduleD));
Assert.IsTrue(dependantModules.IndexOf(moduleC) < dependantModules.IndexOf(moduleX));
}
[TestMethod]
public void CanLoadCatalogFromXaml()
{
Stream stream =
Assembly.GetExecutingAssembly().GetManifestResourceStream(
"Microsoft.Practices.Prism.Composition.Tests.Modularity.ModuleCatalogXaml.SimpleModuleCatalog.xaml");
var catalog = ModuleCatalog.CreateFromXaml(stream);
Assert.IsNotNull(catalog);
Assert.AreEqual(4, catalog.Modules.Count());
}
[TestMethod]
public void ShouldLoadAndValidateOnInitialize()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
Assert.IsFalse(testableCatalog.LoadCalled);
Assert.IsFalse(testableCatalog.ValidateCalled);
testableCatalog.Initialize();
Assert.IsTrue(testableCatalog.LoadCalled);
Assert.IsTrue(testableCatalog.ValidateCalled);
Assert.IsTrue(testableCatalog.LoadCalledFirst);
}
[TestMethod]
public void ShouldNotLoadAgainIfInitializedCalledMoreThanOnce()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
Assert.IsFalse(testableCatalog.LoadCalled);
Assert.IsFalse(testableCatalog.ValidateCalled);
testableCatalog.Initialize();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
testableCatalog.Initialize();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
}
[TestMethod]
public void ShouldNotLoadAgainDuringInitialize()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
Assert.IsFalse(testableCatalog.LoadCalled);
Assert.IsFalse(testableCatalog.ValidateCalled);
testableCatalog.Load();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
testableCatalog.Initialize();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
}
[TestMethod]
public void ShouldAllowLoadToBeInvokedTwice()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
testableCatalog.Load();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
testableCatalog.Load();
Assert.AreEqual<int>(2, testableCatalog.LoadCalledCount);
}
[TestMethod]
public void CanAddModule1()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule("Module", "ModuleType", InitializationMode.OnDemand, "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("Module", catalog.Modules.First().ModuleName);
Assert.AreEqual("ModuleType", catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.OnDemand, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddModule2()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule("Module", "ModuleType", "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("Module", catalog.Modules.First().ModuleName);
Assert.AreEqual("ModuleType", catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.WhenAvailable, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddModule3()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule(typeof(MockModule), InitializationMode.OnDemand, "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName);
Assert.AreEqual(typeof(MockModule).AssemblyQualifiedName, catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.OnDemand, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddModule4()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule(typeof(MockModule), "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName);
Assert.AreEqual(typeof(MockModule).AssemblyQualifiedName, catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.WhenAvailable, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddGroup()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.Items.Add(new ModuleInfoGroup());
catalog.AddGroup(InitializationMode.OnDemand, "Ref1",
new ModuleInfo("M1", "T1"),
new ModuleInfo("M2", "T2", "M1"));
Assert.AreEqual(2, catalog.Modules.Count());
var module1 = catalog.Modules.First();
var module2 = catalog.Modules.Skip(1).First();
Assert.AreEqual("M1", module1.ModuleName);
Assert.AreEqual("T1", module1.ModuleType);
Assert.AreEqual("Ref1", module1.Ref);
Assert.AreEqual(InitializationMode.OnDemand, module1.InitializationMode);
Assert.AreEqual("M2", module2.ModuleName);
Assert.AreEqual("T2", module2.ModuleType);
Assert.AreEqual("Ref1", module2.Ref);
Assert.AreEqual(InitializationMode.OnDemand, module2.InitializationMode);
}
private class TestableModuleCatalog : ModuleCatalog
{
public bool ValidateCalled { get; set; }
public bool LoadCalledFirst { get; set; }
public bool LoadCalled
{
get { return LoadCalledCount > 0; }
}
public int LoadCalledCount { get; set; }
public override void Validate()
{
ValidateCalled = true;
Validated = true;
}
protected override void InnerLoad()
{
if (ValidateCalled == false && !LoadCalled)
LoadCalledFirst = true;
LoadCalledCount++;
}
}
private static ModuleInfo CreateModuleInfo(string name, params string[] dependsOn)
{
ModuleInfo moduleInfo = new ModuleInfo(name, name);
moduleInfo.DependsOn.AddRange(dependsOn);
return moduleInfo;
}
}
}
| |
using System;
namespace Obscur.Core.Cryptography.Ciphers.Block.Primitives
{
#if INCLUDE_IDEA
/**
* A class that provides a basic International Data Encryption Algorithm (IDEA) engine.
* <p>
* This implementation is based on the "HOWTO: INTERNATIONAL DATA ENCRYPTION ALGORITHM"
* implementation summary by Fauzan Mirza ([email protected]). (baring 1 typo at the
* end of the mulinv function!).
* </p>
* <p>
* It can be found at ftp://ftp.funet.fi/pub/crypt/cryptography/symmetric/idea/
* </p>
* <p>
* Note 1: This algorithm is patented in the USA, Japan, and Europe including
* at least Austria, France, Germany, Italy, Netherlands, Spain, Sweden, Switzerland
* and the United Kingdom. Non-commercial use is free, however any commercial
* products are liable for royalties. Please see
* <a href="http://www.mediacrypt.com">www.mediacrypt.com</a> for
* further details. This announcement has been included at the request of
* the patent holders.
* </p>
* <p>
* Note 2: Due to the requests concerning the above, this algorithm is now only
* included in the extended assembly. It is not included in the default distributions.
* </p>
*/
public class IdeaEngine
: BlockCipherBase
{
private const int BLOCK_SIZE = 8;
private int[] workingKey;
public IdeaEngine() : base(BlockCipher.Idea, BLOCK_SIZE) {}
/// <inheritdoc />
protected override void InitState()
{
workingKey = GenerateWorkingKey(Encrypting, Key);
}
/// <inheritdoc />
internal override int ProcessBlockInternal(byte[] input, int inOff, byte[] output, int outOff)
{
IdeaFunc(workingKey, input, inOff, output, outOff);
return BLOCK_SIZE;
}
/// <inheritdoc />
public override void Reset()
{
}
private static readonly int MASK = 0xffff;
private static readonly int BASE = 0x10001;
private static int BytesToWord(
byte[] input,
int inOff)
{
return ((input[inOff] << 8) & 0xff00) + (input[inOff + 1] & 0xff);
}
private static void WordToBytes(
int word,
byte[] outBytes,
int outOff)
{
outBytes[outOff] = (byte)((uint) word >> 8);
outBytes[outOff + 1] = (byte)word;
}
/**
* return x = x * y where the multiplication is done modulo
* 65537 (0x10001) (as defined in the IDEA specification) and
* a zero input is taken to be 65536 (0x10000).
*
* @param x the x value
* @param y the y value
* @return x = x * y
*/
private static int Mul(
int x,
int y)
{
if (x == 0)
{
x = (BASE - y);
}
else if (y == 0)
{
x = (BASE - x);
}
else
{
int p = x * y;
y = p & MASK;
x = (int) ((uint) p >> 16);
x = y - x + ((y < x) ? 1 : 0);
}
return x & MASK;
}
private static void IdeaFunc(
int[] workingKey,
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
int x0, x1, x2, x3, t0, t1;
int keyOff = 0;
x0 = BytesToWord(input, inOff);
x1 = BytesToWord(input, inOff + 2);
x2 = BytesToWord(input, inOff + 4);
x3 = BytesToWord(input, inOff + 6);
for (int round = 0; round < 8; round++)
{
x0 = Mul(x0, workingKey[keyOff++]);
x1 += workingKey[keyOff++];
x1 &= MASK;
x2 += workingKey[keyOff++];
x2 &= MASK;
x3 = Mul(x3, workingKey[keyOff++]);
t0 = x1;
t1 = x2;
x2 ^= x0;
x1 ^= x3;
x2 = Mul(x2, workingKey[keyOff++]);
x1 += x2;
x1 &= MASK;
x1 = Mul(x1, workingKey[keyOff++]);
x2 += x1;
x2 &= MASK;
x0 ^= x1;
x3 ^= x2;
x1 ^= t1;
x2 ^= t0;
}
WordToBytes(Mul(x0, workingKey[keyOff++]), outBytes, outOff);
WordToBytes(x2 + workingKey[keyOff++], outBytes, outOff + 2); /* NB: Order */
WordToBytes(x1 + workingKey[keyOff++], outBytes, outOff + 4);
WordToBytes(Mul(x3, workingKey[keyOff]), outBytes, outOff + 6);
}
/**
* The following function is used to expand the user key to the encryption
* subkey. The first 16 bytes are the user key, and the rest of the subkey
* is calculated by rotating the previous 16 bytes by 25 bits to the left,
* and so on until the subkey is completed.
*/
private static int[] ExpandKey(
byte[] uKey)
{
int[] key = new int[52];
if (uKey.Length < 16)
{
byte[] tmp = new byte[16];
Array.Copy(uKey, 0, tmp, tmp.Length - uKey.Length, uKey.Length);
uKey = tmp;
}
for (int i = 0; i < 8; i++)
{
key[i] = BytesToWord(uKey, i * 2);
}
for (int i = 8; i < 52; i++)
{
if ((i & 7) < 6)
{
key[i] = ((key[i - 7] & 127) << 9 | key[i - 6] >> 7) & MASK;
}
else if ((i & 7) == 6)
{
key[i] = ((key[i - 7] & 127) << 9 | key[i - 14] >> 7) & MASK;
}
else
{
key[i] = ((key[i - 15] & 127) << 9 | key[i - 14] >> 7) & MASK;
}
}
return key;
}
/**
* This function computes multiplicative inverse using Euclid's Greatest
* Common Divisor algorithm. Zero and one are self inverse.
* <p>
* i.e. x * MulInv(x) == 1 (modulo BASE)
* </p>
*/
private static int MulInv(
int x)
{
int t0, t1, q, y;
if (x < 2)
{
return x;
}
t0 = 1;
t1 = BASE / x;
y = BASE % x;
while (y != 1)
{
q = x / y;
x = x % y;
t0 = (t0 + (t1 * q)) & MASK;
if (x == 1)
{
return t0;
}
q = y / x;
y = y % x;
t1 = (t1 + (t0 * q)) & MASK;
}
return (1 - t1) & MASK;
}
/**
* Return the additive inverse of x.
* <p>
* i.e. x + AddInv(x) == 0
* </p>
*/
static int AddInv(
int x)
{
return (0 - x) & MASK;
}
/**
* The function to invert the encryption subkey to the decryption subkey.
* It also involves the multiplicative inverse and the additive inverse functions.
*/
private static int[] InvertKey(
int[] inKey)
{
int t1, t2, t3, t4;
int p = 52; /* We work backwards */
int[] key = new int[52];
int inOff = 0;
t1 = MulInv(inKey[inOff++]);
t2 = AddInv(inKey[inOff++]);
t3 = AddInv(inKey[inOff++]);
t4 = MulInv(inKey[inOff++]);
key[--p] = t4;
key[--p] = t3;
key[--p] = t2;
key[--p] = t1;
for (int round = 1; round < 8; round++)
{
t1 = inKey[inOff++];
t2 = inKey[inOff++];
key[--p] = t2;
key[--p] = t1;
t1 = MulInv(inKey[inOff++]);
t2 = AddInv(inKey[inOff++]);
t3 = AddInv(inKey[inOff++]);
t4 = MulInv(inKey[inOff++]);
key[--p] = t4;
key[--p] = t2; /* NB: Order */
key[--p] = t3;
key[--p] = t1;
}
t1 = inKey[inOff++];
t2 = inKey[inOff++];
key[--p] = t2;
key[--p] = t1;
t1 = MulInv(inKey[inOff++]);
t2 = AddInv(inKey[inOff++]);
t3 = AddInv(inKey[inOff++]);
t4 = MulInv(inKey[inOff]);
key[--p] = t4;
key[--p] = t3;
key[--p] = t2;
key[--p] = t1;
return key;
}
private static int[] GenerateWorkingKey(
bool forEncryption,
byte[] userKey)
{
if (forEncryption)
{
return ExpandKey(userKey);
}
else
{
return InvertKey(ExpandKey(userKey));
}
}
}
#endif
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using ALinq.Mapping;
using System.ComponentModel;
namespace ALinq.SqlClient
{
/// <summary>
/// Contains functionality to connect to and communicate with a SQL Server 2005.
/// </summary>
public sealed class Sql2005Provider : SqlProvider, IProvider
{
private string dbName;
private bool deleted;
/// <summary>
/// Initializes a new instance of the ALinq.SqlClient.Sql2005Provider class.
/// </summary>
public Sql2005Provider()
: base(ProviderMode.Sql2005)
{
}
void IProvider.Initialize(IDataServices dataServices, object connection)
{
DbConnection connection2;
Type type;
if (dataServices == null)
{
throw Error.ArgumentNull("dataServices");
}
services = dataServices;
DbTransaction transaction = null;
string fileOrServerOrConnectionString = connection as string;
if (fileOrServerOrConnectionString != null)
{
string connectionString = GetConnectionString(fileOrServerOrConnectionString);
dbName = GetDatabaseName(connectionString);
if (dbName.EndsWith(".sdf", StringComparison.OrdinalIgnoreCase))
{
Mode = ProviderMode.SqlCE;
}
if (Mode == ProviderMode.SqlCE)
{
DbProviderFactory provider = GetProvider("System.Data.SqlServerCe.3.5");
if (provider == null)
{
throw Error.ProviderNotInstalled(dbName, "System.Data.SqlServerCe.3.5");
}
connection2 = provider.CreateConnection();
}
else
{
connection2 = new SqlConnection();
}
connection2.ConnectionString = connectionString;
}
else
{
transaction = connection as SqlTransaction;
if ((transaction == null) &&
(connection.GetType().FullName == "System.Data.SqlServerCe.SqlCeTransaction"))
{
transaction = connection as DbTransaction;
}
if (transaction != null)
{
connection = transaction.Connection;
}
connection2 = connection as DbConnection;
if (connection2 == null)
{
throw Error.InvalidConnectionArgument("connection");
}
if (connection2.GetType().FullName == "System.Data.SqlServerCe.SqlCeConnection")
{
Mode = ProviderMode.SqlCE;
}
dbName = GetDatabaseName(connection2.ConnectionString);
}
using (DbCommand command = connection2.CreateCommand())
{
CommandTimeout = command.CommandTimeout;
}
int maxUsers = 1;
if (connection2.ConnectionString.Contains("MultipleActiveResultSets"))
{
DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
builder.ConnectionString = connection2.ConnectionString;
if (
string.Compare((string)builder["MultipleActiveResultSets"], "true",
StringComparison.OrdinalIgnoreCase) == 0)
{
maxUsers = 10;
}
}
conManager = new SqlConnectionManager(this, connection2, maxUsers);
if (transaction != null)
{
conManager.Transaction = transaction;
}
if (Mode == ProviderMode.SqlCE)
{
type = connection2.GetType().Module.GetType("System.Data.SqlServerCe.SqlCeDataReader");
}
else if (connection2 is SqlConnection)
{
type = typeof(SqlDataReader);
}
else
{
type = typeof(DbDataReader);
}
readerCompiler = new ObjectReaderCompiler(type, services);
//InvokeIProviderMethod("Initialize", new[] { SourceService(conManager.Connection), connection });
}
private string GetConnectionString(string fileOrServerOrConnectionString)
{
if (fileOrServerOrConnectionString.IndexOf('=') >= 0)
{
return fileOrServerOrConnectionString;
}
DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
if (fileOrServerOrConnectionString.EndsWith(".mdf", StringComparison.OrdinalIgnoreCase))
{
builder.Add("AttachDBFileName", fileOrServerOrConnectionString);
builder.Add("Server", @"localhost\sqlexpress");
builder.Add("Integrated Security", "SSPI");
builder.Add("User Instance", "true");
builder.Add("MultipleActiveResultSets", "true");
}
else if (fileOrServerOrConnectionString.EndsWith(".sdf", StringComparison.OrdinalIgnoreCase))
{
builder.Add("Data Source", fileOrServerOrConnectionString);
}
else
{
builder.Add("Server", fileOrServerOrConnectionString);
builder.Add("Database", services.Model.DatabaseName);
builder.Add("Integrated Security", "SSPI");
}
return builder.ToString();
}
private string GetDatabaseName(string constr)
{
DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
builder.ConnectionString = constr;
if (builder.ContainsKey("Initial Catalog"))
{
return (string)builder["Initial Catalog"];
}
if (builder.ContainsKey("Database"))
{
return (string)builder["Database"];
}
if (builder.ContainsKey("AttachDBFileName"))
{
return (string)builder["AttachDBFileName"];
}
if (builder.ContainsKey("Data Source") &&
((string)builder["Data Source"]).EndsWith(".sdf", StringComparison.OrdinalIgnoreCase))
{
return (string)builder["Data Source"];
}
return services.Model.DatabaseName;
}
private static DbProviderFactory GetProvider(string providerName)
{
if (
DbProviderFactories.GetFactoryClasses().Rows.OfType<DataRow>().Select(
delegate(DataRow r) { return (string)r["InvariantName"]; }).Contains(providerName,
StringComparer.
OrdinalIgnoreCase))
{
return DbProviderFactories.GetFactory(providerName);
}
return null;
}
bool IProvider.DatabaseExists()
{
CheckDispose();
CheckInitialized();
if (deleted)
{
return false;
}
bool flag = false;
if (Mode == ProviderMode.SqlCE)
{
return File.Exists(dbName);
}
string connectionString = conManager.Connection.ConnectionString;
try
{
conManager.UseConnection(this);
conManager.Connection.ChangeDatabase(dbName);
conManager.ReleaseConnection(this);
flag = true;
}
catch (Exception exc)
{
}
finally
{
if ((conManager.Connection.State == ConnectionState.Closed) &&
(string.Compare(conManager.Connection.ConnectionString, connectionString,
StringComparison.Ordinal) != 0))
{
conManager.Connection.ConnectionString = connectionString;
}
}
return flag;
}
internal override QueryConverter CreateQueryConverter(SqlFactory sql)
{
return new SqlQueryConverter(services, typeProvider, translator, sql);
}
internal override DbFormatter CreateSqlFormatter()
{
return new MsSqlFormatter(this);
}
void IProvider.CreateDatabase()
{
var SqlBuilder = new SqlBuilder(SqlIdentifier);
object obj3;
CheckDispose();
CheckInitialized();
string databaseName = null;
string str2 = null;
var builder = new DbConnectionStringBuilder();
builder.ConnectionString = conManager.Connection.ConnectionString;
if (conManager.Connection.State != ConnectionState.Closed)
{
object obj4;
if ((Mode == ProviderMode.SqlCE) && File.Exists(this.dbName))
{
throw Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(this.dbName);
}
if (builder.TryGetValue("Initial Catalog", out obj4))
{
databaseName = obj4.ToString();
}
if (builder.TryGetValue("Database", out obj4))
{
databaseName = obj4.ToString();
}
if (builder.TryGetValue("AttachDBFileName", out obj4))
{
str2 = obj4.ToString();
}
goto Label_01D2;
}
if (Mode == ProviderMode.SqlCE)
{
if (!File.Exists(this.dbName))
{
Type type =
conManager.Connection.GetType().Module.GetType("System.Data.SqlServerCe.SqlCeEngine");
object target = Activator.CreateInstance(type, new object[] { builder.ToString() });
try
{
type.InvokeMember("CreateDatabase",
BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null,
target, new object[0], CultureInfo.InvariantCulture);
goto Label_0153;
}
catch (TargetInvocationException exception)
{
throw exception.InnerException;
}
finally
{
IDisposable disposable = target as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
throw Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(this.dbName);
}
if (builder.TryGetValue("Initial Catalog", out obj3))
{
databaseName = obj3.ToString();
builder.Remove("Initial Catalog");
}
if (builder.TryGetValue("Database", out obj3))
{
databaseName = obj3.ToString();
builder.Remove("Database");
}
if (builder.TryGetValue("AttachDBFileName", out obj3))
{
str2 = obj3.ToString();
builder.Remove("AttachDBFileName");
}
Label_0153:
conManager.Connection.ConnectionString = builder.ToString();
Label_01D2:
if (string.IsNullOrEmpty(databaseName))
{
if (string.IsNullOrEmpty(str2))
{
if (string.IsNullOrEmpty(this.dbName))
{
throw Error.CouldNotDetermineCatalogName();
}
databaseName = this.dbName;
}
else
{
databaseName = Path.GetFullPath(str2);
}
}
conManager.UseConnection(this);
conManager.AutoClose = false;
try
{
if (services.Model.GetTables().FirstOrDefault() == null)
{
throw Error.CreateDatabaseFailedBecauseOfContextWithNoTables(services.Model.DatabaseName);
}
deleted = false;
if (Mode == ProviderMode.SqlCE)
{
foreach (MetaTable table in services.Model.GetTables())
{
string createTableCommand = SqlBuilder.GetCreateTableCommand(table);
if (!string.IsNullOrEmpty(createTableCommand))
{
ExecuteCommand(createTableCommand);
}
}
foreach (MetaTable table2 in services.Model.GetTables())
{
foreach (string str4 in SqlBuilder.GetCreateForeignKeyCommands(table2))
{
if (!string.IsNullOrEmpty(str4))
{
ExecuteCommand(str4);
}
}
}
}
else
{
string command = SqlBuilder.GetCreateDatabaseCommand(databaseName, str2,
Path.ChangeExtension(str2, ".ldf"));
ExecuteCommand(command);
conManager.Connection.ChangeDatabase(databaseName);
if (Mode == ProviderMode.Sql2005)
{
var set = new HashSet<string>();
foreach (MetaTable table3 in services.Model.GetTables())
{
string createSchemaForTableCommand = SqlBuilder.GetCreateSchemaForTableCommand(table3);
if (!string.IsNullOrEmpty(createSchemaForTableCommand))
{
set.Add(createSchemaForTableCommand);
}
}
foreach (string str7 in set)
{
ExecuteCommand(str7);
}
}
var builder2 = new StringBuilder();
foreach (MetaTable table4 in services.Model.GetTables())
{
string str8 = SqlBuilder.GetCreateTableCommand(table4);
if (!string.IsNullOrEmpty(str8))
{
builder2.AppendLine(str8);
}
}
foreach (MetaTable table5 in services.Model.GetTables())
{
foreach (string str9 in SqlBuilder.GetCreateForeignKeyCommands(table5))
{
if (!string.IsNullOrEmpty(str9))
{
builder2.AppendLine(str9);
}
}
}
if (builder2.Length > 0)
{
builder2.Insert(0, "SET ARITHABORT ON" + Environment.NewLine);
ExecuteCommand(builder2.ToString());
}
}
}
finally
{
conManager.ReleaseConnection(this);
if (conManager.Connection is SqlConnection)
{
SqlConnection.ClearAllPools();
}
}
}
void IProvider.DeleteDatabase()
{
var SqlBuilder = new SqlBuilder(SqlIdentifier);
CheckDispose();
CheckInitialized();
if (!deleted)
{
if (Mode == ProviderMode.SqlCE)
{
((IProvider)this).ClearConnection();
File.Delete(dbName);
deleted = true;
}
else
{
string connectionString = conManager.Connection.ConnectionString;
IDbConnection connection = conManager.UseConnection(this);
try
{
connection.ChangeDatabase("MASTER");
if (connection is SqlConnection)
{
SqlConnection.ClearAllPools();
}
if (Log != null)
{
Log.WriteLine(Strings.LogAttemptingToDeleteDatabase(dbName));
}
ExecuteCommand(SqlBuilder.GetDropDatabaseCommand(dbName));
deleted = true;
}
finally
{
conManager.ReleaseConnection(this);
if ((conManager.Connection.State == ConnectionState.Closed) &&
(string.Compare(conManager.Connection.ConnectionString, connectionString,
StringComparison.Ordinal) != 0))
{
conManager.Connection.ConnectionString = connectionString;
}
}
}
}
}
private void ExecuteCommand(string command)
{
if (Log != null)
{
Log.WriteLine(command);
Log.WriteLine();
}
IDbCommand command2 = conManager.Connection.CreateCommand();
command2.CommandTimeout = CommandTimeout;
command2.Transaction = conManager.Transaction;
command2.CommandText = command;
command2.ExecuteNonQuery();
}
internal override ITypeSystemProvider CreateTypeSystemProvider()
{
return new SqlTypeSystem.Sql2005Provider();
}
}
}
| |
using System;
using System.Diagnostics;
/*
* Computation of the n'th decimal digit of \pi with very little memory.
* Written by Fabrice Bellard on January 8, 1997.
*
* We use a slightly modified version of the method described by Simon
* Plouffe in "On the Computation of the n'th decimal digit of various
* transcendental numbers" (November 1996). We have modified the algorithm
* to get a running time of O(n^2) instead of O(n^3log(n)^3).
*
* This program uses mostly integer arithmetic. It may be slow on some
* hardwares where integer multiplications and divisons must be done
* by software. We have supposed that 'int' has a size of 32 bits. If
* your compiler supports 'long long' integers of 64 bits, you may use
* the integer version of 'mul_mod' (see HAS_LONG_LONG).
*/
namespace Alchemi.Examples.PiCalculator
{
public class Plouffe_Bellard
{
public Plouffe_Bellard() {}
private static int mul_mod(int a, int b, int m)
{
return (int) (((long) a * (long) b) % m);
}
/* return the inverse of x mod y */
private static int inv_mod(int x, int y)
{
int q,u,v,a,c,t;
u=x;
v=y;
c=1;
a=0;
do
{
q=v/u;
t=c;
c=a-q*c;
a=t;
t=u;
u=v-q*u;
v=t;
} while (u!=0);
a=a%y;
if (a<0)
{
a=y+a;
}
return a;
}
/* return (a^b) mod m */
private static int pow_mod(int a, int b, int m)
{
int r, aa;
r=1;
aa=a;
while (true)
{
if ((b & 1) != 0)
{
r = mul_mod(r, aa, m);
}
b = b >> 1;
if (b == 0)
{
break;
}
aa = mul_mod(aa, aa, m);
}
return r;
}
/* return true if n is prime */
private static bool is_prime(int n)
{
if ((n % 2) == 0)
{
return false;
}
int r = (int) Math.Sqrt(n);
for (int i = 3; i <= r; i += 2)
{
if ((n % i) == 0)
{
return false;
}
}
return true;
}
/* return the prime number immediatly after n */
private static int next_prime(int n)
{
do
{
n++;
} while (!is_prime(n));
return n;
}
public String CalculatePiDigits(int n)
{
int av, vmax, num, den, s, t;
int N = (int) ((n + 20) * Math.Log(10) / Math.Log(2));
double sum = 0;
for (int a = 3; a <= (2 * N); a = next_prime(a))
{
vmax = (int) (Math.Log(2 * N) / Math.Log(a));
av = 1;
for (int i = 0; i < vmax; i++)
{
av = av * a;
}
s = 0;
num = 1;
den = 1;
int v = 0;
int kq = 1;
int kq2 = 1;
for (int k = 1; k <= N; k++)
{
t = k;
if (kq >= a)
{
do
{
t = t / a;
v--;
} while ((t % a) == 0);
kq = 0;
}
kq++;
num = mul_mod(num, t, av);
t = 2 * k - 1;
if (kq2 >= a)
{
if (kq2 == a)
{
do
{
t = t / a;
v++;
} while ((t % a) == 0);
}
kq2 -= a;
}
den = mul_mod(den, t, av);
kq2 += 2;
if (v > 0)
{
t = inv_mod(den, av);
t = mul_mod(t, num, av);
t = mul_mod(t, k, av);
for (int i = v; i < vmax; i++)
{
t = mul_mod(t, a, av);
}
s += t;
if (s >= av)
{
s -= av;
}
}
}
t = pow_mod(10, n - 1, av);
s = mul_mod(s, t, av);
sum = (sum + (double) s / (double) av) % 1.0;
}
int Result = (int) (sum * 1e9);
String StringResult = String.Format("{0:D9}", Result);
return StringResult;
}
public int DigitsReturned()
{
return 9;
}
}
}
| |
// PlantUML Studio
// Copyright 2013 Matthew Hamilton - [email protected]
// Copyright 2010 Omar Al Zabir - http://omaralzabir.com/ (original author)
//
// 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.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using PlantUmlStudio.Core;
using SharpEssentials.Collections;
using SharpEssentials.Controls.Mvvm;
using SharpEssentials.Controls.Mvvm.Commands;
using SharpEssentials.Observable;
namespace PlantUmlStudio.ViewModel
{
/// <summary>
/// Manages open diagrams and also serves as the main application driver.
/// </summary>
public class DiagramManagerViewModel : ViewModelBase, IDiagramManager
{
public DiagramManagerViewModel(IDiagramExplorer explorer, Func<Diagram, IDiagramEditor> editorFactory)
: this()
{
_explorer = explorer;
_editorFactory = editorFactory;
_explorer.OpenPreviewRequested += explorer_OpenPreviewRequested;
}
private DiagramManagerViewModel()
{
_openDiagrams = Property.New(this, p => OpenDiagrams);
_openDiagrams.Value = new ObservableCollection<IDiagramEditor>();
_openDiagram = Property.New(this, p => p.OpenDiagram);
_closingDiagram = Property.New(this, p => p.ClosingDiagram);
SaveClosingDiagramCommand = new RelayCommand(() => _editorsNeedingSaving.Add(ClosingDiagram));
OpenDiagramCommand = new RelayCommand<PreviewDiagramViewModel>(OpenDiagramForEdit, d => d != null);
CloseCommand = new RelayCommand(Close);
SaveAllCommand = Command.For(this)
.DependsOnCollection(p => p.OpenDiagrams)
.When(c => c.Any(p => p.CanSave))
.ExecutesAsync(SaveAllAsync);
}
private void explorer_OpenPreviewRequested(object sender, OpenPreviewRequestedEventArgs e)
{
OpenDiagramForEdit(e.RequestedPreview);
}
/// <see cref="IDiagramManager.OpenDiagram"/>
public IDiagramEditor OpenDiagram
{
get { return _openDiagram.Value; }
set { _openDiagram.Value = value; }
}
/// <see cref="IDiagramManager.OpenDiagrams"/>
public ICollection<IDiagramEditor> OpenDiagrams => _openDiagrams.Value;
/// <summary>
/// Command to open a diagram for editing.
/// </summary>
public ICommand OpenDiagramCommand { get; private set; }
/// <see cref="IDiagramManager.OpenDiagramForEdit"/>
public void OpenDiagramForEdit(PreviewDiagramViewModel diagram)
{
if (diagram == null)
throw new ArgumentNullException(nameof(diagram));
OpenDiagram = OpenDiagrams.FirstOrNone(d => d.Diagram.Equals(diagram.Diagram)).GetOrElse(() =>
{
var newEditor = _editorFactory(diagram.Diagram);
newEditor.DiagramImage = diagram.ImagePreview;
newEditor.Closing += diagramEditor_Closing;
newEditor.Closed += diagramEditor_Closed;
newEditor.Saved += diagramEditor_Saved;
OpenDiagrams.Add(newEditor);
OnDiagramOpened(diagram.Diagram);
return newEditor;
});
}
/// <see cref="IDiagramManager.DiagramOpened"/>
public event EventHandler<DiagramOpenedEventArgs> DiagramOpened;
private void OnDiagramOpened(Diagram diagram)
{
DiagramOpened?.Invoke(this, new DiagramOpenedEventArgs(diagram));
}
/// <see cref="IDiagramManager.DiagramClosed"/>
public event EventHandler<DiagramClosedEventArgs> DiagramClosed;
private void OnDiagramClosed(Diagram diagram)
{
DiagramClosed?.Invoke(this, new DiagramClosedEventArgs(diagram));
}
/// <summary>
/// Command to save all modified open diagrams.
/// </summary>
public IAsyncCommand SaveAllCommand { get; private set; }
/// <see cref="IDiagramManager.SaveAllAsync"/>
public async Task SaveAllAsync()
{
await OpenDiagrams.Where(d => d.CanSave).Select(d => d.SaveAsync());
}
void diagramEditor_Saved(object sender, EventArgs e)
{
var diagramEditor = (IDiagramEditor)sender;
Explorer.PreviewDiagrams.FirstOrNone(d => d.Diagram.Equals(diagramEditor.Diagram)).Apply(preview =>
{
preview.ImagePreview = diagramEditor.DiagramImage; // Update preview with new image.
// If for some reason the matching preview's Diagram is a different instance than the
// editor's Diagram (which may occur if the preview list was refreshed or the diagram was
// restored through the 'restore open diagrams' feature), update the preview's Diagram's
// data.
if (!ReferenceEquals(preview.Diagram, diagramEditor.Diagram))
{
preview.Diagram.Content = diagramEditor.Diagram.Content;
preview.Diagram.ImageFile = diagramEditor.Diagram.ImageFile;
}
});
}
void diagramEditor_Closing(object sender, CancelEventArgs e)
{
ClosingDiagram = null;
ClosingDiagram = (IDiagramEditor)sender;
}
async void diagramEditor_Closed(object sender, EventArgs e)
{
var diagramEditor = (IDiagramEditor)sender;
if (_editorsNeedingSaving.Contains(diagramEditor))
{
await SaveClosingEditorAsync(diagramEditor);
}
else
{
RemoveEditor(diagramEditor);
}
}
private async Task SaveClosingEditorAsync(IDiagramEditor diagramEditor)
{
var saveTask = diagramEditor.SaveAsync();
_editorSaveTasks.Add(saveTask);
_editorsNeedingSaving.Remove(diagramEditor);
await saveTask;
_editorSaveTasks.Remove(saveTask);
RemoveEditor(diagramEditor);
}
private void RemoveEditor(IDiagramEditor editor)
{
var diagram = editor.Diagram;
editor.Closing -= diagramEditor_Closing;
editor.Closed -= diagramEditor_Closed;
editor.Saved -= diagramEditor_Saved;
OpenDiagrams.Remove(editor);
editor.Dispose();
OnDiagramClosed(diagram);
}
/// <summary>
/// Saves the currently closing diagram.
/// </summary>
public ICommand SaveClosingDiagramCommand { get; private set; }
/// <summary>
/// The diagram currently being closed, if any.
/// </summary>
public IDiagramEditor ClosingDiagram
{
get { return _closingDiagram.Value; }
set { _closingDiagram.Value = value; }
}
/// <summary>
/// Command executed when closing a diagram manager.
/// </summary>
public ICommand CloseCommand { get; private set; }
/// <see cref="IDiagramManager.Close"/>
public void Close()
{
OnClosing();
var unsavedOpenDiagrams = OpenDiagrams.Where(od => od.CodeEditor.IsModified).ToList();
foreach (var openDiagram in unsavedOpenDiagrams)
{
openDiagram.Close();
}
Task.WaitAll(_editorSaveTasks.ToArray());
}
/// <see cref="IDiagramManager.Closing"/>
public event EventHandler<EventArgs> Closing;
private void OnClosing()
{
Closing?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Diagram previews.
/// </summary>
public IDiagramExplorer Explorer => _explorer;
private readonly Property<IDiagramEditor> _openDiagram;
private readonly Property<ICollection<IDiagramEditor>> _openDiagrams;
private readonly Property<IDiagramEditor> _closingDiagram;
private readonly ICollection<IDiagramEditor> _editorsNeedingSaving = new HashSet<IDiagramEditor>();
private readonly ICollection<Task> _editorSaveTasks = new HashSet<Task>();
private readonly IDiagramExplorer _explorer;
private readonly Func<Diagram, IDiagramEditor> _editorFactory;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace ACQ.Math
{
public static class Utils
{
#region Floating Point
/// <summary>
/// Returns a with the same sign as b
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static double Sign(double a, double b)
{
double abs = System.Math.Abs(a);
if (b >= 0.0)
{
return abs;
}
else
{
return -abs;
}
}
public static double Sign(double a)
{
return (a >= 0.0) ? 1.0 : -1.0;
}
/// <summary>
/// Returns sqrt(a*a + b*b)
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static double Hypotenuse(double a, double b)
{
if (System.Math.Abs(a) > System.Math.Abs(b))
{
double r = b / a;
return System.Math.Abs(a) * System.Math.Sqrt(1 + r * r);
}
if (b != 0)
{
double r = a / b;
return System.Math.Abs(b) * System.Math.Sqrt(1 + r * r);
}
return 0.0;
}
public static double Sqr(double x)
{
return x * x;
}
public static double Cube(double x)
{
return x * x * x;
}
public static double RadToDeg(double x)
{
return x * Const.radian;
}
public static double DegToRad(double x)
{
return x / Const.radian;
}
#endregion
#region Integer Routines
public static int Factorial(int n)
{
if (n == 0)
return 1;
else
return n * Factorial(n - 1);
}
public static Int64 Factorial(Int64 n)
{
if (n == 0)
return 1;
else
return n * Factorial(n - 1);
}
#endregion
#region Generic Routines
public static Tuple<T, int> MinIndex<T>(params T[] a) where T : IComparable<T>
{
if (a == null || a.Length == 0)
{
throw new ArgumentNullException();
}
int index = 0;
T min = a[0];
for (int i = 1; i < a.Length; i++)
{
if (min.CompareTo(a[i]) > 0)
{
min = a[i];
index = i;
}
}
return new Tuple<T, int>(min, index);
}
public static T Min<T>(params T[] a) where T : IComparable<T>
{
if (a == null || a.Length == 0)
{
throw new ArgumentNullException();
}
T min = a[0];
for (int i = 1; i < a.Length; i++)
{
if (min.CompareTo(a[i]) > 0)
{
min = a[i];
}
}
return min;
}
public static T Max<T>(params T[] a) where T : IComparable<T>
{
if (a == null || a.Length == 0)
{
throw new ArgumentNullException();
}
T max = a[0];
for (int i = 1; i < a.Length; i++)
{
if (max.CompareTo(a[i]) < 0)
{
max = a[i];
}
}
return max;
}
public static Tuple<T, bool> MinBound<T>(T bound, params T[] a) where T : IComparable<T>
{
if (a == null || a.Length == 0)
{
throw new ArgumentNullException();
}
bool first = true;
T min = default(T); //this value will not be used
for (int i = 0; i < a.Length; i++)
{
T value = a[i];
if (value.CompareTo(bound) > 0) //if value > bound
{
if (first)
{
min = value;
first = false;
}else if (value.CompareTo(min) < 0) // if value < min
{
min = value;
}
}
}
return new Tuple<T,bool>(min, !first);
}
public static void Bound<T>(T[] a, T min, T max) where T : IComparable<T>
{
if (a == null)
{
throw new ArgumentNullException();
}
for (int i = 0; i < a.Length; i++)
{
if (a[i].CompareTo(min) < 0)
a[i] = min;
else if (a[i].CompareTo(max) > 0)
a[i] = max;
}
}
public static T Bound<T>(T value, T min, T max) where T : IComparable<T>
{
if (value.CompareTo(min) < 0)
return min;
else if (value.CompareTo(max) > 0)
return max;
else
return value;
}
#endregion
#region Array Routines
/// <summary>
/// Fills arrays with specified value
/// </summary>
/// <typeparam name="T">any value type</typeparam>
/// <param name="a"></param>
/// <param name="value"></param>
public static void FillArray<T>(T[] a, T value)
{
for (int i = 0; i < a.Length; i++)
{
a[i] = value;
}
}
public static T[][] JaggedArray<T>(int rows, int cols)
{
T[][] res = new T[rows][];
for (int i = 0; i < rows; i++)
{
res[i] = new T[cols];
}
return res;
}
public static T[][] SquareToJagged<T>(T[,] a)
{
int rows = a.GetLength(0);
int cols = a.GetLength(1);
T[][] res = new T[rows][];
for (int i = 0; i < rows; i++)
{
T[] row = new T[cols];
for (int j = 0; j < cols; j++)
{
row[j] = a[i, j];
}
res[i] = row;
}
return res;
}
/// <summary>
/// generates n points between min and max. For N less or equal to 2 Linspace returns [min, max].
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <param name="n"></param>
/// <returns></returns>
public static double[] Linspace(double min, double max, int n)
{
int m = System.Math.Min(2, n); //needs at least two points
double[] x = new double[m];
double step = (max - min) / (m - 1);
for (int i = 1; i < x.Length - 1; i++)
{
x[i] = min + step * i;
}
x[0] = min;
x[m - 1] = max;
return x;
}
#endregion
}
/// <summary>
/// Some frequently used constants
/// </summary>
public static class Const
{
public const double epsilon = 2.2204460492503131e-16;
public const double epsilon_sqrt = 1.4901161193847656e-08;
public const double epsilon_sqrt4 = 1.2207031250000000e-04;
public const double pi = 3.1415926535897932384626433832795;
public const double twopi = 6.283185307179586476925286766559;
public const double e = 2.3025850929940456840179914546844;
public const double radian = 57.295779513082320876798154814105;
public const double tiny = 1.6033346880071782e-291; //2^-966
}
}
| |
/*
* 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.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using MySql.Data.MySqlClient;
using OpenMetaverse;
namespace OpenSim.Data.MySQL
{
public class MySQLGenericTableHandler<T> : MySqlFramework where T: class, new()
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public MySQLGenericTableHandler(MySqlTransaction trans,
string realm, string storeName) : base(trans)
{
m_Realm = realm;
CommonConstruct(storeName);
}
public MySQLGenericTableHandler(string connectionString,
string realm, string storeName) : base(connectionString)
{
m_Realm = realm;
CommonConstruct(storeName);
}
protected void CommonConstruct(string storeName)
{
if (storeName != String.Empty)
{
// We always use a new connection for any Migrations
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, storeName);
m.Update();
}
}
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (fields.Length == 0)
return;
foreach (FieldInfo f in fields)
{
if (f.Name != "Data")
m_Fields[f.Name] = f;
else
m_DataField = f;
}
}
private void CheckColumnNames(IDataReader reader)
{
if (m_ColumnNames != null)
return;
List<string> columnNames = new List<string>();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null &&
(!m_Fields.ContainsKey(row["ColumnName"].ToString())))
columnNames.Add(row["ColumnName"].ToString());
}
m_ColumnNames = columnNames;
}
public virtual T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public virtual T[] Get(string[] fields, string[] keys)
{
return Get(fields, keys, String.Empty);
}
public virtual T[] Get(string[] fields, string[] keys, string options)
{
int flen = fields.Length;
if (flen == 0 || flen != keys.Length)
return new T[0];
int flast = flen - 1;
StringBuilder sb = new StringBuilder(1024);
sb.AppendFormat("select * from {0} where ", m_Realm);
using (MySqlCommand cmd = new MySqlCommand())
{
for (int i = 0 ; i < flen ; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
if(i< flast)
sb.AppendFormat("`{0}` = ?{0} and ", fields[i]);
else
sb.AppendFormat("`{0}` = ?{0} ", fields[i]);
}
sb.Append(options);
cmd.CommandText = sb.ToString();
return DoQuery(cmd);
}
}
protected T[] DoQuery(MySqlCommand cmd)
{
if (m_trans == null)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
T[] ret = DoQueryWithConnection(cmd, dbcon);
dbcon.Close();
return ret;
}
}
else
{
return DoQueryWithTransaction(cmd, m_trans);
}
}
protected T[] DoQueryWithTransaction(MySqlCommand cmd, MySqlTransaction trans)
{
cmd.Transaction = trans;
return DoQueryWithConnection(cmd, trans.Connection);
}
protected T[] DoQueryWithConnection(MySqlCommand cmd, MySqlConnection dbcon)
{
List<T> result = new List<T>();
cmd.Connection = dbcon;
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader == null)
return new T[0];
CheckColumnNames(reader);
while (reader.Read())
{
T row = new T();
foreach (string name in m_Fields.Keys)
{
if (reader[name] is DBNull)
{
continue;
}
if (m_Fields[name].FieldType == typeof(bool))
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0);
}
else if (m_Fields[name].FieldType == typeof(UUID))
{
m_Fields[name].SetValue(row, DBGuid.FromDB(reader[name]));
}
else if (m_Fields[name].FieldType == typeof(int))
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else if (m_Fields[name].FieldType == typeof(uint))
{
uint v = Convert.ToUInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else
{
m_Fields[name].SetValue(row, reader[name]);
}
}
if (m_DataField != null)
{
Dictionary<string, string> data =
new Dictionary<string, string>();
foreach (string col in m_ColumnNames)
{
data[col] = reader[col].ToString();
if (data[col] == null)
data[col] = String.Empty;
}
m_DataField.SetValue(row, data);
}
result.Add(row);
}
}
cmd.Connection = null;
return result.ToArray();
}
public virtual T[] Get(string where)
{
using (MySqlCommand cmd = new MySqlCommand())
{
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
}
public virtual bool Store(T row)
{
// m_log.DebugFormat("[MYSQL GENERIC TABLE HANDLER]: Store(T row) invoked");
using (MySqlCommand cmd = new MySqlCommand())
{
string query = "";
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add("?" + fi.Name);
// Temporarily return more information about what field is unexpectedly null for
// http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
// InventoryTransferModule or we may be required to substitute a DBNull here.
if (fi.GetValue(row) == null)
throw new NullReferenceException(
string.Format(
"[MYSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
fi.Name, row));
cmd.Parameters.AddWithValue(fi.Name, fi.GetValue(row).ToString());
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
names.Add(kvp.Key);
values.Add("?" + kvp.Key);
cmd.Parameters.AddWithValue("?" + kvp.Key, kvp.Value);
}
}
query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
cmd.CommandText = query;
if (ExecuteNonQuery(cmd) > 0)
return true;
return false;
}
}
public virtual bool Delete(string field, string key)
{
return Delete(new string[] { field }, new string[] { key });
}
public virtual bool Delete(string[] fields, string[] keys)
{
// m_log.DebugFormat(
// "[MYSQL GENERIC TABLE HANDLER]: Delete(string[] fields, string[] keys) invoked with {0}:{1}",
// string.Join(",", fields), string.Join(",", keys));
if (fields.Length != keys.Length)
return false;
List<string> terms = new List<string>();
using (MySqlCommand cmd = new MySqlCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
terms.Add("`" + fields[i] + "` = ?" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("delete from {0} where {1}", m_Realm, where);
cmd.CommandText = query;
return ExecuteNonQuery(cmd) > 0;
}
}
public long GetCount(string field, string key)
{
return GetCount(new string[] { field }, new string[] { key });
}
public long GetCount(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return 0;
List<string> terms = new List<string>();
using (MySqlCommand cmd = new MySqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
terms.Add("`" + fields[i] + "` = ?" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
Object result = DoQueryScalar(cmd);
return Convert.ToInt64(result);
}
}
public long GetCount(string where)
{
using (MySqlCommand cmd = new MySqlCommand())
{
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
object result = DoQueryScalar(cmd);
return Convert.ToInt64(result);
}
}
public object DoQueryScalar(MySqlCommand cmd)
{
if (m_trans == null)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
cmd.Connection = dbcon;
Object ret = cmd.ExecuteScalar();
cmd.Connection = null;
dbcon.Close();
return ret;
}
}
else
{
cmd.Connection = m_trans.Connection;
cmd.Transaction = m_trans;
return cmd.ExecuteScalar();
}
}
}
}
| |
/*
* Deed API
*
* Land Registry Deed API
*
* OpenAPI spec version: 2.3.1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace IO.Swagger.Model
{
/// <summary>
/// Unique deed, consisting of property, borrower and charge information as well as clauses for the deed.
/// </summary>
[DataContract]
public partial class OperativeDeedDeed : IEquatable<OperativeDeedDeed>
{
/// <summary>
/// Initializes a new instance of the <see cref="OperativeDeedDeed" /> class.
/// </summary>
/// <param name="TitleNumber">Unique Land Registry identifier for the registered estate..</param>
/// <param name="MdRef">Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345).</param>
/// <param name="Borrowers">Borrowers.</param>
/// <param name="ChargeClause">ChargeClause.</param>
/// <param name="AdditionalProvisions">AdditionalProvisions.</param>
/// <param name="Lender">Lender.</param>
/// <param name="EffectiveClause">Text to display the make effective clause.</param>
/// <param name="PropertyAddress">The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA.</param>
/// <param name="Reference">Reference.</param>
/// <param name="DeedStatus">Current state of the deed.</param>
/// <param name="EffectiveDate">An effective date is shown if the deed is made effective.</param>
public OperativeDeedDeed(string TitleNumber = null, string MdRef = null, OpBorrowers Borrowers = null, ChargeClause ChargeClause = null, AdditionalProvisions AdditionalProvisions = null, Lender Lender = null, string EffectiveClause = null, string PropertyAddress = null, string Reference = null, string DeedStatus = null, string EffectiveDate = null)
{
this.TitleNumber = TitleNumber;
this.MdRef = MdRef;
this.Borrowers = Borrowers;
this.ChargeClause = ChargeClause;
this.AdditionalProvisions = AdditionalProvisions;
this.Lender = Lender;
this.EffectiveClause = EffectiveClause;
this.PropertyAddress = PropertyAddress;
this.Reference = Reference;
this.DeedStatus = DeedStatus;
this.EffectiveDate = EffectiveDate;
}
/// <summary>
/// Unique Land Registry identifier for the registered estate.
/// </summary>
/// <value>Unique Land Registry identifier for the registered estate.</value>
[DataMember(Name="title_number", EmitDefaultValue=false)]
public string TitleNumber { get; set; }
/// <summary>
/// Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345)
/// </summary>
/// <value>Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345)</value>
[DataMember(Name="md_ref", EmitDefaultValue=false)]
public string MdRef { get; set; }
/// <summary>
/// Gets or Sets Borrowers
/// </summary>
[DataMember(Name="borrowers", EmitDefaultValue=false)]
public OpBorrowers Borrowers { get; set; }
/// <summary>
/// Gets or Sets ChargeClause
/// </summary>
[DataMember(Name="charge_clause", EmitDefaultValue=false)]
public ChargeClause ChargeClause { get; set; }
/// <summary>
/// Gets or Sets AdditionalProvisions
/// </summary>
[DataMember(Name="additional_provisions", EmitDefaultValue=false)]
public AdditionalProvisions AdditionalProvisions { get; set; }
/// <summary>
/// Gets or Sets Lender
/// </summary>
[DataMember(Name="lender", EmitDefaultValue=false)]
public Lender Lender { get; set; }
/// <summary>
/// Text to display the make effective clause
/// </summary>
/// <value>Text to display the make effective clause</value>
[DataMember(Name="effective_clause", EmitDefaultValue=false)]
public string EffectiveClause { get; set; }
/// <summary>
/// The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA
/// </summary>
/// <value>The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA</value>
[DataMember(Name="property_address", EmitDefaultValue=false)]
public string PropertyAddress { get; set; }
/// <summary>
/// Gets or Sets Reference
/// </summary>
[DataMember(Name="reference", EmitDefaultValue=false)]
public string Reference { get; set; }
/// <summary>
/// Current state of the deed
/// </summary>
/// <value>Current state of the deed</value>
[DataMember(Name="deed_status", EmitDefaultValue=false)]
public string DeedStatus { get; set; }
/// <summary>
/// An effective date is shown if the deed is made effective
/// </summary>
/// <value>An effective date is shown if the deed is made effective</value>
[DataMember(Name="effective_date", EmitDefaultValue=false)]
public string EffectiveDate { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OperativeDeedDeed {\n");
sb.Append(" TitleNumber: ").Append(TitleNumber).Append("\n");
sb.Append(" MdRef: ").Append(MdRef).Append("\n");
sb.Append(" Borrowers: ").Append(Borrowers).Append("\n");
sb.Append(" ChargeClause: ").Append(ChargeClause).Append("\n");
sb.Append(" AdditionalProvisions: ").Append(AdditionalProvisions).Append("\n");
sb.Append(" Lender: ").Append(Lender).Append("\n");
sb.Append(" EffectiveClause: ").Append(EffectiveClause).Append("\n");
sb.Append(" PropertyAddress: ").Append(PropertyAddress).Append("\n");
sb.Append(" Reference: ").Append(Reference).Append("\n");
sb.Append(" DeedStatus: ").Append(DeedStatus).Append("\n");
sb.Append(" EffectiveDate: ").Append(EffectiveDate).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as OperativeDeedDeed);
}
/// <summary>
/// Returns true if OperativeDeedDeed instances are equal
/// </summary>
/// <param name="other">Instance of OperativeDeedDeed to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OperativeDeedDeed other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.TitleNumber == other.TitleNumber ||
this.TitleNumber != null &&
this.TitleNumber.Equals(other.TitleNumber)
) &&
(
this.MdRef == other.MdRef ||
this.MdRef != null &&
this.MdRef.Equals(other.MdRef)
) &&
(
this.Borrowers == other.Borrowers ||
this.Borrowers != null &&
this.Borrowers.Equals(other.Borrowers)
) &&
(
this.ChargeClause == other.ChargeClause ||
this.ChargeClause != null &&
this.ChargeClause.Equals(other.ChargeClause)
) &&
(
this.AdditionalProvisions == other.AdditionalProvisions ||
this.AdditionalProvisions != null &&
this.AdditionalProvisions.Equals(other.AdditionalProvisions)
) &&
(
this.Lender == other.Lender ||
this.Lender != null &&
this.Lender.Equals(other.Lender)
) &&
(
this.EffectiveClause == other.EffectiveClause ||
this.EffectiveClause != null &&
this.EffectiveClause.Equals(other.EffectiveClause)
) &&
(
this.PropertyAddress == other.PropertyAddress ||
this.PropertyAddress != null &&
this.PropertyAddress.Equals(other.PropertyAddress)
) &&
(
this.Reference == other.Reference ||
this.Reference != null &&
this.Reference.Equals(other.Reference)
) &&
(
this.DeedStatus == other.DeedStatus ||
this.DeedStatus != null &&
this.DeedStatus.Equals(other.DeedStatus)
) &&
(
this.EffectiveDate == other.EffectiveDate ||
this.EffectiveDate != null &&
this.EffectiveDate.Equals(other.EffectiveDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.TitleNumber != null)
hash = hash * 59 + this.TitleNumber.GetHashCode();
if (this.MdRef != null)
hash = hash * 59 + this.MdRef.GetHashCode();
if (this.Borrowers != null)
hash = hash * 59 + this.Borrowers.GetHashCode();
if (this.ChargeClause != null)
hash = hash * 59 + this.ChargeClause.GetHashCode();
if (this.AdditionalProvisions != null)
hash = hash * 59 + this.AdditionalProvisions.GetHashCode();
if (this.Lender != null)
hash = hash * 59 + this.Lender.GetHashCode();
if (this.EffectiveClause != null)
hash = hash * 59 + this.EffectiveClause.GetHashCode();
if (this.PropertyAddress != null)
hash = hash * 59 + this.PropertyAddress.GetHashCode();
if (this.Reference != null)
hash = hash * 59 + this.Reference.GetHashCode();
if (this.DeedStatus != null)
hash = hash * 59 + this.DeedStatus.GetHashCode();
if (this.EffectiveDate != null)
hash = hash * 59 + this.EffectiveDate.GetHashCode();
return hash;
}
}
}
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using BitSharper.IO;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Math;
namespace BitSharper
{
/// <summary>
/// A collection of various utility methods that are helpful for working with the BitCoin protocol.
/// To enable debug logging from the library, run with -Dbitcoinj.logging=true on your command line.
/// </summary>
public static class Utils
{
// TODO: Replace this nanocoins business with something better.
/// <summary>
/// How many "nanocoins" there are in a BitCoin.
/// </summary>
/// <remarks>
/// A nanocoin is the smallest unit that can be transferred using BitCoin.
/// The term nanocoin is very misleading, though, because there are only 100 million
/// of them in a coin (whereas one would expect 1 billion.
/// </remarks>
public const ulong Coin = 100000000;
/// <summary>
/// How many "nanocoins" there are in 0.01 BitCoins.
/// </summary>
/// <remarks>
/// A nanocoin is the smallest unit that can be transferred using BitCoin.
/// The term nanocoin is very misleading, though, because there are only 100 million
/// of them in a coin (whereas one would expect 1 billion).
/// </remarks>
public const ulong Cent = 1000000;
/// <summary>
/// Convert an amount expressed in the way humans are used to into nanocoins.
/// </summary>
public static ulong ToNanoCoins(uint coins, uint cents)
{
Debug.Assert(cents < 100);
var bi = coins*Coin;
bi += cents*Cent;
return bi;
}
/// <summary>
/// Convert an amount expressed in the way humans are used to into nanocoins.
/// </summary>
/// <remarks>
/// This takes string in a format understood by <see cref="System.Double.Parse(string)"/>,
/// for example "0", "1", "0.10", "1.23E3", "1234.5E-5".
/// </remarks>
/// <exception cref="ArithmeticException">If you try to specify fractional nanocoins.</exception>
public static ulong ToNanoCoins(string coins)
{
var value = decimal.Parse(coins, NumberStyles.Float)*Coin;
if (value != Math.Round(value))
{
throw new ArithmeticException();
}
return checked((ulong) value);
}
public static void Uint32ToByteArrayBe(uint val, byte[] @out, int offset)
{
@out[offset + 0] = (byte) (val >> 24);
@out[offset + 1] = (byte) (val >> 16);
@out[offset + 2] = (byte) (val >> 8);
@out[offset + 3] = (byte) (val >> 0);
}
public static void Uint32ToByteArrayLe(uint val, byte[] @out, int offset)
{
@out[offset + 0] = (byte) (val >> 0);
@out[offset + 1] = (byte) (val >> 8);
@out[offset + 2] = (byte) (val >> 16);
@out[offset + 3] = (byte) (val >> 24);
}
/// <exception cref="IOException"/>
public static void Uint32ToByteStreamLe(uint val, Stream stream)
{
stream.Write((byte) (val >> 0));
stream.Write((byte) (val >> 8));
stream.Write((byte) (val >> 16));
stream.Write((byte) (val >> 24));
}
/// <exception cref="IOException"/>
public static void Uint64ToByteStreamLe(ulong val, Stream stream)
{
var bytes = BitConverter.GetBytes(val);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(bytes);
}
stream.Write(bytes);
}
/// <summary>
/// See <see cref="DoubleDigest(byte[], int, int)"/>.
/// </summary>
public static byte[] DoubleDigest(byte[] input)
{
return DoubleDigest(input, 0, input.Length);
}
/// <summary>
/// Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again. This is
/// standard procedure in BitCoin. The resulting hash is in big endian form.
/// </summary>
public static byte[] DoubleDigest(byte[] input, int offset, int length)
{
var algorithm = new SHA256Managed();
var first = algorithm.ComputeHash(input, offset, length);
return algorithm.ComputeHash(first);
}
/// <summary>
/// Calculates SHA256(SHA256(byte range 1 + byte range 2)).
/// </summary>
public static byte[] DoubleDigestTwoBuffers(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2)
{
var algorithm = new SHA256Managed();
var buffer = new byte[length1 + length2];
Array.Copy(input1, offset1, buffer, 0, length1);
Array.Copy(input2, offset2, buffer, length1, length2);
var first = algorithm.ComputeHash(buffer, 0, buffer.Length);
return algorithm.ComputeHash(first);
}
/// <summary>
/// Returns the given byte array hex encoded.
/// </summary>
public static string BytesToHexString(byte[] bytes)
{
var buf = new StringBuilder(bytes.Length*2);
foreach (var b in bytes)
{
var s = b.ToString("x");
if (s.Length < 2)
buf.Append('0');
buf.Append(s);
}
return buf.ToString();
}
/// <summary>
/// Returns a copy of the given byte array in reverse order.
/// </summary>
public static byte[] ReverseBytes(byte[] bytes)
{
// We could use the XOR trick here but it's easier to understand if we don't. If we find this is really a
// performance issue the matter can be revisited.
var buf = new byte[bytes.Length];
for (var i = 0; i < bytes.Length; i++)
buf[i] = bytes[bytes.Length - 1 - i];
return buf;
}
public static uint ReadUint32(byte[] bytes, int offset)
{
return (((uint) bytes[offset + 0]) << 0) |
(((uint) bytes[offset + 1]) << 8) |
(((uint) bytes[offset + 2]) << 16) |
(((uint) bytes[offset + 3]) << 24);
}
public static uint ReadUint32Be(byte[] bytes, int offset)
{
return (((uint) bytes[offset + 0]) << 24) |
(((uint) bytes[offset + 1]) << 16) |
(((uint) bytes[offset + 2]) << 8) |
(((uint) bytes[offset + 3]) << 0);
}
public static ushort ReadUint16Be(byte[] bytes, int offset)
{
return (ushort) ((bytes[offset] << 8) | bytes[offset + 1]);
}
/// <summary>
/// Calculates RIPEMD160(SHA256(input)). This is used in Address calculations.
/// </summary>
public static byte[] Sha256Hash160(byte[] input)
{
var sha256 = new SHA256Managed().ComputeHash(input);
var digest = new RipeMD160Digest();
digest.BlockUpdate(sha256, 0, sha256.Length);
var @out = new byte[20];
digest.DoFinal(@out, 0);
return @out;
}
/// <summary>
/// Returns the given value in nanocoins as a 0.12 type string.
/// </summary>
public static string BitcoinValueToFriendlyString(long value)
{
var negative = value < 0;
if (negative)
value = -value;
var coins = value/(long) Coin;
var cents = value%(long) Coin;
return string.Format("{0}{1}.{2:00}", negative ? "-" : "", coins, cents/(long) Cent);
}
/// <summary>
/// Returns the given value in nanocoins as a 0.12 type string.
/// </summary>
public static string BitcoinValueToFriendlyString(ulong value)
{
var coins = value/Coin;
var cents = value%Coin;
return string.Format("{0}.{1:00}", coins, cents/Cent);
}
/// <summary>
/// MPI encoded numbers are produced by the OpenSSL BN_bn2mpi function. They consist of
/// a 4 byte big endian length field, followed by the stated number of bytes representing
/// the number in big endian format.
/// </summary>
private static BigInteger DecodeMpi(byte[] mpi)
{
var length = ReadUint32Be(mpi, 0);
var buf = new byte[length];
Array.Copy(mpi, 4, buf, 0, (int) length);
return new BigInteger(1, buf);
}
// The representation of nBits uses another home-brew encoding, as a way to represent a large
// hash value in only 32 bits.
internal static BigInteger DecodeCompactBits(long compact)
{
var size = (byte) (compact >> 24);
var bytes = new byte[4 + size];
bytes[3] = size;
if (size >= 1) bytes[4] = (byte) (compact >> 16);
if (size >= 2) bytes[5] = (byte) (compact >> 8);
if (size >= 3) bytes[6] = (byte) (compact >> 0);
return DecodeMpi(bytes);
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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.Globalization;
using System.IO;
using System.Runtime.InteropServices;
namespace SharpDX.IO
{
/// <summary>
/// Windows File Helper.
/// </summary>
public class NativeFileStream : Stream
{
private bool canRead;
private bool canWrite;
private bool canSeek;
private IntPtr handle;
private long position;
/// <summary>
/// Initializes a new instance of the <see cref="NativeFileStream"/> class.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="fileMode">The file mode.</param>
/// <param name="access">The access mode.</param>
/// <param name="share">The share mode.</param>
public unsafe NativeFileStream(string fileName, NativeFileMode fileMode, NativeFileAccess access, NativeFileShare share = NativeFileShare.Read)
{
#if W8CORE
//uint newAccess = 0;
//const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
//const int FILE_FLAG_RANDOM_ACCESS = 0x10000000;
//const int FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000;
//var extendedParams = default(NativeFile.CREATEFILE2_EXTENDED_PARAMETERS);
//extendedParams.dwSize = (uint)Utilities.SizeOf<NativeFile.CREATEFILE2_EXTENDED_PARAMETERS>();
//extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
//extendedParams.dwFileFlags = FILE_FLAG_RANDOM_ACCESS;
//extendedParams.dwSecurityQosFlags = 0;
//extendedParams.lpSecurityAttributes = IntPtr.Zero;
//extendedParams.hTemplateFile = IntPtr.Zero;
//if ((access & NativeFileAccess.Read) != 0)
//{
// // Sets GENERIC_READ
// newAccess |= 0x00120089;
//}
//if ((access & NativeFileAccess.Write) != 0)
//{
// newAccess |= 0x00120116;
//}
//if ((access & NativeFileAccess.Execute) != 0)
//{
// newAccess |= 0x001200a0;
//}
//handle = NativeFile.Create(fileName, (NativeFileAccess)newAccess, share, fileMode, new IntPtr(&extendedParams));
handle = NativeFile.Create(fileName, access, share, fileMode, IntPtr.Zero);
#else
handle = NativeFile.Create(fileName, access, share, IntPtr.Zero, fileMode, NativeFileOptions.None, IntPtr.Zero);
#endif
if (handle == new IntPtr(-1))
{
var lastWin32Error = MarshalGetLastWin32Error();
if (lastWin32Error == 2)
{
throw new FileNotFoundException("Unable to find file", fileName);
}
var lastError = Result.GetResultFromWin32Error(lastWin32Error);
throw new IOException(string.Format(CultureInfo.InvariantCulture, "Unable to open file {0}", fileName), lastError.Code);
}
canRead = 0 != (access & NativeFileAccess.Read);
canWrite = 0 != (access & NativeFileAccess.Write);
// TODO how setup correctly canSeek flags?
// Kernel32.GetFileType(SafeFileHandle handle); is not available on W8CORE
canSeek = true;
}
private static int MarshalGetLastWin32Error()
{
#if WP8
return 0;
#else
return Marshal.GetLastWin32Error();
#endif
}
/// <inheritdoc/>
public override void Flush()
{
if (!NativeFile.FlushFileBuffers(handle))
throw new IOException("Unable to flush stream", MarshalGetLastWin32Error());
}
/// <inheritdoc/>
public override long Seek(long offset, SeekOrigin origin)
{
long newPosition;
if (!NativeFile.SetFilePointerEx(handle, offset, out newPosition, origin))
throw new IOException("Unable to seek to this position", MarshalGetLastWin32Error());
position = newPosition;
return position;
}
/// <inheritdoc/>
public override void SetLength(long value)
{
long newPosition;
if (!NativeFile.SetFilePointerEx(handle, value, out newPosition, SeekOrigin.Begin))
throw new IOException("Unable to seek to this position", MarshalGetLastWin32Error());
if (!NativeFile.SetEndOfFile(handle))
throw new IOException("Unable to set the new length", MarshalGetLastWin32Error());
if (position < value)
{
Seek(position, SeekOrigin.Begin);
}
else
{
Seek(0, SeekOrigin.End);
}
}
/// <inheritdoc/>
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
unsafe
{
fixed (void* pbuffer = buffer)
return Read((IntPtr) pbuffer, offset, count);
}
}
/// <summary>
/// Reads a block of bytes from the stream and writes the data in a given buffer.
/// </summary>
/// <param name="buffer">When this method returns, contains the specified buffer with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. </param>
/// <param name="offset">The byte offset in array at which the read bytes will be placed. </param>
/// <param name="count">The maximum number of bytes to read. </param>
/// <exception cref="ArgumentNullException">array is null. </exception>
/// <returns>The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached.</returns>
public int Read(IntPtr buffer, int offset, int count)
{
if (buffer == IntPtr.Zero)
throw new ArgumentNullException("buffer");
int numberOfBytesRead;
unsafe
{
void* pbuffer = (byte*) buffer + offset;
{
if (!NativeFile.ReadFile(handle, (IntPtr)pbuffer, count, out numberOfBytesRead, IntPtr.Zero))
throw new IOException("Unable to read from file", MarshalGetLastWin32Error());
}
position += numberOfBytesRead;
}
return numberOfBytesRead;
}
/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
unsafe
{
fixed (void* pbuffer = buffer)
Write((IntPtr)pbuffer, offset, count);
}
}
/// <summary>
/// Writes a block of bytes to this stream using data from a buffer.
/// </summary>
/// <param name="buffer">The buffer containing data to write to the stream.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream. </param>
/// <param name="count">The number of bytes to be written to the current stream. </param>
public void Write(IntPtr buffer, int offset, int count)
{
if (buffer == IntPtr.Zero)
throw new ArgumentNullException("buffer");
int numberOfBytesWritten;
unsafe
{
void* pbuffer = (byte*) buffer + offset;
{
if (!NativeFile.WriteFile(handle, (IntPtr)pbuffer, count, out numberOfBytesWritten, IntPtr.Zero))
throw new IOException("Unable to write to file", MarshalGetLastWin32Error());
}
position += numberOfBytesWritten;
}
}
/// <inheritdoc/>
public override bool CanRead
{
get
{
return canRead;
}
}
/// <inheritdoc/>
public override bool CanSeek
{
get
{
return canSeek;
}
}
/// <inheritdoc/>
public override bool CanWrite
{
get
{
return canWrite;
}
}
/// <inheritdoc/>
public override long Length
{
get
{
long length;
if (!NativeFile.GetFileSizeEx(handle, out length))
throw new IOException("Unable to get file length", MarshalGetLastWin32Error());
return length;
}
}
/// <inheritdoc/>
public override long Position
{
get
{
return position;
}
set
{
Seek(value, SeekOrigin.Begin);
position = value;
}
}
protected override void Dispose(bool disposing)
{
Utilities.CloseHandle(handle);
handle = IntPtr.Zero;
base.Dispose(disposing);
}
}
}
| |
using System;
using System.Collections;
using System.Diagnostics;
namespace Recognizer.DTW
{
public class Utils
{
#region Constants
private static readonly Random _rand = new Random();
#endregion
#region Lengths and Rects
public static RectangleR FindBox(ArrayList points)
{
double minX = double.MaxValue;
double maxX = double.MinValue;
double minY = double.MaxValue;
double maxY = double.MinValue;
foreach (PointR p in points)
{
if (p.X < minX)
minX = p.X;
if (p.X > maxX)
maxX = p.X;
if (p.Y < minY)
minY = p.Y;
if (p.Y > maxY)
maxY = p.Y;
}
return new RectangleR(minX, minY, maxX - minX, maxY - minY);
}
public static double Distance(PointR p1, PointR p2)
{
double dx = p2.X - p1.X;
double dy = p2.Y - p1.Y;
return Math.Sqrt(dx * dx + dy * dy);
}
// compute the centroid of the points given
public static PointR Centroid(ArrayList points)
{
double xsum = 0.0;
double ysum = 0.0;
foreach (PointR p in points)
{
xsum += p.X;
ysum += p.Y;
}
return new PointR(xsum / points.Count, ysum / points.Count);
}
#endregion
#region Angles and Rotations
// determines the angle, in degrees, between two points. the angle is defined
// by the circle centered on the start point with a radius to the end point,
// where 0 degrees is straight right from start (+x-axis) and 90 degrees is
// straight down (+y-axis).
public static double AngleInDegrees(PointR start, PointR end, bool positiveOnly)
{
double radians = AngleInRadians(start, end, positiveOnly);
return Rad2Deg(radians);
}
// determines the angle, in radians, between two points. the angle is defined
// by the circle centered on the start point with a radius to the end point,
// where 0 radians is straight right from start (+x-axis) and PI/2 radians is
// straight down (+y-axis).
public static double AngleInRadians(PointR start, PointR end, bool positiveOnly)
{
double radians = 0.0;
if (start.X != end.X)
{
radians = Math.Atan2(end.Y - start.Y, end.X - start.X);
}
else // pure vertical movement
{
if (end.Y < start.Y)
radians = -Math.PI / 2.0; // -90 degrees is straight up
else if (end.Y > start.Y)
radians = Math.PI / 2.0; // 90 degrees is straight down
}
if (positiveOnly && radians < 0.0)
{
radians += Math.PI * 2.0;
}
return radians;
}
public static double Rad2Deg(double rad)
{
return (rad * 180d / Math.PI);
}
public static double Deg2Rad(double deg)
{
return (deg * Math.PI / 180d);
}
// rotate the points by the given degrees about their centroid
public static ArrayList RotateByDegrees(ArrayList points, double degrees)
{
double radians = Deg2Rad(degrees);
return RotateByRadians(points, radians);
}
// rotate the points by the given radians about their centroid
public static ArrayList RotateByRadians(ArrayList points, double radians)
{
ArrayList newPoints = new ArrayList(points.Count);
PointR c = Centroid(points);
double cos = Math.Cos(radians);
double sin = Math.Sin(radians);
double cx = c.X;
double cy = c.Y;
for (int i = 0; i < points.Count; i++)
{
PointR p = (PointR) points[i];
double dx = p.X - cx;
double dy = p.Y - cy;
PointR q = PointR.Empty;
q.X = dx * cos - dy * sin + cx;
q.Y = dx * sin + dy * cos + cy;
newPoints.Add(q);
}
return newPoints;
}
// Rotate a point 'p' around a point 'c' by the given radians.
// Rotation (around the origin) amounts to a 2x2 matrix of the form:
//
// [ cos A -sin A ] [ p.x ]
// [ sin A cos A ] [ p.y ]
//
// Note that the C# Math coordinate system has +x-axis stright right and
// +y-axis straight down. Rotation is clockwise such that from +x-axis to
// +y-axis is +90 degrees, from +x-axis to -x-axis is +180 degrees, and
// from +x-axis to -y-axis is -90 degrees.
public static PointR RotatePoint(PointR p, PointR c, double radians)
{
PointR q = PointR.Empty;
q.X = (p.X - c.X) * Math.Cos(radians) - (p.Y - c.Y) * Math.Sin(radians) + c.X;
q.Y = (p.X - c.X) * Math.Sin(radians) + (p.Y - c.Y) * Math.Cos(radians) + c.Y;
return q;
}
#endregion
#region Translations
// translates the points so that the upper-left corner of their bounding box lies at 'toPt'
public static ArrayList TranslateBBoxTo(ArrayList points, PointR toPt)
{
ArrayList newPoints = new ArrayList(points.Count);
RectangleR r = Utils.FindBox(points);
for (int i = 0; i < points.Count; i++)
{
PointR p = (PointR) points[i];
p.X += (toPt.X - r.X);
p.Y += (toPt.Y - r.Y);
newPoints.Add(p);
}
return newPoints;
}
// translates the points so that their centroid lies at 'toPt'
public static ArrayList TranslateCentroidTo(ArrayList points, PointR toPt)
{
ArrayList newPoints = new ArrayList(points.Count);
PointR centroid = Centroid(points);
for (int i = 0; i < points.Count; i++)
{
PointR p = (PointR) points[i];
p.X += (toPt.X - centroid.X);
p.Y += (toPt.Y - centroid.Y);
newPoints.Add(p);
}
return newPoints;
}
// translates the points by the given delta amounts
public static ArrayList TranslateBy(ArrayList points, SizeR sz)
{
ArrayList newPoints = new ArrayList(points.Count);
for (int i = 0; i < points.Count; i++)
{
PointR p = (PointR) points[i];
p.X += sz.Width;
p.Y += sz.Height;
newPoints.Add(p);
}
return newPoints;
}
#endregion
#region Scaling
// scales the points so that they form the size given. does not restore the
// origin of the box.
public static ArrayList ScaleTo(ArrayList points, SizeR sz)
{
ArrayList newPoints = new ArrayList(points.Count);
RectangleR r = FindBox(points);
for (int i = 0; i < points.Count; i++)
{
PointR p = (PointR) points[i];
if (r.Width != 0d)
p.X *= (sz.Width / r.Width);
if (r.Height != 0d)
p.Y *= (sz.Height / r.Height);
newPoints.Add(p);
}
return newPoints;
}
// scales by the percentages contained in the 'sz' parameter. values of 1.0 would result in the
// identity scale (that is, no change).
public static ArrayList ScaleBy(ArrayList points, SizeR sz)
{
ArrayList newPoints = new ArrayList(points.Count);
RectangleR r = FindBox(points);
for (int i = 0; i < points.Count; i++)
{
PointR p = (PointR) points[i];
p.X *= sz.Width;
p.Y *= sz.Height;
newPoints.Add(p);
}
return newPoints;
}
// scales the points so that the length of their longer side
// matches the length of the longer side of the given box.
// thus, both dimensions are warped proportionally, rather than
// independently, like in the function ScaleTo.
public static ArrayList ScaleToMax(ArrayList points, RectangleR box)
{
ArrayList newPoints = new ArrayList(points.Count);
RectangleR r = FindBox(points);
for (int i = 0; i < points.Count; i++)
{
PointR p = (PointR) points[i];
p.X *= (box.MaxSide / r.MaxSide);
p.Y *= (box.MaxSide / r.MaxSide);
newPoints.Add(p);
}
return newPoints;
}
// scales the points so that the length of their shorter side
// matches the length of the shorter side of the given box.
// thus, both dimensions are warped proportionally, rather than
// independently, like in the function ScaleTo.
public static ArrayList ScaleToMin(ArrayList points, RectangleR box)
{
ArrayList newPoints = new ArrayList(points.Count);
RectangleR r = FindBox(points);
for (int i = 0; i < points.Count; i++)
{
PointR p = (PointR) points[i];
p.X *= (box.MinSide / r.MinSide);
p.Y *= (box.MinSide / r.MinSide);
newPoints.Add(p);
}
return newPoints;
}
#endregion
#region Random Numbers
/// <summary>
/// Gets a random number between low and high, inclusive.
/// </summary>
/// <param name="low"></param>
/// <param name="high"></param>
/// <returns></returns>
public static int Random(int low, int high)
{
return _rand.Next(low, high + 1);
}
/// <summary>
/// Gets multiple random numbers between low and high, inclusive. The
/// numbers are guaranteed to be distinct.
/// </summary>
/// <param name="low"></param>
/// <param name="high"></param>
/// <param name="num"></param>
/// <returns></returns>
public static int[] Random(int low, int high, int num)
{
int[] array = new int[num];
for (int i = 0; i < num; i++)
{
array[i] = _rand.Next(low, high + 1);
for (int j = 0; j < i; j++)
{
if (array[i] == array[j])
{
i--; // redo i
break;
}
}
}
return array;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using GraphQL.Execution;
using Shouldly;
using Xunit;
namespace GraphQL.Tests.Errors
{
public class ErrorInfoProviderTests
{
[Fact]
public void null_executionError_throws()
{
var provider = new ErrorInfoProvider();
Should.Throw<ArgumentNullException>(() => provider.GetInfo(null));
}
[Fact]
public void simple_message()
{
var error = new ExecutionError("test message");
var info = new ErrorInfoProvider().GetInfo(error);
info.Message.ShouldBe("test message");
info.Extensions.ShouldBeNull();
}
[Fact]
public void null_message_ok()
{
var error = new ExecutionError(null); // create executionerror with a default message
error.Message.ShouldNotBeNull();
var info = new ErrorInfoProvider().GetInfo(error);
info.Message.ShouldBe(error.Message);
}
[Fact]
public void message_and_data()
{
var data = new Dictionary<string, object>()
{
{ "test1", "object1" },
{ "test2", 15 },
{ "test3", new Dictionary<string, object>() { { "test4", "object4" } } },
};
var error = new ExecutionError(null, data);
error.Data.ShouldNotBeNull();
error.Data.Count.ShouldBe(3);
error.Data["test1"].ShouldBe("object1");
error.Data["test2"].ShouldBe(15);
error.Data["test3"].ShouldBe(new Dictionary<string, object>() { { "test4", "object4" } });
var info = new ErrorInfoProvider().GetInfo(error);
info.Message.ShouldBe(error.Message);
info.Extensions.ShouldNotBeNull();
info.Extensions.Count.ShouldBe(1);
info.Extensions.ShouldContainKey("data");
info.Extensions["data"].ShouldBeAssignableTo<IDictionary>().ShouldBe(error.Data);
}
[Fact]
public void message_and_code()
{
var error = new ExecutionError(null) { Code = "test code" };
var info = new ErrorInfoProvider().GetInfo(error);
info.Message.ShouldBe(error.Message);
info.Extensions.ShouldNotBeNull();
info.Extensions.Count.ShouldBe(2);
info.Extensions.ShouldContainKeyAndValue("code", "test code");
info.Extensions.ShouldContainKey("codes");
info.Extensions["codes"].ShouldBeAssignableTo<IEnumerable<string>>().ShouldBe(new[] { "test code" });
}
[Fact]
public void message_and_inner_exception()
{
var innerException = new ArgumentNullException(null, new ArgumentOutOfRangeException());
var error = new ExecutionError(innerException.Message, innerException);
error.Code.ShouldBe(ErrorInfoProvider.GetErrorCode<ArgumentNullException>());
error.Code.ShouldNotBeNull();
var info = new ErrorInfoProvider().GetInfo(error);
info.Message.ShouldBe(error.Message);
info.Extensions.ShouldNotBeNull();
info.Extensions.Count.ShouldBe(2);
info.Extensions.ShouldContainKeyAndValue("code", error.Code);
info.Extensions.ShouldContainKey("codes");
info.Extensions["codes"].ShouldBeAssignableTo<IEnumerable<string>>().ShouldBe(
new[] { ErrorInfoProvider.GetErrorCode<ArgumentNullException>(), ErrorInfoProvider.GetErrorCode<ArgumentOutOfRangeException>() });
}
[Fact]
public void drops_extensions_when_no_data()
{
var error = new ExecutionError(null);
error.Code.ShouldBeNull();
error.Data.ShouldNotBeNull();
error.Data.Count.ShouldBe(0);
var info = new ErrorInfoProvider().GetInfo(error);
info.Extensions.ShouldBeNull();
}
[Fact]
public void multiple_innerExceptions()
{
var error = new ExecutionError("Test error message", new ArgumentNullException(null, new ArgumentOutOfRangeException()));
error.Data.Add("test1", "object1");
error.Data.Add("test2", 15);
error.Data.Add("test3", new Dictionary<string, object>() { { "test4", "object4" } });
error.AddLocation(5, 6);
error.AddLocation(7, 8);
var info = new ErrorInfoProvider().GetInfo(error);
info.Message.ShouldBe(error.Message);
info.Extensions.ShouldNotBeNull();
info.Extensions.Count.ShouldBe(3);
info.Extensions.ShouldContainKeyAndValue("code", error.Code);
info.Extensions.ShouldContainKey("codes");
info.Extensions["codes"].ShouldBeAssignableTo<IEnumerable<string>>().ShouldBe(
new[] { ErrorInfoProvider.GetErrorCode<ArgumentNullException>(), ErrorInfoProvider.GetErrorCode<ArgumentOutOfRangeException>() });
info.Extensions.ShouldContainKey("data");
info.Extensions["data"].ShouldBeAssignableTo<IDictionary>().ShouldBe(error.Data);
}
[Fact]
public void exposeExceptions()
{
var innerException = new ArgumentNullException(null, new ArgumentOutOfRangeException());
var error = new ExecutionError(innerException.Message, innerException);
var info = new ErrorInfoProvider(new ErrorInfoProviderOptions { ExposeExceptionStackTrace = true }).GetInfo(error);
info.Message.ShouldBe(error.ToString());
}
[Fact]
public void exposeExceptions_with_real_stack_trace()
{
// generate a real stack trace to serialize
ExecutionError error;
try
{
try
{
throw new ArgumentNullException(null, new ArgumentOutOfRangeException());
}
catch (Exception innerException)
{
throw new ExecutionError(innerException.Message, innerException);
}
}
catch (ExecutionError e)
{
error = e;
}
var info = new ErrorInfoProvider(new ErrorInfoProviderOptions { ExposeExceptionStackTrace = true }).GetInfo(error);
info.Message.ShouldBe(error.ToString());
}
[Fact]
public void blank_codes_do_serialize()
{
var error = new ExecutionError(null)
{
Code = "",
};
error.Code.ShouldBe("");
var info = new ErrorInfoProvider(new ErrorInfoProviderOptions { ExposeExceptionStackTrace = true }).GetInfo(error);
info.Extensions.ShouldNotBeNull();
info.Extensions.ShouldContainKey("code");
info.Extensions["code"].ShouldBe("");
info.Extensions.ShouldContainKey("codes");
info.Extensions["codes"].ShouldBeAssignableTo<IEnumerable<object>>().ShouldBe(new object[] { "" });
}
[Fact]
public void inner_exception_of_type_exception_does_serialize_extensions()
{
var error = new ExecutionError("Test execution error", new Exception("Test exception"));
error.Code.ShouldBe(ErrorInfoProvider.GetErrorCode<Exception>());
var info = new ErrorInfoProvider().GetInfo(error);
info.Extensions.ShouldNotBeNull();
info.Extensions.ShouldContainKey("code");
info.Extensions["code"].ShouldBe(ErrorInfoProvider.GetErrorCode<Exception>());
info.Extensions.ShouldContainKey("codes");
info.Extensions["codes"].ShouldBeAssignableTo<IEnumerable<object>>().ShouldBe(new[] { ErrorInfoProvider.GetErrorCode<Exception>() });
}
[Fact]
public void codes_with_blank_code_always_serialize()
{
var error = new ExecutionError(null, new Exception(null, new ArgumentNullException("param")));
error.Code.ShouldBe(ErrorInfoProvider.GetErrorCode<Exception>());
var info = new ErrorInfoProvider().GetInfo(error);
info.Extensions.ShouldNotBeNull();
info.Extensions.ShouldContainKey("code");
info.Extensions["code"].ShouldBe(ErrorInfoProvider.GetErrorCode<Exception>());
info.Extensions.ShouldContainKey("codes");
info.Extensions["codes"].ShouldBeAssignableTo<IEnumerable<object>>().ShouldBe(
new[] { ErrorInfoProvider.GetErrorCode<Exception>(), ErrorInfoProvider.GetErrorCode<ArgumentNullException>() });
error.Data.Add("test1", "object1");
info = new ErrorInfoProvider().GetInfo(error);
info.Extensions.ShouldNotBeNull();
info.Extensions.ShouldContainKey("code");
info.Extensions["code"].ShouldBe("");
info.Extensions.ShouldContainKey("data");
info.Extensions.ShouldContainKey("codes");
info.Extensions["codes"].ShouldBeAssignableTo<IEnumerable<object>>().ShouldBe(
new[] { ErrorInfoProvider.GetErrorCode<Exception>(), ErrorInfoProvider.GetErrorCode<ArgumentNullException>() });
}
[Fact]
public void verify_exposeextensions_functionality_code()
{
var error = new ExecutionError("test")
{
Code = "test code"
};
var info = new ErrorInfoProvider(opts => opts.ExposeExtensions = false).GetInfo(error);
info.Extensions.ShouldBeNull();
}
[Fact]
public void verify_exposeextensions_functionality_codes()
{
var error = new ExecutionError("test", new ArgumentNullException())
{
Code = null
};
var info = new ErrorInfoProvider(opts => opts.ExposeExtensions = false).GetInfo(error);
info.Extensions.ShouldBeNull();
}
[Fact]
public void verify_exposeextensions_functionality_data()
{
var error = new ExecutionError("test");
error.Data["test"] = "abc";
var info = new ErrorInfoProvider(opts => opts.ExposeExtensions = false).GetInfo(error);
info.Extensions.ShouldBeNull();
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, false, true)]
[InlineData(false, true, false)]
[InlineData(false, true, true)]
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
[InlineData(true, true, true)]
public void verify_exposeextensions_functionality_ignore_other_properties(bool exposeCode, bool exposeCodes, bool exposeData)
{
var error = new ExecutionError("test", new ArgumentNullException())
{
Code = "code"
};
error.Data["test"] = "abc";
var info = new ErrorInfoProvider(opts =>
{
opts.ExposeExtensions = false;
opts.ExposeCode = exposeCode;
opts.ExposeCodes = exposeCodes;
opts.ExposeData = exposeData;
}).GetInfo(error);
info.Extensions.ShouldBeNull();
}
[Fact]
public void verify_exposecode_functionality()
{
var error = new ExecutionError("message")
{
Code = "code"
};
var info = new ErrorInfoProvider(opts => opts.ExposeCode = false).GetInfo(error);
info.Extensions.ShouldNotBeNull();
info.Extensions.ShouldNotContainKey("code");
info.Extensions.ShouldContainKey("codes");
info.Extensions["codes"].ShouldBeAssignableTo<IEnumerable<object>>().ShouldBe(new[] { "code" });
}
[Fact]
public void verify_exposecodes_functionality_no_other_data()
{
var error = new ExecutionError("message", new ArgumentNullException())
{
Code = null
};
var info = new ErrorInfoProvider(opts => opts.ExposeCodes = false).GetInfo(error);
info.Extensions.ShouldBeNull();
}
[Fact]
public void verify_exposecodes_functionality_with_other_data()
{
var error = new ExecutionError("message", new ArgumentNullException())
{
Code = "code"
};
var info = new ErrorInfoProvider(opts => opts.ExposeCodes = false).GetInfo(error);
info.Extensions.ShouldNotBeNull();
info.Extensions.ShouldContainKey("code");
info.Extensions.ShouldNotContainKey("codes");
}
[Fact]
public void verify_exposedata_functionality_no_other_data()
{
var error = new ExecutionError("message");
error.Data["test"] = "abc";
var info = new ErrorInfoProvider(opts => opts.ExposeData = false).GetInfo(error);
info.Extensions.ShouldBeNull();
}
[Fact]
public void verify_exposedata_functionality_with_other_data()
{
var error = new ExecutionError("message")
{
Code = "code"
};
error.Data["test"] = "abc";
var info = new ErrorInfoProvider(opts => opts.ExposeData = false).GetInfo(error);
info.Extensions.ShouldNotBeNull();
info.Extensions.ShouldContainKey("code");
info.Extensions.ShouldNotContainKey("data");
}
[Theory]
[InlineData(typeof(Exception), "")]
[InlineData(typeof(ArgumentException), "ARGUMENT")]
[InlineData(typeof(ArgumentNullException), "ARGUMENT_NULL")]
[InlineData(typeof(GraphQLParser.Exceptions.GraphQLSyntaxErrorException), "SYNTAX_ERROR")]
[InlineData(typeof(GraphQLException), "")]
[InlineData(typeof(GraphQlException), "GRAPH_QL")]
[InlineData(typeof(ExecutionError), "EXECUTION_ERROR")]
[InlineData(typeof(GraphQL.Validation.ValidationError), "VALIDATION_ERROR")]
public void geterrorcode_tests(Type type, string code)
{
ErrorInfoProvider.GetErrorCode(type).ShouldBe(code);
}
[Fact]
public void geterrorcode_null_throws()
{
Assert.Throws<ArgumentNullException>(() => ErrorInfoProvider.GetErrorCode((Type)null));
}
[Fact]
public void geterrorcode_instance_works()
{
ErrorInfoProvider.GetErrorCode(new ArgumentNullException()).ShouldBe("ARGUMENT_NULL");
}
[Fact]
public void geterrorcode_generic_works()
{
ErrorInfoProvider.GetErrorCode<ArgumentNullException>().ShouldBe("ARGUMENT_NULL");
}
private class GraphQLException : Exception { }
private class GraphQlException : Exception { }
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
namespace _4PosBackOffice.NET
{
internal partial class frmSupplierList : System.Windows.Forms.Form
{
string gFilter;
ADODB.Recordset gRS;
string gFilterSQL;
short gSection;
bool gAll;
private void loadLanguage()
{
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1433;
//Select a Supplier|Checked
if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1080;
//Search|Checked
if (modRecordSet.rsLang.RecordCount){lbl.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lbl.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1065;
//New|Checked
if (modRecordSet.rsLang.RecordCount){cmdNew.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdNew.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmSupplierList.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void getNamespace()
{
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
private void cmdNamespace_Click()
{
My.MyProject.Forms.frmFilter.loadFilter(ref gFilter);
getNamespace();
}
private void cmdNew_Click(System.Object eventSender, System.EventArgs eventArgs)
{
My.MyProject.Forms.frmSupplier.loadItem(ref 0);
doSearch();
}
private void DataList1_DblClick(System.Object eventSender, KeyEventArgs eventArgs)
{
if (!string.IsNullOrEmpty(DataList1.BoundText)) {
switch (gSection) {
case 0:
My.MyProject.Forms.frmSupplier.loadItem(ref Convert.ToInt32(DataList1.BoundText));
break;
case 1:
My.MyProject.Forms.frmSupplierTransaction.loadItem(ref Convert.ToInt32(DataList1.BoundText), ref 0);
break;
case 2:
My.MyProject.Forms.frmSupplierTransaction.loadItem(ref Convert.ToInt32(DataList1.BoundText), ref 1);
break;
case 3:
My.MyProject.Forms.frmSupplierTransaction.loadItem(ref Convert.ToInt32(DataList1.BoundText), ref 2);
break;
case 4:
My.MyProject.Forms.frmSupplierDeposits.loadItem(ref Convert.ToInt32(DataList1.BoundText));
break;
}
}
doSearch();
}
private void DataList1_KeyPress(System.Object eventSender, KeyPressEventArgs eventArgs)
{
switch (eventArgs.KeyChar) {
case Strings.ChrW(13):
DataList1_DblClick(DataList1, new System.EventArgs());
eventArgs.KeyChar = Strings.ChrW(0);
break;
case Strings.ChrW(27):
this.Close();
eventArgs.KeyChar = Strings.ChrW(0);
break;
}
}
public void loadItem(ref short section)
{
gSection = section;
if (gSection)
cmdNew.Visible = false;
doSearch();
loadLanguage();
ShowDialog();
}
private void frmSupplierList_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs)
{
short KeyCode = eventArgs.KeyCode;
short Shift = eventArgs.KeyData / 0x10000;
if (KeyCode == 36) {
gAll = !gAll;
doSearch();
KeyCode = false;
}
}
private void frmSupplierList_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
gRS.Close();
}
private void frmSupplierList_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 27) {
KeyAscii = 0;
cmdExit_Click(cmdExit, new System.EventArgs());
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtSearch_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtSearch.SelectionStart = 0;
txtSearch.SelectionLength = 999;
}
private void txtSearch_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs)
{
short KeyCode = eventArgs.KeyCode;
short Shift = eventArgs.KeyData / 0x10000;
switch (KeyCode) {
case 40:
this.DataList1.Focus();
break;
}
}
private void txtSearch_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case 13:
doSearch();
KeyAscii = 0;
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void doSearch()
{
string sql = null;
string lString = null;
lString = Strings.Trim(txtSearch.Text);
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, "'", "");
if (string.IsNullOrEmpty(lString)) {
} else {
lString = "WHERE (Supplier_Name LIKE '%" + Strings.Replace(lString, " ", "%' AND Supplier_Name LIKE '%") + "%')";
}
if (gAll) {
} else {
if (string.IsNullOrEmpty(lString)) {
lString = " WHERE Supplier_Disabled = 0";
} else {
lString = lString + " AND Supplier_Disabled = 0";
}
}
gRS = modRecordSet.getRS(ref "SELECT DISTINCT SupplierID, Supplier_Name FROM Supplier " + lString + " ORDER BY Supplier_Name");
//Display the list of Titles in the DataCombo
DataList1.DataSource = gRS;
DataList1.listField = "Supplier_Name";
//Bind the DataCombo to the ADO Recordset
//UPGRADE_ISSUE: VBControlExtender property DataList1.DataSource is not supported at runtime. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="74E732F3-CAD8-417B-8BC9-C205714BB4A7"'
DataList1.DataSource = gRS;
DataList1.boundColumn = "SupplierID";
}
}
}
| |
//------------------------------------------------------------------------------
/// <copyright from='2004' to='2005' company='Microsoft Corporation'>
/// Copyright (c) Microsoft Corporation. All Rights Reserved.
/// Information Contained Herein is Proprietary and Confidential.
/// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics.CodeAnalysis;
namespace System.AddIn.Contract
{
/// <summary>
/// Empty == System.Reflection.Missing
/// Intrinsic == All Primitive types, System.String
/// </summary>
public enum RemoteArgumentKind
{
Missing,
Intrinsic,
IntrinsicArray,
Contract
}
/// <summary>
/// Similar to the COM Variant type, this class can be used to safely
/// pass Contract compliant types through the IRemoteTypeContract
/// RemoteArgument passes, by value, the "Convertible" types.
/// These are: int, uint, long, ulong, short, ushort, sbyte, byte, char
/// decimal, float, double, bool, DateTime, DBNull, Empty and String
/// </summary>
[Serializable]
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
public struct RemoteArgument
{
#region Private Fields
//this ("value") clearly breaks the rule of "tranistive closure" by
//having a field typed as System.Object. We re-enforce the rule
//by ensuring the only things that can be assigned here are either
//intrinsic types or IContracts, and *never* exposing the object.
//This should be the *ONLY* exception, ever, and allows the rule
//to be enforced everywhere else
private object _value;
//byref is changeable, can be set and unset....
private bool isByRef;
//the following two fields are "readonly" because once they
//are set they are not allowed to change.
private readonly RemoteArgumentKind remoteArgKind;
private readonly TypeCode intrinsicTypeCode;
#endregion
#region Static Creation Methods
/// <summary>
/// With all the various intrinsic types, in order to avoid each consumer
/// of this method having to write the large switch statement to decide which constructor
/// to call, we wrote it for you in this helper method. All primitive types
/// implement IConvertible, as do enum types, which fit into integral primitives
/// String *is* included here though it is not strictly a primitive type.
/// Anything with its own type code is included. Anything with TypeCode.Object throws
/// </summary>
/// <param name="intrinsicValue"></param>
/// <returns></returns>
public static RemoteArgument CreateRemoteArgument(object value)
{
return CreateRemoteArgument(value, false);
}
/// <summary>
/// This overload allows the caller to create a byref remote argument
/// </summary>
/// <param name="intrinsicValue"></param>
/// <param name="isByRef"></param>
/// <returns></returns>
public static RemoteArgument CreateRemoteArgument(object value, bool isByRef)
{
if (value == null)
throw new ArgumentNullException("value");
System.Array arrayValue = value as System.Array;
TypeCode typeCode;
if (arrayValue != null)
{
typeCode = Type.GetTypeCode(arrayValue.GetType().GetElementType());
}
else
{
typeCode = Type.GetTypeCode(value.GetType());
}
//else its System.Reflection.Missing, so leave as TypeCode.Empty
return CreateRemoteArgument(value, isByRef, typeCode);
}
/// <summary>
/// This overload allows the caller to convert between intrinsic types. The returned
/// remote argument will contain the type code specified or this will throw.
/// </summary>
/// <param name="intrinsicValue"></param>
/// <param name="isByRef"></param>
/// <param name="typeCodeToUse"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public static RemoteArgument CreateRemoteArgument(object value, bool isByRef, TypeCode typeCodeToUse)
{
IConvertible convertibleValue = value as IConvertible;
IContract contractValue = value as IContract;
System.Array arrayValue = value as System.Array;
if ((typeCodeToUse == TypeCode.Object) && (contractValue == null) && (value != null))
{
// If the TypeCode is object, we better have a Contract unless the value itself
// was null to begin with. In this case, we just want a RemoteArgument for a
// null contract.
throw new ArgumentException(null, "value");
}
else if ((typeCodeToUse == TypeCode.Empty) && (value != System.Reflection.Missing.Value))
{
// If the TypeCode is Empty the only valid value is Missing.Value.
throw new ArgumentException(null, "value");
}
else if ((convertibleValue == null) && (value != null) && (arrayValue == null) && (typeCodeToUse != TypeCode.Object) && (typeCodeToUse != TypeCode.Empty))
{
// All the rest of the TypeCodes are for Convertible values, so we better
// have one unless of course the value itself was null (i.e. a null string).
// In this case, null is completely valid and we should create a null
// string RemoteArgument.
throw new ArgumentException(null, "value");
}
if (arrayValue != null)
{
TypeCode arrayTypeCode = Type.GetTypeCode(arrayValue.GetType().GetElementType());
if ((arrayTypeCode == TypeCode.Object) || (arrayTypeCode != typeCodeToUse))
throw new ArgumentException(null, "value");
return new RemoteArgument(arrayValue, isByRef);
}
bool needsConversion = false;
if (convertibleValue != null)
needsConversion = (convertibleValue.GetTypeCode() != typeCodeToUse);
//all of this seemingly duplicated code
//is necessary to unbox the value and call the
//correct constructor on RemoteArgument
switch (typeCodeToUse)
{
case TypeCode.Boolean:
{
bool boolToUse;
if (needsConversion)
boolToUse = convertibleValue.ToBoolean(null);
else
boolToUse = (bool)convertibleValue;
return new RemoteArgument(boolToUse, isByRef);
}
case TypeCode.Byte:
{
byte byteToUse;
if (needsConversion)
byteToUse = convertibleValue.ToByte(null);
else
byteToUse = (byte)convertibleValue;
return new RemoteArgument(byteToUse, isByRef);
}
case TypeCode.Char:
{
char charToUse;
if (needsConversion)
charToUse = convertibleValue.ToChar(null);
else
charToUse = (char)convertibleValue;
return new RemoteArgument(charToUse, isByRef);
}
case TypeCode.DateTime:
{
DateTime dateTimeToUse;
if (needsConversion)
dateTimeToUse = convertibleValue.ToDateTime(null);
else
dateTimeToUse = (DateTime)convertibleValue;
return new RemoteArgument(dateTimeToUse, isByRef);
}
case TypeCode.DBNull:
{
//there is no conversion to DBNull
//its either DBNull or not, so
//throw if needs conversion is true
if (needsConversion)
throw new NotSupportedException();
return new RemoteArgument((DBNull)convertibleValue);
}
case TypeCode.Decimal:
{
decimal decimalToUse;
if (needsConversion)
decimalToUse = convertibleValue.ToDecimal(null);
else
decimalToUse = (decimal)convertibleValue;
return new RemoteArgument(decimalToUse, isByRef);
}
case TypeCode.Double:
{
double doubleToUse;
if (needsConversion)
doubleToUse = convertibleValue.ToDouble(null);
else
doubleToUse = (double)convertibleValue;
return new RemoteArgument(doubleToUse, isByRef);
}
case TypeCode.Int16:
{
short shortToUse;
if (needsConversion)
shortToUse = convertibleValue.ToInt16(null);
else
shortToUse = (short)convertibleValue;
return new RemoteArgument(shortToUse, isByRef);
}
case TypeCode.Int32:
{
int intToUse;
if (needsConversion)
intToUse = convertibleValue.ToInt32(null);
else
intToUse = (int)convertibleValue;
return new RemoteArgument(intToUse, isByRef);
}
case TypeCode.Int64:
{
long longToUse;
if (needsConversion)
longToUse = convertibleValue.ToInt64(null);
else
longToUse = (long)convertibleValue;
return new RemoteArgument(longToUse, isByRef);
}
case TypeCode.SByte:
{
sbyte sbyteToUse;
if (needsConversion)
sbyteToUse = convertibleValue.ToSByte(null);
else
sbyteToUse = (sbyte)convertibleValue;
return new RemoteArgument(sbyteToUse, isByRef);
}
case TypeCode.Single:
{
float floatToUse;
if (needsConversion)
floatToUse = convertibleValue.ToSingle(null);
else
floatToUse = (float)convertibleValue;
return new RemoteArgument(floatToUse, isByRef);
}
case TypeCode.String:
{
string stringToUse;
if (needsConversion)
stringToUse = convertibleValue.ToString(null);
else
stringToUse = (string)convertibleValue;
return new RemoteArgument(stringToUse, isByRef);
}
case TypeCode.UInt16:
{
ushort ushortToUse;
if (needsConversion)
ushortToUse = convertibleValue.ToUInt16(null);
else
ushortToUse = (ushort)convertibleValue;
return new RemoteArgument(ushortToUse, isByRef);
}
case TypeCode.UInt32:
{
uint uintToUse;
if (needsConversion)
uintToUse = convertibleValue.ToUInt32(null);
else
uintToUse = (uint)convertibleValue;
return new RemoteArgument(uintToUse, isByRef);
}
case TypeCode.UInt64:
{
ulong ulongToUse;
if (needsConversion)
ulongToUse = convertibleValue.ToUInt64(null);
else
ulongToUse = (ulong)convertibleValue;
return new RemoteArgument(ulongToUse, isByRef);
}
case TypeCode.Empty:
{
// Just Missing.Value
return new RemoteArgument(RemoteArgumentKind.Missing, TypeCode.Empty, isByRef);
}
case TypeCode.Object:
{
return new RemoteArgument(contractValue, isByRef);
}
default:
throw new InvalidOperationException();
}
}
#endregion
#region Initializers
//the "default constructor" of RemoteArgument is
//built-in because this is a struct.
//it creates the "Null" RemoteArgument:
//value = null;
//remoteArgKing = RemoteArgumentKind.Missing
//intrinsicTypeCode = TypeCode.Empty
#region Contract
//Creates the Contract RemoteArgument
public RemoteArgument(IContract value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Contract;
this.intrinsicTypeCode = TypeCode.Object;
this.isByRef = false;
}
public RemoteArgument(IContract value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Contract;
this.intrinsicTypeCode = TypeCode.Object;
this.isByRef = isByRef;
}
#endregion
#region Special case for null/"out" params and/or default value intrinsics
//isByRef == true means "out". Must be true if Kind == Contract
public RemoteArgument(RemoteArgumentKind remoteArgKind, TypeCode typeCode) : this(remoteArgKind, typeCode, false)
{
}
public RemoteArgument(RemoteArgumentKind remoteArgKind, TypeCode typeCode, bool isByRef)
{
this._value = null;
this.isByRef = isByRef;
this.remoteArgKind = remoteArgKind;
switch (remoteArgKind)
{
case RemoteArgumentKind.Missing:
if (typeCode != TypeCode.Empty)
throw new ArgumentException(null, "typeCode");
this.intrinsicTypeCode = typeCode;
break;
case RemoteArgumentKind.Intrinsic:
case RemoteArgumentKind.IntrinsicArray:
if (typeCode == TypeCode.Object ||
typeCode == TypeCode.Empty)
throw new ArgumentException(null, "typeCode");
this.intrinsicTypeCode = typeCode;
break;
case RemoteArgumentKind.Contract:
if (typeCode != TypeCode.Object)
throw new ArgumentException(null, "typeCode");
this.intrinsicTypeCode = typeCode;
break;
default:
throw new InvalidOperationException();
}
}
#endregion
#region Primitive Types -- CLS Compliant
//two for each of the primitive types
//value, by ref
#region System.Boolean
public RemoteArgument(System.Boolean value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Boolean;
this.isByRef = false;
}
public RemoteArgument(System.Boolean value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Boolean;
this.isByRef = isByRef;
}
#endregion
#region System.Byte
public RemoteArgument(System.Byte value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Byte;
this.isByRef = false;
}
public RemoteArgument(System.Byte value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Byte;
this.isByRef = isByRef;
}
#endregion
#region System.Char
public RemoteArgument(System.Char value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Char;
this.isByRef = false;
}
public RemoteArgument(System.Char value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Char;
this.isByRef = isByRef;
}
#endregion
#region System.DateTime
public RemoteArgument(System.DateTime value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.DateTime;
this.isByRef = false;
}
public RemoteArgument(System.DateTime value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.DateTime;
this.isByRef = isByRef;
}
#endregion
#region System.DBNull
public RemoteArgument(System.DBNull value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.DBNull;
this.isByRef = false;
}
public RemoteArgument(System.DBNull value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.DBNull;
this.isByRef = isByRef;
}
#endregion
#region System.Decimal
public RemoteArgument(System.Decimal value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Decimal;
this.isByRef = false;
}
public RemoteArgument(System.Decimal value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Decimal;
this.isByRef = isByRef;
}
#endregion
#region System.Double
public RemoteArgument(System.Double value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Double;
this.isByRef = false;
}
public RemoteArgument(System.Double value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Double;
this.isByRef = isByRef;
}
#endregion
#region System.Int16
public RemoteArgument(System.Int16 value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Int16;
this.isByRef = false;
}
public RemoteArgument(System.Int16 value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Int16;
this.isByRef = isByRef;
}
#endregion
#region System.Int32
public RemoteArgument(System.Int32 value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Int32;
this.isByRef = false;
}
public RemoteArgument(System.Int32 value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Int32;
this.isByRef = isByRef;
}
#endregion
#region System.Int64
public RemoteArgument(System.Int64 value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Int64;
this.isByRef = false;
}
public RemoteArgument(System.Int64 value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Int64;
this.isByRef = isByRef;
}
#endregion
#region System.Single
public RemoteArgument(System.Single value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Single;
this.isByRef = false;
}
public RemoteArgument(System.Single value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.Single;
this.isByRef = isByRef;
}
#endregion
#region System.String
public RemoteArgument(System.String value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.String;
this.isByRef = false;
}
public RemoteArgument(System.String value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.String;
this.isByRef = isByRef;
}
#endregion
#endregion
#region Intrinsic Types Non-CLS Compliant
#region System.SByte
[CLSCompliant(false)]
public RemoteArgument(System.SByte value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.SByte;
this.isByRef = false;
}
[CLSCompliant(false)]
public RemoteArgument(System.SByte value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.SByte;
this.isByRef = isByRef;
}
#endregion
#region System.UInt16
[CLSCompliant(false)]
public RemoteArgument(System.UInt16 value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.UInt16;
this.isByRef = false;
}
[CLSCompliant(false)]
public RemoteArgument(System.UInt16 value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.UInt16;
this.isByRef = isByRef;
}
#endregion
#region System.UInt32
[CLSCompliant(false)]
public RemoteArgument(System.UInt32 value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.UInt32;
this.isByRef = false;
}
[CLSCompliant(false)]
public RemoteArgument(System.UInt32 value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.UInt32;
this.isByRef = isByRef;
}
#endregion
#region System.UInt64
[CLSCompliant(false)]
public RemoteArgument(System.UInt64 value)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.UInt64;
this.isByRef = false;
}
[CLSCompliant(false)]
public RemoteArgument(System.UInt64 value, bool isByRef)
{
this._value = value;
this.remoteArgKind = RemoteArgumentKind.Intrinsic;
this.intrinsicTypeCode = TypeCode.UInt64;
this.isByRef = isByRef;
}
#endregion
#endregion
#region IntrinsicArray
//we could have overloads for each of the primitive
//type arrays, but arrays can be multidimensional
//so we'd need this as a catchall anyway.
//So this throws if the array element type isn't intrinsic
//NOTE we don't support System.Reflection.Missing[]
//makes no sense....
public RemoteArgument(System.Array array)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
//this handles multi-dimensional intrinsic arrays, too.
//Jagged arrays are handled recursively as arrays of arrays
//we can't just ask the type if it IsPrimitive because string says "false"
if (Type.GetTypeCode(array.GetType().GetElementType()) == TypeCode.Object)
{
throw new ArgumentException(null, "array");
}
this._value = array;
this.remoteArgKind = RemoteArgumentKind.IntrinsicArray;
//for IntrinsicArray this holds the element type code
this.intrinsicTypeCode = Type.GetTypeCode(array.GetType().GetElementType());
this.isByRef = false;
}
public RemoteArgument(System.Array array, bool isByRef)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
//this handles multi-dimensional intrinsic arrays, too.
//Jagged arrays are handled recursively as arrays of arrays
//we can't just ask the type if it IsPrimitive because string says "false"
if (Type.GetTypeCode(array.GetType().GetElementType()) == TypeCode.Object)
{
throw new ArgumentException(null, "array");
}
this._value = array;
this.remoteArgKind = RemoteArgumentKind.IntrinsicArray;
//for IntrinsicArray this holds the element type code
this.intrinsicTypeCode = Type.GetTypeCode(array.GetType().GetElementType());
this.isByRef = isByRef;
}
#endregion
#endregion
#region Public Accessors
public RemoteArgumentKind RemoteArgumentKind
{
get
{
return this.remoteArgKind;
}
}
public TypeCode TypeCode
{
get
{
return this.intrinsicTypeCode;
}
}
public bool IsByRef
{
get
{
return this.isByRef;
}
set
{
this.isByRef = value;
}
}
#region Type Specific Value Properties
/// <summary>
/// All of these properties do the same thing:
/// On get, validate return and typecode, return if
/// appropriate, else throw InvalidOperationException
/// On set, isByRef MUST be true, then validate kind
/// and typecode and set value if appropriate, else
/// throw InvalidOperationException
/// </summary>
#region Contract
public IContract ContractValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Contract &&
this.intrinsicTypeCode == TypeCode.Object)
{
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (IContract)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Contract &&
this.intrinsicTypeCode == TypeCode.Object)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.Reflection.Missing
public System.Reflection.Missing MissingValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Missing &&
this.intrinsicTypeCode == TypeCode.Empty)
{
//only one possible return value...
return System.Reflection.Missing.Value;
}
throw new InvalidOperationException();
}
}
#endregion
#region Primitive Types -- CLS Compliant
/// <remarks>
/// A Note on the implementation: We could have used
/// a generic helper function to eliminate so much duplicated
/// code. We chose not to to avoid misuse of the generic argument
/// Explicitly coding all of these leaves nothing to interpretation
/// on the use of a function.
/// </remarks>
#region System.Boolean
public System.Boolean BooleanValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Boolean)
{
if (this._value == null)
return default(System.Boolean);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.Boolean)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Boolean)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.Byte
public System.Byte ByteValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Byte)
{
if (this._value == null)
return default(System.Byte);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.Byte)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Byte)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.Char
public System.Char CharValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Char)
{
if (this._value == null)
return default(System.Char);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.Char)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Char)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.DateTime
public System.DateTime DateTimeValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.DateTime)
{
if (this._value == null)
return default(System.DateTime);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.DateTime)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.DateTime)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.DBNull
public System.DBNull DBNullValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.DBNull)
{
if (this._value == null)
return default(System.DBNull);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.DBNull)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.DBNull)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.Decimal
public System.Decimal DecimalValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Decimal)
{
if (this._value == null)
return default(System.Decimal);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.Decimal)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Decimal)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.Double
public System.Double DoubleValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Double)
{
if (this._value == null)
return default(System.Double);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.Double)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Double)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.Int16
public System.Int16 Int16Value
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Int16)
{
if (this._value == null)
return default(System.Int16);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.Int16)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Int16)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.Int32
public System.Int32 Int32Value
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Int32)
{
if (this._value == null)
return default(System.Int32);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.Int32)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Int32)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.Int64
public System.Int64 Int64Value
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Int64)
{
if (this._value == null)
return default(System.Int64);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.Int64)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Int64)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.Single
public System.Single SingleValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Single)
{
if (this._value == null)
return default(System.Single);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.Single)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.Single)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.String
public System.String StringValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.String)
{
if (this._value == null)
return default(System.String);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.String)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.String)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#endregion
#region Intrinsic Types -- Non-CLS Compliant
#region System.SByte
[CLSCompliant(false)]
public System.SByte SByteValue
{
get
{
if(this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.SByte)
{
if (this._value == null)
return default(System.SByte);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.SByte)this._value;
}
throw new InvalidOperationException();
}
set
{
if(this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.SByte)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.UInt16
[CLSCompliant(false)]
public System.UInt16 UInt16Value
{
get
{
if(this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.UInt16)
{
if (this._value == null)
return default(System.UInt16);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.UInt16)this._value;
}
throw new InvalidOperationException();
}
set
{
if(this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.UInt16)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.UInt32
[CLSCompliant(false)]
public System.UInt32 UInt32Value
{
get
{
if(this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.UInt32)
{
if (this._value == null)
return default(System.UInt32);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.UInt32)this._value;
}
throw new InvalidOperationException();
}
set
{
if(this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.UInt32)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#region System.UInt64
[CLSCompliant(false)]
public System.UInt64 UInt64Value
{
get
{
if(this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.UInt64)
{
if (this._value == null)
return default(System.UInt64);
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.UInt64)this._value;
}
throw new InvalidOperationException();
}
set
{
if(this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.Intrinsic &&
this.intrinsicTypeCode == TypeCode.UInt64)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#endregion
#region IntrinsicArray
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public System.Array ArrayValue
{
get
{
if (this.remoteArgKind == RemoteArgumentKind.IntrinsicArray &&
this.intrinsicTypeCode != TypeCode.Object)
{
//do explicit cast here instead of "as"
//because we *want* it to throw if it is a
//bad cast. It would mean an invalid state
//of the struct.
return (System.Array)this._value;
}
throw new InvalidOperationException();
}
set
{
if (this.isByRef == true &&
this.remoteArgKind == RemoteArgumentKind.IntrinsicArray &&
this.intrinsicTypeCode != TypeCode.Object)
{
this._value = value;
}
else
{
throw new InvalidOperationException();
}
}
}
#endregion
#endregion
#endregion
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Infoplus.Client;
using Infoplus.Model;
namespace Infoplus.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface ICarrierApi
{
#region Synchronous Operations
/// <summary>
/// Get a carrier by id
/// </summary>
/// <remarks>
/// Returns the carrier identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="carrierId">Id of carrier to be returned.</param>
/// <returns>Carrier</returns>
Carrier GetCarrierById (string carrierId);
/// <summary>
/// Get a carrier by id
/// </summary>
/// <remarks>
/// Returns the carrier identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="carrierId">Id of carrier to be returned.</param>
/// <returns>ApiResponse of Carrier</returns>
ApiResponse<Carrier> GetCarrierByIdWithHttpInfo (string carrierId);
/// <summary>
/// Search carriers
/// </summary>
/// <remarks>
/// Returns the list of carriers that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<Carrier></returns>
List<Carrier> GetCarrierBySearchText (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search carriers
/// </summary>
/// <remarks>
/// Returns the list of carriers that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<Carrier></returns>
ApiResponse<List<Carrier>> GetCarrierBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Get a carrier by id
/// </summary>
/// <remarks>
/// Returns the carrier identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="carrierId">Id of carrier to be returned.</param>
/// <returns>Task of Carrier</returns>
System.Threading.Tasks.Task<Carrier> GetCarrierByIdAsync (string carrierId);
/// <summary>
/// Get a carrier by id
/// </summary>
/// <remarks>
/// Returns the carrier identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="carrierId">Id of carrier to be returned.</param>
/// <returns>Task of ApiResponse (Carrier)</returns>
System.Threading.Tasks.Task<ApiResponse<Carrier>> GetCarrierByIdAsyncWithHttpInfo (string carrierId);
/// <summary>
/// Search carriers
/// </summary>
/// <remarks>
/// Returns the list of carriers that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<Carrier></returns>
System.Threading.Tasks.Task<List<Carrier>> GetCarrierBySearchTextAsync (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search carriers
/// </summary>
/// <remarks>
/// Returns the list of carriers that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<Carrier>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<Carrier>>> GetCarrierBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class CarrierApi : ICarrierApi
{
/// <summary>
/// Initializes a new instance of the <see cref="CarrierApi"/> class.
/// </summary>
/// <returns></returns>
public CarrierApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="CarrierApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public CarrierApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.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>
/// Get a carrier by id Returns the carrier identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="carrierId">Id of carrier to be returned.</param>
/// <returns>Carrier</returns>
public Carrier GetCarrierById (string carrierId)
{
ApiResponse<Carrier> localVarResponse = GetCarrierByIdWithHttpInfo(carrierId);
return localVarResponse.Data;
}
/// <summary>
/// Get a carrier by id Returns the carrier identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="carrierId">Id of carrier to be returned.</param>
/// <returns>ApiResponse of Carrier</returns>
public ApiResponse< Carrier > GetCarrierByIdWithHttpInfo (string carrierId)
{
// verify the required parameter 'carrierId' is set
if (carrierId == null)
throw new ApiException(400, "Missing required parameter 'carrierId' when calling CarrierApi->GetCarrierById");
var localVarPath = "/beta/carrier/{carrierId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (carrierId != null) localVarPathParams.Add("carrierId", Configuration.ApiClient.ParameterToString(carrierId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetCarrierById: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetCarrierById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<Carrier>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Carrier) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Carrier)));
}
/// <summary>
/// Get a carrier by id Returns the carrier identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="carrierId">Id of carrier to be returned.</param>
/// <returns>Task of Carrier</returns>
public async System.Threading.Tasks.Task<Carrier> GetCarrierByIdAsync (string carrierId)
{
ApiResponse<Carrier> localVarResponse = await GetCarrierByIdAsyncWithHttpInfo(carrierId);
return localVarResponse.Data;
}
/// <summary>
/// Get a carrier by id Returns the carrier identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="carrierId">Id of carrier to be returned.</param>
/// <returns>Task of ApiResponse (Carrier)</returns>
public async System.Threading.Tasks.Task<ApiResponse<Carrier>> GetCarrierByIdAsyncWithHttpInfo (string carrierId)
{
// verify the required parameter 'carrierId' is set
if (carrierId == null) throw new ApiException(400, "Missing required parameter 'carrierId' when calling GetCarrierById");
var localVarPath = "/beta/carrier/{carrierId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (carrierId != null) localVarPathParams.Add("carrierId", Configuration.ApiClient.ParameterToString(carrierId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetCarrierById: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetCarrierById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<Carrier>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Carrier) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Carrier)));
}
/// <summary>
/// Search carriers Returns the list of carriers that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<Carrier></returns>
public List<Carrier> GetCarrierBySearchText (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<Carrier>> localVarResponse = GetCarrierBySearchTextWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search carriers Returns the list of carriers that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<Carrier></returns>
public ApiResponse< List<Carrier> > GetCarrierBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/beta/carrier/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetCarrierBySearchText: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetCarrierBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<List<Carrier>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<Carrier>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Carrier>)));
}
/// <summary>
/// Search carriers Returns the list of carriers that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<Carrier></returns>
public async System.Threading.Tasks.Task<List<Carrier>> GetCarrierBySearchTextAsync (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<Carrier>> localVarResponse = await GetCarrierBySearchTextAsyncWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search carriers Returns the list of carriers that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<Carrier>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<Carrier>>> GetCarrierBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/beta/carrier/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetCarrierBySearchText: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetCarrierBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<List<Carrier>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<Carrier>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Carrier>)));
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Rendering\Testing\Tcl\labeledContours.tcl
// output file is AVlabeledContours.cs
/// <summary>
/// The testing class derived from AVlabeledContours
/// </summary>
public class AVlabeledContoursClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVlabeledContours(String [] argv)
{
//Prefix Content is: ""
// demonstrate labeling of contour with scalar value[]
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.SetMultiSamples(0);
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
// Read a slice and contour it[]
v16 = new vtkVolume16Reader();
v16.SetDataDimensions((int)64,(int)64);
v16.GetOutput().SetOrigin((double)0.0,(double)0.0,(double)0.0);
v16.SetDataByteOrderToLittleEndian();
v16.SetFilePrefix((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/headsq/quarter");
v16.SetImageRange((int)45,(int)45);
v16.SetDataSpacing((double)3.2,(double)3.2,(double)1.5);
iso = new vtkContourFilter();
iso.SetInputConnection((vtkAlgorithmOutput)v16.GetOutputPort());
iso.GenerateValues((int)6,(double)500,(double)1150);
iso.Update();
numPts = iso.GetOutput().GetNumberOfPoints();
isoMapper = vtkPolyDataMapper.New();
isoMapper.SetInputConnection((vtkAlgorithmOutput)iso.GetOutputPort());
isoMapper.ScalarVisibilityOn();
isoMapper.SetScalarRange((double)((vtkDataSet)iso.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)iso.GetOutput()).GetScalarRange()[1]);
isoActor = new vtkActor();
isoActor.SetMapper((vtkMapper)isoMapper);
// Subsample the points and label them[]
mask = new vtkMaskPoints();
mask.SetInputConnection((vtkAlgorithmOutput)iso.GetOutputPort());
mask.SetOnRatio((int)(numPts/50));
mask.SetMaximumNumberOfPoints((int)50);
mask.RandomModeOn();
// Create labels for points - only show visible points[]
visPts = new vtkSelectVisiblePoints();
visPts.SetInputConnection((vtkAlgorithmOutput)mask.GetOutputPort());
visPts.SetRenderer((vtkRenderer)ren1);
ldm = new vtkLabeledDataMapper();
ldm.SetInputConnection((vtkAlgorithmOutput)mask.GetOutputPort());
// ldm SetLabelFormat "%g"[]
ldm.SetLabelModeToLabelScalars();
tprop = ldm.GetLabelTextProperty();
tprop.SetFontFamilyToArial();
tprop.SetFontSize((int)10);
tprop.SetColor((double)1,(double)0,(double)0);
contourLabels = new vtkActor2D();
contourLabels.SetMapper((vtkMapper2D)ldm);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor2D((vtkProp)isoActor);
ren1.AddActor2D((vtkProp)contourLabels);
ren1.SetBackground((double)1,(double)1,(double)1);
renWin.SetSize((int)500,(int)500);
renWin.Render();
ren1.GetActiveCamera().Zoom((double)1.5);
// render the image[]
//[]
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkVolume16Reader v16;
static vtkContourFilter iso;
static long numPts;
static vtkPolyDataMapper isoMapper;
static vtkActor isoActor;
static vtkMaskPoints mask;
static vtkSelectVisiblePoints visPts;
static vtkLabeledDataMapper ldm;
static vtkTextProperty tprop;
static vtkActor2D contourLabels;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkVolume16Reader Getv16()
{
return v16;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setv16(vtkVolume16Reader toSet)
{
v16 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkContourFilter Getiso()
{
return iso;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiso(vtkContourFilter toSet)
{
iso = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static long GetnumPts()
{
return numPts;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetnumPts(long toSet)
{
numPts = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetisoMapper()
{
return isoMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetisoMapper(vtkPolyDataMapper toSet)
{
isoMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetisoActor()
{
return isoActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetisoActor(vtkActor toSet)
{
isoActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkMaskPoints Getmask()
{
return mask;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmask(vtkMaskPoints toSet)
{
mask = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkSelectVisiblePoints GetvisPts()
{
return visPts;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetvisPts(vtkSelectVisiblePoints toSet)
{
visPts = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkLabeledDataMapper Getldm()
{
return ldm;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setldm(vtkLabeledDataMapper toSet)
{
ldm = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTextProperty Gettprop()
{
return tprop;
}
///<summary> A Set Method for Static Variables </summary>
public static void Settprop(vtkTextProperty toSet)
{
tprop = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor2D GetcontourLabels()
{
return contourLabels;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcontourLabels(vtkActor2D toSet)
{
contourLabels = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(v16!= null){v16.Dispose();}
if(iso!= null){iso.Dispose();}
if(isoMapper!= null){isoMapper.Dispose();}
if(isoActor!= null){isoActor.Dispose();}
if(mask!= null){mask.Dispose();}
if(visPts!= null){visPts.Dispose();}
if(ldm!= null){ldm.Dispose();}
if(tprop!= null){tprop.Dispose();}
if(contourLabels!= null){contourLabels.Dispose();}
}
}
//--- end of script --//
| |
/*
* CultureInfo.cs - Implementation of "System.Globalization.CultureInfo".
*
* Copyright (C) 2001, 2003, 2004 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Globalization
{
using System;
using System.Runtime.CompilerServices;
using System.Text;
// Note: if we don't have reflection, then we cannot load I18N handlers,
// and all "CultureInfo" objects act like the invariant culture.
public class CultureInfo : ICloneable, IFormatProvider
{
// Cached culture objects.
private static CultureInfo invariantCulture;
[ThreadStatic] private static CultureInfo currentCulture;
[ThreadStatic] private static CultureInfo currentUICulture;
#if CONFIG_REFLECTION
private static CultureInfo globalCulture;
private static bool gettingCurrent;
#endif
// Internal state.
private int cultureID;
private bool readOnly;
private Calendar calendar;
private Calendar[] otherCalendars;
private NumberFormatInfo numberFormat;
private CompareInfo compareInfo;
private DateTimeFormatInfo dateTimeFormat;
private TextInfo textInfo;
private bool userOverride;
#if CONFIG_REFLECTION
private CultureInfo handler;
// Culture identifier for "es-ES" with traditional sort rules.
private const int TraditionalSpanish = 0x040A;
#endif
// Constructors.
public CultureInfo(int culture)
: this(culture, true)
{
// Nothing to do here.
}
public CultureInfo(String name)
: this(name, true)
{
// Nothing to do here.
}
public CultureInfo(int culture, bool useUserOverride)
{
if(culture < 0)
{
throw new ArgumentOutOfRangeException
("culture", _("ArgRange_NonNegative"));
}
if((culture & 0x40000000) != 0)
{
// This flag is a special indication from the I18N
// library that this object is a culture handler
// and we should not recursively load another culture.
this.cultureID = (culture & ~0x40000000);
return;
}
#if CONFIG_REFLECTION
if(culture == TraditionalSpanish)
{
cultureID = culture;
handler = GetCultureHandler(cultureID, useUserOverride);
}
else if(culture == 0x007F)
{
cultureID = 0x007F;
}
else
{
cultureID = culture;
handler = GetCultureHandler(cultureID, useUserOverride);
}
#else
cultureID = culture;
#endif
userOverride = useUserOverride;
}
public CultureInfo(String name, bool useUserOverride)
{
if(name == null)
{
throw new ArgumentNullException("name");
}
#if CONFIG_REFLECTION
userOverride = useUserOverride;
if( name == string.Empty ) {
cultureID = 0x007F;
}
else {
handler = GetCultureHandler(name, useUserOverride);
cultureID = handler.LCID;
}
#else
cultureID = 0x007F;
userOverride = useUserOverride;
#endif
}
#if CONFIG_REFLECTION
private CultureInfo(CultureInfo handler, bool useUserOverride)
{
this.handler = handler;
this.userOverride = useUserOverride;
this.cultureID = handler.LCID;
}
#endif
// Get the invariant culture object.
public static CultureInfo InvariantCulture
{
get
{
lock(typeof(CultureInfo))
{
if(invariantCulture != null)
{
return invariantCulture;
}
invariantCulture = new CultureInfo(0x007F);
invariantCulture.readOnly = true;
return invariantCulture;
}
}
}
#if CONFIG_REFLECTION
// Get the current culture identifier from the runtime engine.
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static int InternalCultureID();
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static String InternalCultureName();
// Get the global culture object for the running process.
private static CultureInfo GlobalCulture
{
get
{
lock(typeof(CultureInfo))
{
if(globalCulture != null)
{
return globalCulture;
}
if(gettingCurrent)
{
// We were recursively called during initialization,
// so return the invariant culture for now.
return InvariantCulture;
}
gettingCurrent = true;
int id = InternalCultureID();
CultureInfo handler;
if(id <= 0)
{
// Try getting by name instead, in case the
// engine doesn't know about culture ID's.
String name = InternalCultureName();
if(name != null)
{
handler = GetCultureHandler(name, true);
}
else
{
handler = null;
}
}
else if(id == 0x007F)
{
handler = null;
}
else
{
handler = GetCultureHandler(id, true);
}
if(handler == null)
{
// Could not find a handler, so use invariant.
globalCulture = InvariantCulture;
gettingCurrent = false;
return globalCulture;
}
globalCulture = new CultureInfo(handler, true);
globalCulture.readOnly = true;
gettingCurrent = false;
return globalCulture;
}
}
}
#else // !CONFIG_REFLECTION
// Get the global culture object for the running process.
private static CultureInfo GlobalCulture
{
get
{
// The invariant culture is the only one in the system.
return InvariantCulture;
}
}
#endif // !CONFIG_REFLECTION
// Get the current culture object for the running thread.
public static CultureInfo CurrentCulture
{
get
{
if(currentCulture == null)
{
currentCulture = GlobalCulture;
}
return currentCulture;
}
}
// Set the current culture.
internal static void SetCurrentCulture(CultureInfo value)
{
currentCulture = value;
#if !ECMA_COMPAT
RegionInfo.currentRegion = null; // Recreate on next call.
#endif
}
// Get the current UI culture object for the running thread.
public static CultureInfo CurrentUICulture
{
get
{
if(currentUICulture == null)
{
currentUICulture = GlobalCulture;
}
return currentUICulture;
}
}
// Set the current UI culture.
internal static void SetCurrentUICulture(CultureInfo value)
{
currentUICulture = value;
}
// Get the installed UI culture object for the system.
public static CultureInfo InstalledUICulture
{
get
{
return GlobalCulture;
}
}
#if !ECMA_COMPAT
// Create a CultureInfo object for a specific culture.
public static CultureInfo CreateSpecificCulture(String name)
{
CultureInfo culture = new CultureInfo(name);
return culture;
}
// Get the list of all cultures supported by this system.
public static CultureInfo[] GetCultures(CultureTypes types)
{
Object obj = Encoding.InvokeI18N("GetCultures", types);
if(obj != null)
{
return (CultureInfo[])obj;
}
else if((types & CultureTypes.NeutralCultures) != 0)
{
CultureInfo[] cultures = new CultureInfo [1];
cultures[0] = InvariantCulture;
return cultures;
}
else
{
return new CultureInfo [0];
}
}
// Wrap a culture information object to make it read-only.
public static CultureInfo ReadOnly(CultureInfo ci)
{
if(ci == null)
{
throw new ArgumentNullException("ci");
}
if(ci.IsReadOnly)
{
return ci;
}
else
{
CultureInfo culture = (CultureInfo)(ci.MemberwiseClone());
culture.readOnly = true;
return culture;
}
}
#endif
// Get the default calendar that is used by the culture.
public virtual Calendar Calendar
{
get
{
lock(this)
{
if(calendar == null)
{
#if CONFIG_REFLECTION
if(handler != null)
{
calendar = handler.Calendar;
if(calendar == null)
{
calendar = new GregorianCalendar();
}
}
else
#endif
{
calendar = new GregorianCalendar();
}
}
return calendar;
}
}
}
// Get the comparison rules that are used by the culture.
public virtual CompareInfo CompareInfo
{
get
{
lock(this)
{
if(compareInfo == null)
{
#if CONFIG_REFLECTION
if(handler != null)
{
compareInfo = handler.CompareInfo;
if(compareInfo == null)
{
compareInfo =
CompareInfo.InvariantCompareInfo;
}
}
else
#endif
{
compareInfo = CompareInfo.InvariantCompareInfo;
}
}
return compareInfo;
}
}
}
// Get or set the date and time formatting information for this culture.
public virtual DateTimeFormatInfo DateTimeFormat
{
get
{
if(dateTimeFormat == null)
{
if(cultureID == 0x007F && readOnly)
{
// This is the invariant culture, so always
// return the invariant date time format info.
return DateTimeFormatInfo.InvariantInfo;
}
#if CONFIG_REFLECTION
else if(handler != null)
{
dateTimeFormat = handler.DateTimeFormat;
if(dateTimeFormat == null)
{
dateTimeFormat = new DateTimeFormatInfo();
}
}
else
#endif
{
dateTimeFormat = new DateTimeFormatInfo();
}
}
if(readOnly)
{
// Wrap up the date/time formatting information
// to make it read-only like the culture.
dateTimeFormat = DateTimeFormatInfo.ReadOnly
(dateTimeFormat);
}
return dateTimeFormat;
}
set
{
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
if(value == null)
{
throw new ArgumentNullException("value");
}
dateTimeFormat = value;
}
}
#if CONFIG_REFLECTION
// Get the display name for this culture.
public virtual String DisplayName
{
get
{
if(handler != null)
{
return handler.DisplayName;
}
return "Invariant Language (Invariant Country)";
}
}
// Get the English display name for this culture.
public virtual String EnglishName
{
get
{
if(handler != null)
{
return handler.EnglishName;
}
return "Invariant Language (Invariant Country)";
}
}
// Determine if this is a neutral culture.
public virtual bool IsNeutralCulture
{
get
{
return ((cultureID & ~0x3FF) == 0);
}
}
// Get the culture identifier for this instance.
public virtual int LCID
{
get
{
return cultureID;
}
}
// Get the culture name.
public virtual String Name
{
get
{
if(handler != null)
{
return handler.Name;
}
return "";
}
}
// Get the culture's full name in the native language.
public virtual String NativeName
{
get
{
if(handler != null)
{
return handler.NativeName;
}
return "Invariant Language (Invariant Country)";
}
}
#else // !CONFIG_REFLECTION
// Get the culture name.
public virtual String Name
{
get
{
// All cultures are invariant if no reflection.
return "";
}
}
#endif // !CONFIG_REFLECTION
// Determine if this culture instance is read-only.
public bool IsReadOnly
{
get
{
return readOnly;
}
}
#if CONFIG_FRAMEWORK_1_2
// Get the keyboard layout identifier for this culture.
public virtual int KeyboardLayoutID
{
get
{
if(handler != null)
{
return handler.KeyboardLayoutID;
}
return 0x0C09; // US 101 keyboard.
}
}
#endif // CONFIG_FRAMEWORK_1_2
// Get or set the number formatting information for this culture.
public virtual NumberFormatInfo NumberFormat
{
get
{
if(numberFormat == null)
{
if(cultureID == 0x007F && readOnly)
{
// This is the invariant culture, so always
// return the invariant number format info.
return NumberFormatInfo.InvariantInfo;
}
#if CONFIG_REFLECTION
else if(handler != null)
{
numberFormat = handler.NumberFormat;
if(numberFormat == null)
{
numberFormat = new NumberFormatInfo();
}
}
else
#endif
{
numberFormat = new NumberFormatInfo();
}
}
if(readOnly)
{
// Wrap up the number formatting information
// to make it read-only like the culture.
numberFormat = NumberFormatInfo.ReadOnly
(numberFormat);
}
return numberFormat;
}
set
{
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
if(value == null)
{
throw new ArgumentNullException("value");
}
numberFormat = value;
}
}
// Get the optional calendars for this instance.
public virtual Calendar[] OptionalCalendars
{
get
{
lock(this)
{
if(otherCalendars == null)
{
#if CONFIG_REFLECTION
if(handler != null)
{
otherCalendars = handler.OptionalCalendars;
}
else
#endif
{
otherCalendars = new Calendar [0];
}
}
return otherCalendars;
}
}
}
// Get the parent culture.
public virtual CultureInfo Parent
{
get
{
if((cultureID & ~0x03FF) == 0)
{
return InvariantCulture;
}
else
{
return new CultureInfo(cultureID & 0x03FF);
}
}
}
// Get the text writing system associated with this culture.
public virtual TextInfo TextInfo
{
get
{
lock(this)
{
if(textInfo == null)
{
#if CONFIG_REFLECTION
if(handler != null)
{
textInfo = handler.TextInfo;
if(textInfo == null)
{
textInfo = new TextInfo(cultureID);
}
}
else
#endif
{
textInfo = new TextInfo(cultureID);
}
}
return textInfo;
}
}
}
#if CONFIG_REFLECTION
// Get the 3-letter ISO language name for this culture.
public virtual String ThreeLetterISOLanguageName
{
get
{
if(handler != null)
{
return handler.ThreeLetterISOLanguageName;
}
return "IVL";
}
}
// Get the 3-letter Windows language name for this culture.
public virtual String ThreeLetterWindowsLanguageName
{
get
{
if(handler != null)
{
return handler.ThreeLetterWindowsLanguageName;
}
return "IVL";
}
}
// Get the 2-letter ISO language name for this culture.
public virtual String TwoLetterISOLanguageName
{
get
{
if(handler != null)
{
return handler.TwoLetterISOLanguageName;
}
return "iv";
}
}
#endif // CONFIG_REFLECTION
// Determine if this culture is configured for user overrides.
public bool UseUserOverride
{
get
{
return userOverride;
}
}
// Implementation of the ICloneable interface.
public virtual Object Clone()
{
#if !ECMA_COMPAT
CultureInfo culture = (CultureInfo)(MemberwiseClone());
culture.readOnly = false;
// clone DateTimeFormat and NumberFormat if available
if(dateTimeFormat != null)
{
culture.dateTimeFormat = (DateTimeFormatInfo)dateTimeFormat.Clone();
}
if(numberFormat != null)
{
culture.numberFormat = (NumberFormatInfo)numberFormat.Clone();
}
return culture;
#else
return MemberwiseClone();
#endif
}
// Implementation of the IFormatProvider interface.
public virtual Object GetFormat(Type formatType)
{
if(formatType ==
typeof(System.Globalization.DateTimeFormatInfo))
{
return DateTimeFormat;
}
else if(formatType ==
typeof(System.Globalization.NumberFormatInfo))
{
return NumberFormat;
}
else
{
return null;
}
}
// Clear any cached culture data in this object.
public void ClearCachedData()
{
// Nothing to do here.
}
// Determine if two culture objects are equal.
public override bool Equals(Object obj)
{
CultureInfo other = (obj as CultureInfo);
if(other != null)
{
return (other.cultureID == cultureID);
}
else
{
return false;
}
}
// Get the hash code for this object.
public override int GetHashCode()
{
return cultureID;
}
// Convert this object into a string.
public override String ToString()
{
return Name;
}
#if CONFIG_REFLECTION
// Get the culture handler for a specific culture.
internal static CultureInfo GetCultureHandler
(int culture, bool useUserOverride)
{
Object obj = Encoding.InvokeI18N
("GetCulture", culture, useUserOverride);
if(obj == null)
{
// Try the neutral culture instead.
obj = Encoding.InvokeI18N
("GetCulture", culture & 0x03FF, useUserOverride);
}
return (CultureInfo)obj;
}
internal static CultureInfo GetCultureHandler
(String culture, bool useUserOverride)
{
Object obj = Encoding.InvokeI18N
("GetCulture", culture, useUserOverride);
return (CultureInfo)obj;
}
#endif // CONFIG_REFLECTION
}; // class CultureInfo
}; // namespace System.Globalization
| |
/*
* Copyright (C) 2005-2015 Christoph Rupp ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Hamster;
namespace Unittests
{
public class DatabaseTest
{
private static int errorCounter;
static void MyErrorHandler(int level, String message) {
Console.WriteLine("ErrorHandler: Level " + level + ", msg: " + message);
errorCounter++;
}
private void SetErrorHandler() {
Hamster.Environment env = new Hamster.Environment();
ErrorHandler eh = new ErrorHandler(MyErrorHandler);
try {
Database.SetErrorHandler(eh);
env.Create(null);
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_INV_PARAMETER, e.ErrorCode);
Assert.AreEqual(1, errorCounter);
}
Database.SetErrorHandler(null);
}
private void CreateWithParameters()
{
using (Hamster.Environment env = new Hamster.Environment())
{
env.Create("ntest.db");
Parameter[] param = new Parameter[] {
new Parameter {
name = HamConst.HAM_PARAM_KEYSIZE, value = 32
}
};
using (Database db = env.CreateDatabase(13, 0, param)) { }
}
}
private void CreateWithParameters2()
{
using (Hamster.Environment env = new Hamster.Environment())
{
env.Create("ntest.db");
using (Database db = env.CreateDatabase(13, 0,
new Parameter[0])) { }
}
}
private void GetVersion() {
Hamster.Version v = Database.GetVersion();
Assert.AreEqual(2, v.major);
Assert.AreEqual(1, v.minor);
}
private void DatabaseClose() {
Database db = new Database();
try {
db.Close();
}
catch (DatabaseException e) {
Assert.Fail("Unexpected exception " + e);
}
}
private void CreateString() {
Database db = new Database();
Hamster.Environment env = new Hamster.Environment();
try {
env.Create("ntest.db");
db = env.CreateDatabase(1);
db.Close();
env.Close();
env.Open("ntest.db");
db = env.OpenDatabase(1);
db.Close();
env.Close();
}
catch (DatabaseException e) {
Assert.Fail("Unexpected exception " + e);
}
}
private void CreateInvalidParameter() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
Parameter[] param = new Parameter[3];
param[1] = new Parameter();
param[2] = new Parameter();
try {
env.Create("ntest.db");
db = env.CreateDatabase(1, 0, param);
db.Close();
env.Close();
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_INV_PARAMETER, e.ErrorCode);
}
}
private void CreateStringIntIntParameter() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
Parameter[] param = new Parameter[1];
param[0] = new Parameter();
param[0].name = HamConst.HAM_PARAM_CACHESIZE;
param[0].value = 1024;
try {
env.Create("ntest.db", 0, 0644, param);
env.Close();
}
catch (DatabaseException e) {
Assert.Fail("Unexpected exception " + e);
}
}
private void CreateStringIntIntParameterNeg() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
Parameter[] param = new Parameter[1];
param[0] = new Parameter();
param[0].name = HamConst.HAM_PARAM_CACHESIZE;
param[0].value = 1024;
try {
env.Create("ntest.db", HamConst.HAM_IN_MEMORY, 0644, param);
env.Close();
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_INV_PARAMETER, e.ErrorCode);
}
}
private int compareCounter;
private int MyCompareFunc(byte[] lhs, byte[] rhs) {
// always return a different value or hamsterdb thinks
// we're inserting duplicates
return ++compareCounter;
}
private void SetComparator() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
byte[] r = new byte[5];
Parameter[] param = new Parameter[1];
param[0] = new Parameter();
param[0].name = HamConst.HAM_PARAM_KEY_TYPE;
param[0].value = HamConst.HAM_TYPE_CUSTOM;
compareCounter = 0;
try {
env.Create("ntest.db");
db = env.CreateDatabase(1, 0, param);
db.SetCompareFunc(new CompareFunc(MyCompareFunc));
db.Insert(k, r);
k[0] = 1;
db.Insert(k, r);
db.Close();
env.Close();
}
catch (DatabaseException e) {
Assert.Fail("unexpected exception " + e);
}
Assert.AreEqual(1, compareCounter);
}
void checkEqual(byte[] lhs, byte[] rhs)
{
Assert.AreEqual(lhs.Length, rhs.Length);
for (int i = 0; i < lhs.Length; i++)
Assert.AreEqual(lhs[i], rhs[i]);
}
private void FindKey() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
byte[] r1 = new byte[5];
r1[0] = 1;
try {
env.Create("ntest.db");
db = env.CreateDatabase(1);
db.Insert(k, r1);
byte[] r2 = db.Find(k);
checkEqual(r1, r2);
db.Close();
env.Close();
}
catch (DatabaseException e) {
Assert.Fail("unexpected exception " + e);
}
}
private void FindKeyNull() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
try {
env.Create("ntest.db");
db = env.CreateDatabase(1);
byte[] r = db.Find(null);
}
catch (NullReferenceException) {
}
db.Close();
env.Close();
}
private void FindUnknownKey() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
try {
env.Create("ntest.db");
db = env.CreateDatabase(1);
byte[] r = db.Find(k);
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_KEY_NOT_FOUND, e.ErrorCode);
}
db.Close();
env.Close();
}
private void InsertKey() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
byte[] r1 = new byte[5];
byte[] r2;
try {
env.Create("ntest.db");
db = env.CreateDatabase(1);
k[0] = 1;
r1[0] = 1;
db.Insert(k, r1);
r2 = db.Find(k);
checkEqual(r1, r2);
k[0] = 2;
r1[0] = 2;
db.Insert(k, r1);
r2 = db.Find(k);
checkEqual(r1, r2);
k[0] = 3;
r1[0] = 3;
db.Insert(k, r1);
r2 = db.Find(k);
checkEqual(r1, r2);
db.Close();
env.Close();
}
catch (DatabaseException e) {
Assert.Fail("unexpected exception " + e);
}
}
private void InsertRecNo()
{
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] r1 = new byte[5];
byte[] r2;
try
{
env.Create("ntest.db");
db = env.CreateDatabase(1, HamConst.HAM_RECORD_NUMBER);
r1[0] = 1;
var k = db.InsertRecNo(r1);
r2 = db.Find(k);
checkEqual(r1, r2);
r1[0] = 2;
k = db.InsertRecNo(r1);
r2 = db.Find(k);
checkEqual(r1, r2);
r1[0] = 3;
k = db.InsertRecNo(r1);
r2 = db.Find(k);
checkEqual(r1, r2);
}
catch (DatabaseException e)
{
Assert.Fail("unexpected exception " + e);
}
db.Close();
env.Close();
}
private void InsertKeyInvalidParam() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
byte[] r = new byte[5];
env.Create("ntest.db");
db = env.CreateDatabase(1);
try {
db.Insert(null, r);
}
catch (NullReferenceException) {
}
try {
db.Insert(k, null);
}
catch (NullReferenceException) {
}
try {
db.Insert(k, r, 9999);
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_INV_PARAMETER, e.ErrorCode);
}
db.Close();
env.Close();
}
private void InsertKeyNegative() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
byte[] r = new byte[5];
try {
env.Create("ntest.db");
db = env.CreateDatabase(1);
db.Insert(k, r);
db.Insert(k, r);
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_DUPLICATE_KEY, e.ErrorCode);
}
db.Close();
env.Close();
}
private void InsertKeyOverwrite() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
byte[] r = new byte[5];
try {
env.Create("ntest.db");
db = env.CreateDatabase(1);
db.Insert(k, r);
r[0] = 1;
db.Insert(k, r, HamConst.HAM_OVERWRITE);
byte[] r2 = db.Find(k);
checkEqual(r, r2);
db.Close();
env.Close();
}
catch (DatabaseException e) {
Assert.Fail("unexpected exception " + e);
}
}
private void EraseKey() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
byte[] r = new byte[5];
env.Create("ntest.db");
db = env.CreateDatabase(1);
db.Insert(k, r);
byte[] r2 = db.Find(k);
checkEqual(r, r2);
db.Erase(k);
try {
r2 = db.Find(k);
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_KEY_NOT_FOUND, e.ErrorCode);
}
db.Close();
env.Close();
}
private void EraseKeyNegative() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
env.Create("ntest.db");
db = env.CreateDatabase(1);
try {
db.Erase(null);
}
catch (NullReferenceException) {
}
db.Close();
env.Close();
}
private void EraseUnknownKey() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
env.Create("ntest.db");
db = env.CreateDatabase(1);
try {
db.Erase(k);
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_KEY_NOT_FOUND, e.ErrorCode);
}
db.Close();
env.Close();
}
private void EraseKeyTwice() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k = new byte[5];
byte[] r = new byte[5];
env.Create("ntest.db");
db = env.CreateDatabase(1);
db.Insert(k, r);
byte[] r2 = db.Find(k);
checkEqual(r, r2);
db.Erase(k);
try {
db.Erase(k);
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_KEY_NOT_FOUND, e.ErrorCode);
}
db.Close();
env.Close();
}
private void Recovery() {
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
env.Create("ntest.db", HamConst.HAM_ENABLE_RECOVERY);
db = env.CreateDatabase(1);
byte[] k = new byte[5];
byte[] r = new byte[5];
db.Insert(k, r);
db.Close();
env.Close();
}
private void GetKeyCount()
{
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
env.Create("ntest.db");
db = env.CreateDatabase(1);
byte[] k = new byte[5];
byte[] r = new byte[5];
Assert.AreEqual(0, db.GetKeyCount());
db.Insert(k, r);
Assert.AreEqual(1, db.GetKeyCount());
k[0] = 1;
db.Insert(k, r);
Assert.AreEqual(2, db.GetKeyCount());
db.Close();
env.Close();
}
private int NumericalCompareFunc(byte[] lhs, byte[] rhs)
{
// translate buffers to two numbers and compare them
ulong ulhs = BitConverter.ToUInt64(lhs, 0);
ulong urhs = BitConverter.ToUInt64(rhs, 0);
if (ulhs < urhs) return -1;
if (ulhs > urhs) return +1;
return 0;
}
private Database CreateDatabase(string file)
{
List<Parameter> list = new List<Parameter>();
Parameter param1 = new Parameter();
param1.name = HamConst.HAM_PARAM_CACHESIZE;
param1.value = 768 * 1024 * 1024;
list.Add(param1);
Parameter param2 = new Parameter();
param2.name = HamConst.HAM_PARAM_KEYSIZE;
param2.value = 8; // sizeof(ulong);
list.Add(param2);
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
env.Create(file, 0, 0, list.ToArray());
db = env.CreateDatabase(1);
db.SetCompareFunc(new CompareFunc(NumericalCompareFunc));
return db;
}
private Database OpenDatabase(string file)
{
List<Parameter> list = new List<Parameter>();
Parameter param1 = new Parameter();
param1.name = HamConst.HAM_PARAM_CACHESIZE;
param1.value = 768 * 1024 * 1024;
list.Add(param1);
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
env.Open(file, 0, list.ToArray());
db = env.OpenDatabase(1);
db.SetCompareFunc(new CompareFunc(NumericalCompareFunc));
return db;
}
private void Cursor10000Test()
{
//create database
Hamster.Environment env = new Hamster.Environment();
env.Create("ntest.db");
Parameter[] param = new Parameter[1];
param[0] = new Parameter();
param[0].name = HamConst.HAM_PARAM_KEY_TYPE;
param[0].value = HamConst.HAM_TYPE_UINT64;
Database db = env.CreateDatabase(1, 0, param);
//insert records
for (ulong i = 0; i < 10000; i++)
{
byte[] key = BitConverter.GetBytes(i);
byte[] record = new byte[20];
db.Insert(key, record);
}
//close database
db.Close();
//reopen again
db = env.OpenDatabase(1);
Cursor cursor = new Cursor(db);
cursor.MoveFirst();
ulong firstKey = BitConverter.ToUInt64(cursor.GetKey(), 0);
Assert.AreEqual((ulong)0, firstKey);
cursor.MoveLast();
ulong lastKey = BitConverter.ToUInt64(cursor.GetKey(), 0);
Assert.AreEqual((ulong)9999, lastKey);
//close database
cursor.Close();
db.Close();
env.Close();
}
private void AutoCleanupCursors()
{
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
env.Create("ntest.db");
db = env.CreateDatabase(1);
Cursor cursor = new Cursor(db);
// let gc do the cleanup
env.Close();
}
private void AutoCleanupCursors2()
{
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
env.Create("ntest.db");
db = env.CreateDatabase(1);
Cursor cursor1 = new Cursor(db);
Cursor cursor2 = new Cursor(db);
Cursor cursor3 = new Cursor(db);
Cursor cursor4 = new Cursor(db);
Cursor cursor5 = new Cursor(db);
// let gc do the cleanup
env.Close();
}
private void AutoCleanupCursors3()
{
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
env.Create("ntest.db");
db = env.CreateDatabase(1);
Cursor cursor1 = new Cursor(db);
Cursor cursor2 = new Cursor(db);
Cursor cursor3 = new Cursor(db);
Cursor cursor4 = new Cursor(db);
Cursor cursor5 = new Cursor(db);
cursor3.Close();
cursor5.Close();
// let gc do the cleanup
env.Close();
}
private void AutoCleanupCursors4()
{
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
env.Create("ntest.db");
db = env.CreateDatabase(1);
Cursor cursor1 = new Cursor(db);
Cursor cursor2 = cursor1.Clone();
Cursor cursor3 = cursor1.Clone();
Cursor cursor4 = cursor1.Clone();
Cursor cursor5 = cursor1.Clone();
cursor3.Close();
cursor5.Close();
// let gc do the cleanup
env.Close();
}
private void ApproxMatching()
{
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k1 = new byte[5];
byte[] r1 = new byte[5];
k1[0] = 1; r1[0] = 1;
byte[] k2 = new byte[5];
byte[] r2 = new byte[5];
k2[0] = 2; r2[0] = 2;
byte[] k3 = new byte[5];
byte[] r3 = new byte[5];
k3[0] = 3; r3[0] = 3;
try
{
env.Create("ntest.db");
db = env.CreateDatabase(1);
db.Insert(k1, r1);
db.Insert(k2, r2);
db.Insert(k3, r3);
byte[] r = db.Find(null, ref k2, HamConst.HAM_FIND_GT_MATCH);
checkEqual(r, r3);
checkEqual(k2, k3);
k2[0] = 2;
r = db.Find(null, ref k2, HamConst.HAM_FIND_LT_MATCH);
checkEqual(r, r1);
checkEqual(k2, k1);
db.Close();
env.Close();
}
catch (DatabaseException e)
{
Assert.Fail("unexpected exception " + e);
}
}
public void Run()
{
Console.WriteLine("DatabaseTest.InsertRecNo");
InsertRecNo();
Console.WriteLine("DatabaseTest.SetErrorHandler");
SetErrorHandler();
Console.WriteLine("DatabaseTest.CreateWithParameters");
CreateWithParameters();
Console.WriteLine("DatabaseTest.CreateWithParameters2");
CreateWithParameters2();
Console.WriteLine("DatabaseTest.GetVersion");
GetVersion();
Console.WriteLine("DatabaseTest.DatabaseClose");
DatabaseClose();
Console.WriteLine("DatabaseTest.CreateInvalidParameter");
CreateInvalidParameter();
Console.WriteLine("DatabaseTest.CreateString");
CreateString();
Console.WriteLine("DatabaseTest.CreateStringIntIntParameter");
CreateStringIntIntParameter();
Console.WriteLine("DatabaseTest.CreateStringIntIntParameterNeg");
CreateStringIntIntParameterNeg();
Console.WriteLine("DatabaseTest.CreateWithParameters");
CreateWithParameters();
Console.WriteLine("DatabaseTest.CreateWithParameters2");
CreateWithParameters2();
Console.WriteLine("DatabaseTest.SetComparator");
SetComparator();
Console.WriteLine("DatabaseTest.FindKey");
FindKey();
Console.WriteLine("DatabaseTest.FindKeyNull");
FindKeyNull();
Console.WriteLine("DatabaseTest.FindUnknownKey");
FindUnknownKey();
Console.WriteLine("DatabaseTest.InsertKey");
InsertKey();
Console.WriteLine("DatabaseTest.InsertKeyInvalidParam");
InsertKeyInvalidParam();
Console.WriteLine("DatabaseTest.InsertKeyNegative");
InsertKeyNegative();
Console.WriteLine("DatabaseTest.InsertKeyOverwrite");
InsertKeyOverwrite();
Console.WriteLine("DatabaseTest.EraseKey");
EraseKey();
Console.WriteLine("DatabaseTest.EraseKeyNegative");
EraseKeyNegative();
Console.WriteLine("DatabaseTest.EraseKeyTwice");
EraseKeyTwice();
Console.WriteLine("DatabaseTest.EraseUnknownKey");
EraseUnknownKey();
Console.WriteLine("DatabaseTest.GetKeyCount");
GetKeyCount();
Console.WriteLine("DatabaseTest.Cursor10000Test");
Cursor10000Test();
Console.WriteLine("DatabaseTest.AutoCleanupCursors");
AutoCleanupCursors();
Console.WriteLine("DatabaseTest.AutoCleanupCursors2");
AutoCleanupCursors2();
Console.WriteLine("DatabaseTest.AutoCleanupCursors3");
AutoCleanupCursors3();
Console.WriteLine("DatabaseTest.AutoCleanupCursors4");
AutoCleanupCursors4();
Console.WriteLine("DatabaseTest.ApproxMatching");
ApproxMatching();
}
}
}
| |
//
// CMSampleBuffer.cs: Implements the managed CMSampleBuffer
//
// Authors: Mono Team
// Marek Safar ([email protected])
//
// Copyright 2010 Novell, Inc
// Copyright 2012-2013 Xamarin Inc
//
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using MonoMac;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
using OSStatus = System.Int32;
#if !COREBUILD
using MonoMac.AudioToolbox;
using MonoMac.CoreVideo;
#if !MONOMAC
using MonoTouch.UIKit;
#endif
#endif
namespace MonoMac.CoreMedia {
public enum CMSampleBufferError {
None = 0,
AllocationFailed = -12730,
RequiredParameterMissing = -12731,
AlreadyHasDataBuffer = -12732,
BufferNotReady = -12733,
SampleIndexOutOfRange = -12734,
BufferHasNoSampleSizes = -12735,
BufferHasNoSampleTimingInfo = -12736,
ArrayTooSmall = -12737,
InvalidEntryCount = -12738,
CannotSubdivide = -12739,
SampleTimingInfoInvalid = -12740,
InvalidMediaTypeForOperation = -12741,
InvalidSampleData = -12742,
InvalidMediaFormat = -12743,
Invalidated = -12744,
}
[Since (4,0)]
public class CMSampleBuffer : INativeObject, IDisposable {
internal IntPtr handle;
internal CMSampleBuffer (IntPtr handle)
{
this.handle = handle;
}
[Preserve (Conditional=true)]
internal CMSampleBuffer (IntPtr handle, bool owns)
{
if (!owns)
CFObject.CFRetain (handle);
this.handle = handle;
}
~CMSampleBuffer ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
#if !COREBUILD
[DllImport(Constants.CoreMediaLibrary)]
extern static CMSampleBufferError CMAudioSampleBufferCreateWithPacketDescriptions (
IntPtr allocator,
IntPtr dataBuffer,
bool dataReady,
IntPtr makeDataReadyCallback,
IntPtr makeDataReadyRefcon,
IntPtr formatDescription,
int numSamples,
CMTime sbufPTS,
AudioStreamPacketDescription[] packetDescriptions,
out IntPtr sBufOut);
public static CMSampleBuffer CreateWithPacketDescriptions (CMBlockBuffer dataBuffer, CMFormatDescription formatDescription, int samplesCount,
CMTime sampleTimestamp, AudioStreamPacketDescription[] packetDescriptions, out CMSampleBufferError error)
{
if (formatDescription == null)
throw new ArgumentNullException ("formatDescription");
if (samplesCount <= 0)
throw new ArgumentOutOfRangeException ("samplesCount");
IntPtr buffer;
error = CMAudioSampleBufferCreateWithPacketDescriptions (IntPtr.Zero,
dataBuffer == null ? IntPtr.Zero : dataBuffer.handle,
true, IntPtr.Zero, IntPtr.Zero,
formatDescription.handle,
samplesCount, sampleTimestamp,
packetDescriptions,
out buffer);
if (error != CMSampleBufferError.None)
return null;
return new CMSampleBuffer (buffer, true);
}
[DllImport(Constants.CoreMediaLibrary)]
unsafe static extern OSStatus CMSampleBufferCreateCopyWithNewTiming (
IntPtr allocator,
IntPtr originalSBuf,
int numSampleTimingEntries,
CMSampleTimingInfo* sampleTimingArray,
out IntPtr sBufCopyOut
);
public static CMSampleBuffer CreateWithNewTiming (CMSampleBuffer original, CMSampleTimingInfo [] timing)
{
OSStatus status;
return CreateWithNewTiming (original, timing, out status);
}
public unsafe static CMSampleBuffer CreateWithNewTiming (CMSampleBuffer original, CMSampleTimingInfo [] timing, out OSStatus status)
{
IntPtr handle;
fixed (CMSampleTimingInfo *t = timing)
if ((status = CMSampleBufferCreateCopyWithNewTiming (IntPtr.Zero, original.Handle, timing.Length, t, out handle)) != 0)
return null;
return new CMSampleBuffer (handle, true);
}
/*
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferCallForEachSample (
CMSampleBufferRef sbuf,
int (*callback)(CMSampleBufferRef sampleBuffer, int index, void *refcon),
void *refcon
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferCopySampleBufferForRange (
CFAllocatorRef allocator,
CMSampleBufferRef sbuf,
CFRange sampleRange,
CMSampleBufferRef *sBufOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferCreate (
CFAllocatorRef allocator,
CMBlockBufferRef dataBuffer,
Boolean dataReady,
CMSampleBufferMakeDataReadyCallback makeDataReadyCallback,
void *makeDataReadyRefcon,
CMFormatDescriptionRef formatDescription,
int numSamples,
int numSampleTimingEntries,
const CMSampleTimingInfo *sampleTimingArray,
int numSampleSizeEntries,
const uint *sampleSizeArray,
CMSampleBufferRef *sBufOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferCreateCopy (
CFAllocatorRef allocator,
CMSampleBufferRef sbuf,
CMSampleBufferRef *sbufCopyOut
);
*/
[DllImport(Constants.CoreMediaLibrary)]
static extern CMSampleBufferError CMSampleBufferCreateForImageBuffer (IntPtr allocator,
IntPtr imageBuffer, bool dataReady,
IntPtr makeDataReadyCallback, IntPtr makeDataReadyRefcon,
IntPtr formatDescription,
ref CMSampleTimingInfo sampleTiming,
out IntPtr bufOut
);
public static CMSampleBuffer CreateForImageBuffer (CVImageBuffer imageBuffer, bool dataReady, CMVideoFormatDescription formatDescription, CMSampleTimingInfo sampleTiming, out CMSampleBufferError error)
{
if (imageBuffer == null)
throw new ArgumentNullException ("imageBuffer");
if (formatDescription == null)
throw new ArgumentNullException ("formatDescription");
IntPtr buffer;
error = CMSampleBufferCreateForImageBuffer (IntPtr.Zero,
imageBuffer.handle, dataReady,
IntPtr.Zero, IntPtr.Zero,
formatDescription.handle,
ref sampleTiming,
out buffer);
if (error != CMSampleBufferError.None)
return null;
return new CMSampleBuffer (buffer, true);
}
#endif
[DllImport(Constants.CoreMediaLibrary)]
extern static bool CMSampleBufferDataIsReady (IntPtr handle);
public bool DataIsReady
{
get
{
return CMSampleBufferDataIsReady (handle);
}
}
/*[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer (
CMSampleBufferRef sbuf,
uint *bufferListSizeNeededOut,
AudioBufferList *bufferListOut,
uint bufferListSize,
CFAllocatorRef bbufStructAllocator,
CFAllocatorRef bbufMemoryAllocator,
uint32_t flags,
CMBlockBufferRef *blockBufferOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetAudioStreamPacketDescriptions (
CMSampleBufferRef sbuf,
uint packetDescriptionsSize,
AudioStreamPacketDescription *packetDescriptionsOut,
uint *packetDescriptionsSizeNeededOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetAudioStreamPacketDescriptionsPtr (
CMSampleBufferRef sbuf,
const AudioStreamPacketDescription **packetDescriptionsPtrOut,
uint *packetDescriptionsSizeOut
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMSampleBufferGetDataBuffer (IntPtr handle);
public CMBlockBuffer GetDataBuffer ()
{
var blockHandle = CMSampleBufferGetDataBuffer (handle);
if (blockHandle == IntPtr.Zero)
{
return null;
}
else
{
return new CMBlockBuffer (blockHandle, false);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetDecodeTimeStamp (IntPtr handle);
public CMTime DecodeTimeStamp
{
get
{
return CMSampleBufferGetDecodeTimeStamp (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetDuration (IntPtr handle);
public CMTime Duration
{
get
{
return CMSampleBufferGetDuration (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMSampleBufferGetFormatDescription (IntPtr handle);
[Advice ("Use GetAudioFormatDescription or GetVideoFormatDescription")]
public CMFormatDescription GetFormatDescription ()
{
var desc = default(CMFormatDescription);
var descHandle = CMSampleBufferGetFormatDescription (handle);
if (descHandle != IntPtr.Zero)
{
desc = new CMFormatDescription (descHandle, false);
}
return desc;
}
public CMAudioFormatDescription GetAudioFormatDescription ()
{
var descHandle = CMSampleBufferGetFormatDescription (handle);
if (descHandle == IntPtr.Zero)
return null;
return new CMAudioFormatDescription (descHandle, false);
}
public CMVideoFormatDescription GetVideoFormatDescription ()
{
var descHandle = CMSampleBufferGetFormatDescription (handle);
if (descHandle == IntPtr.Zero)
return null;
return new CMVideoFormatDescription (descHandle, false);
}
#if !COREBUILD
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMSampleBufferGetImageBuffer (IntPtr handle);
public CVImageBuffer GetImageBuffer ()
{
IntPtr ib = CMSampleBufferGetImageBuffer (handle);
if (ib == IntPtr.Zero)
return null;
var ibt = CFType.GetTypeID (ib);
if (ibt == CVPixelBuffer.CVImageBufferType)
return new CVPixelBuffer (ib, false);
return new CVImageBuffer (ib, false);
}
#endif
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMSampleBufferGetNumSamples (IntPtr handle);
public int NumSamples
{
get
{
return CMSampleBufferGetNumSamples (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetOutputDecodeTimeStamp (IntPtr handle);
public CMTime OutputDecodeTimeStamp
{
get
{
return CMSampleBufferGetOutputDecodeTimeStamp (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetOutputDuration (IntPtr handle);
public CMTime OutputDuration
{
get
{
return CMSampleBufferGetOutputDuration (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetOutputPresentationTimeStamp (IntPtr handle);
public CMTime OutputPresentationTimeStamp
{
get
{
return CMSampleBufferGetOutputPresentationTimeStamp (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMSampleBufferError CMSampleBufferSetOutputPresentationTimeStamp (IntPtr handle, CMTime outputPresentationTimeStamp);
public int /*CMSampleBufferError*/ SetOutputPresentationTimeStamp (CMTime outputPresentationTimeStamp)
{
return (int)CMSampleBufferSetOutputPresentationTimeStamp (handle, outputPresentationTimeStamp);
}
/*[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetOutputSampleTimingInfoArray (
CMSampleBufferRef sbuf,
int timingArrayEntries,
CMSampleTimingInfo *timingArrayOut,
int *timingArrayEntriesNeededOut
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetPresentationTimeStamp (IntPtr handle);
public CMTime PresentationTimeStamp
{
get
{
return CMSampleBufferGetPresentationTimeStamp (handle);
}
}
#if !COREBUILD
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMSampleBufferGetSampleAttachmentsArray (IntPtr handle, bool createIfNecessary);
public CMSampleBufferAttachmentSettings [] GetSampleAttachments (bool createIfNecessary)
{
var cfArrayRef = CMSampleBufferGetSampleAttachmentsArray (handle, createIfNecessary);
if (cfArrayRef == IntPtr.Zero)
{
return new CMSampleBufferAttachmentSettings [0];
}
else
{
return NSArray.ArrayFromHandle (cfArrayRef, h => new CMSampleBufferAttachmentSettings ((NSMutableDictionary) Runtime.GetNSObject (h)));
}
}
#endif
[DllImport(Constants.CoreMediaLibrary)]
extern static uint CMSampleBufferGetSampleSize (IntPtr handle, int sampleIndex);
public uint GetSampleSize (int sampleIndex)
{
return CMSampleBufferGetSampleSize (handle, sampleIndex);
}
/*[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetSampleSizeArray (
CMSampleBufferRef sbuf,
int sizeArrayEntries,
uint *sizeArrayOut,
int *sizeArrayEntriesNeededOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetSampleTimingInfo (
CMSampleBufferRef sbuf,
int sampleIndex,
CMSampleTimingInfo *timingInfoOut
);
*/
[DllImport(Constants.CoreMediaLibrary)]
unsafe static extern OSStatus CMSampleBufferGetSampleTimingInfoArray (
IntPtr sbuf,
int timingArrayEntries,
CMSampleTimingInfo* timingArrayOut,
out int timingArrayEntriesNeededOut
);
#if !COREBUILD
public CMSampleTimingInfo [] GetSampleTimingInfo ()
{
OSStatus status;
return GetSampleTimingInfo (out status);
}
public unsafe CMSampleTimingInfo [] GetSampleTimingInfo (out OSStatus status) {
int count;
status = 0;
if (handle == IntPtr.Zero)
return null;
if ((status = CMSampleBufferGetSampleTimingInfoArray (handle, 0, null, out count)) != 0)
return null;
CMSampleTimingInfo [] pInfo = new CMSampleTimingInfo [count];
if (count == 0)
return pInfo;
fixed (CMSampleTimingInfo* info = pInfo)
if ((status = CMSampleBufferGetSampleTimingInfoArray (handle, count, info, out count)) != 0)
return null;
return pInfo;
}
static string OSStatusToString (OSStatus status)
{
return new NSError (NSError.OsStatusErrorDomain, status).LocalizedDescription;
}
#endif
[DllImport(Constants.CoreMediaLibrary)]
extern static uint CMSampleBufferGetTotalSampleSize (IntPtr handle);
public uint TotalSampleSize
{
get
{
return CMSampleBufferGetTotalSampleSize (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMSampleBufferGetTypeID ();
public static int GetTypeID ()
{
return CMSampleBufferGetTypeID ();
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMSampleBufferError CMSampleBufferInvalidate (IntPtr handle);
public int /*CMSampleBufferError*/ Invalidate()
{
return (int)CMSampleBufferInvalidate (handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static bool CMSampleBufferIsValid (IntPtr handle);
public bool IsValid
{
get
{
return CMSampleBufferIsValid (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMSampleBufferError CMSampleBufferMakeDataReady (IntPtr handle);
public int /*CMSampleBufferError*/ MakeDataReady ()
{
return (int)CMSampleBufferMakeDataReady (handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMSampleBufferError CMSampleBufferSetDataBuffer (IntPtr handle, IntPtr dataBufferHandle);
public int /*CMSampleBufferError*/ SetDataBuffer (CMBlockBuffer dataBuffer)
{
var dataBufferHandle = IntPtr.Zero;
if (dataBuffer != null)
{
dataBufferHandle = dataBuffer.handle;
}
return (int)CMSampleBufferSetDataBuffer (handle, dataBufferHandle);
}
/*[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferSetDataBufferFromAudioBufferList (
CMSampleBufferRef sbuf,
CFAllocatorRef bbufStructAllocator,
CFAllocatorRef bbufMemoryAllocator,
uint32_t flags,
const AudioBufferList *bufferList
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static CMSampleBufferError CMSampleBufferSetDataReady (IntPtr handle);
public int/*CMSampleBufferError*/ SetDataReady ()
{
return (int)CMSampleBufferSetDataReady (handle);
}
/*[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferSetInvalidateCallback (
CMSampleBufferRef sbuf,
CMSampleBufferInvalidateCallback invalidateCallback,
uint64_t invalidateRefCon
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static CMSampleBufferError CMSampleBufferTrackDataReadiness (IntPtr handle, IntPtr handleToTrack);
public int/*CMSampleBufferError*/ TrackDataReadiness (CMSampleBuffer bufferToTrack)
{
var handleToTrack = IntPtr.Zero;
if (bufferToTrack != null) {
handleToTrack = bufferToTrack.handle;
}
return (int)CMSampleBufferTrackDataReadiness (handle, handleToTrack);
}
}
#if !COREBUILD
public class CMSampleBufferAttachmentSettings : DictionaryContainer
{
static class Selectors
{
public static readonly NSString NotSync;
public static readonly NSString PartialSync;
public static readonly NSString HasRedundantCoding;
public static readonly NSString IsDependedOnByOthers;
public static readonly NSString DependsOnOthers;
public static readonly NSString EarlierDisplayTimesAllowed;
public static readonly NSString DisplayImmediately;
public static readonly NSString DoNotDisplay;
public static readonly NSString ResetDecoderBeforeDecoding;
public static readonly NSString DrainAfterDecoding;
public static readonly NSString PostNotificationWhenConsumed;
public static readonly NSString ResumeOutput;
public static readonly NSString TransitionID;
public static readonly NSString TrimDurationAtStart;
public static readonly NSString TrimDurationAtEnd;
public static readonly NSString SpeedMultiplier;
public static readonly NSString Reverse;
public static readonly NSString FillDiscontinuitiesWithSilence;
public static readonly NSString EmptyMedia;
public static readonly NSString PermanentEmptyMedia;
public static readonly NSString DisplayEmptyMediaImmediately;
public static readonly NSString EndsPreviousSampleDuration;
public static readonly NSString SampleReferenceURL;
public static readonly NSString SampleReferenceByteOffset;
public static readonly NSString GradualDecoderRefresh;
#if !MONOMAC
// Since 6,0
public static readonly NSString DroppedFrameReason;
#endif
static Selectors ()
{
var handle = Dlfcn.dlopen (Constants.CoreMediaLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
NotSync = Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_NotSync");
PartialSync = Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_PartialSync");
HasRedundantCoding = Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_HasRedundantCoding");
IsDependedOnByOthers = Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_IsDependedOnByOthers");
DependsOnOthers = Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_DependsOnOthers");
EarlierDisplayTimesAllowed = Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_EarlierDisplayTimesAllowed");
DisplayImmediately = Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_DisplayImmediately");
DoNotDisplay = Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_DoNotDisplay");
ResetDecoderBeforeDecoding = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_ResetDecoderBeforeDecoding");
DrainAfterDecoding = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_DrainAfterDecoding");
PostNotificationWhenConsumed = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_PostNotificationWhenConsumed");
ResumeOutput = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_ResumeOutput");
TransitionID = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_TransitionID");
TrimDurationAtStart = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_TrimDurationAtStart");
TrimDurationAtEnd = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_TrimDurationAtEnd");
SpeedMultiplier = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_SpeedMultiplier");
Reverse = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_Reverse");
FillDiscontinuitiesWithSilence = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_FillDiscontinuitiesWithSilence");
EmptyMedia = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_EmptyMedia");
PermanentEmptyMedia = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_PermanentEmptyMedia");
DisplayEmptyMediaImmediately = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_DisplayEmptyMediaImmediately");
EndsPreviousSampleDuration = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_EndsPreviousSampleDuration");
SampleReferenceURL = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_SampleReferenceURL");
SampleReferenceByteOffset = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_SampleReferenceByteOffset");
GradualDecoderRefresh = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_GradualDecoderRefresh");
#if !MONOMAC
var version = new Version (UIDevice.CurrentDevice.SystemVersion);
if (version.Major >= 6) {
DroppedFrameReason = Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_DroppedFrameReason");
}
#endif
} finally {
Dlfcn.dlclose (handle);
}
}
}
internal CMSampleBufferAttachmentSettings (NSMutableDictionary dictionary)
: base (dictionary)
{
}
public bool? NotSync {
get {
return GetBoolValue (Selectors.NotSync);
}
set {
SetBooleanValue (Selectors.NotSync, value);
}
}
public bool? PartialSync {
get {
return GetBoolValue (Selectors.PartialSync);
}
set {
SetBooleanValue (Selectors.PartialSync, value);
}
}
public bool? RedundantCoding {
get {
return GetBoolValue (Selectors.HasRedundantCoding);
}
set {
SetBooleanValue (Selectors.HasRedundantCoding, value);
}
}
public bool? DependedOnByOthers {
get {
return GetBoolValue (Selectors.IsDependedOnByOthers);
}
set {
SetBooleanValue (Selectors.IsDependedOnByOthers, value);
}
}
public bool? DependsOnOthers {
get {
return GetBoolValue (Selectors.DependsOnOthers);
}
set {
SetBooleanValue (Selectors.DependsOnOthers, value);
}
}
public bool? EarlierDisplayTimesAllowed {
get {
return GetBoolValue (Selectors.EarlierDisplayTimesAllowed);
}
set {
SetBooleanValue (Selectors.EarlierDisplayTimesAllowed, value);
}
}
public bool? DisplayImmediately {
get {
return GetBoolValue (Selectors.DisplayImmediately);
}
set {
SetBooleanValue (Selectors.DisplayImmediately, value);
}
}
public bool? DoNotDisplay {
get {
return GetBoolValue (Selectors.DoNotDisplay);
}
set {
SetBooleanValue (Selectors.DoNotDisplay, value);
}
}
public bool? ResetDecoderBeforeDecoding {
get {
return GetBoolValue (Selectors.ResetDecoderBeforeDecoding);
}
set {
SetBooleanValue (Selectors.ResetDecoderBeforeDecoding, value);
}
}
public bool? DrainAfterDecoding {
get {
return GetBoolValue (Selectors.DrainAfterDecoding);
}
set {
SetBooleanValue (Selectors.DrainAfterDecoding, value);
}
}
public bool? Reverse {
get {
return GetBoolValue (Selectors.Reverse);
}
set {
SetBooleanValue (Selectors.Reverse, value);
}
}
public bool? FillDiscontinuitiesWithSilence {
get {
return GetBoolValue (Selectors.FillDiscontinuitiesWithSilence);
}
set {
SetBooleanValue (Selectors.FillDiscontinuitiesWithSilence, value);
}
}
public bool? EmptyMedia {
get {
return GetBoolValue (Selectors.EmptyMedia);
}
set {
SetBooleanValue (Selectors.EmptyMedia, value);
}
}
public bool? PermanentEmptyMedia {
get {
return GetBoolValue (Selectors.PermanentEmptyMedia);
}
set {
SetBooleanValue (Selectors.PermanentEmptyMedia, value);
}
}
public bool? DisplayEmptyMediaImmediately {
get {
return GetBoolValue (Selectors.DisplayEmptyMediaImmediately);
}
set {
SetBooleanValue (Selectors.DisplayEmptyMediaImmediately, value);
}
}
public bool? EndsPreviousSampleDuration {
get {
return GetBoolValue (Selectors.EndsPreviousSampleDuration);
}
set {
SetBooleanValue (Selectors.EndsPreviousSampleDuration, value);
}
}
#if !MONOMAC
[Since (6,0)]
public string DroppedFrameReason {
get {
return GetStringValue (Selectors.DroppedFrameReason);
}
}
#endif
// TODO: Implement remaining selector properties
// PostNotificationWhenConsumed
// ResumeOutput
// TransitionID
// TrimDurationAtStart
// TrimDurationAtEnd
// SpeedMultiplier
// SampleReferenceURL
// SampleReferenceByteOffset
// GradualDecoderRefresh
}
#endif
}
| |
using System;
using System.Collections.Generic;
using TriangleNet;
using TriangleNet.Data;
using TriangleNet.Geometry;
namespace TriangleNet.Tools
{
public class BoundedVoronoi : IVoronoi
{
private Mesh mesh;
private Point[] points;
private List<VoronoiRegion> regions;
private int segIndex;
private Dictionary<int, Segment> subsegMap;
private bool includeBoundary = true;
public Point[] Points
{
get
{
return this.points;
}
}
public List<VoronoiRegion> Regions
{
get
{
return this.regions;
}
}
public BoundedVoronoi(Mesh mesh) : this(mesh, true)
{
}
public BoundedVoronoi(Mesh mesh, bool includeBoundary)
{
this.mesh = mesh;
this.includeBoundary = includeBoundary;
this.Generate();
}
private void ComputeCircumCenters()
{
Otri otri = new Otri();
double num = 0;
double num1 = 0;
foreach (Triangle value in this.mesh.triangles.Values)
{
otri.triangle = value;
Point point = Primitives.FindCircumcenter(otri.Org(), otri.Dest(), otri.Apex(), ref num, ref num1);
point.id = value.id;
this.points[value.id] = point;
}
}
private void ConstructBoundaryBvdCell(Vertex vertex)
{
Vertex vertex1;
Point point;
VoronoiRegion voronoiRegion = new VoronoiRegion(vertex);
this.regions.Add(voronoiRegion);
Otri otri = new Otri();
Otri otri1 = new Otri();
Otri otri2 = new Otri();
Otri otri3 = new Otri();
Osub item = new Osub();
Osub osub = new Osub();
int count = this.mesh.triangles.Count;
List<Point> points = new List<Point>();
vertex.tri.Copy(ref otri1);
if (otri1.Org() != vertex)
{
throw new Exception("ConstructBoundaryBvdCell: inconsistent topology.");
}
otri1.Copy(ref otri);
otri1.Onext(ref otri2);
otri1.Oprev(ref otri3);
if (otri3.triangle != Mesh.dummytri)
{
while (otri3.triangle != Mesh.dummytri && !otri3.Equal(otri1))
{
otri3.Copy(ref otri);
otri3.OprevSelf();
}
otri.Copy(ref otri1);
otri.Onext(ref otri2);
}
if (otri3.triangle == Mesh.dummytri)
{
point = new Point(vertex.x, vertex.y)
{
id = count + this.segIndex
};
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
Vertex vertex2 = otri.Org();
Vertex vertex3 = otri.Dest();
point = new Point((vertex2.X + vertex3.X) / 2, (vertex2.Y + vertex3.Y) / 2)
{
id = count + this.segIndex
};
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
do
{
Point point1 = this.points[otri.triangle.id];
if (otri2.triangle != Mesh.dummytri)
{
Point point2 = this.points[otri2.triangle.id];
if (otri.triangle.infected)
{
item.seg = this.subsegMap[otri.triangle.hash];
Vertex vertex4 = item.SegOrg();
Vertex vertex5 = item.SegDest();
if (otri2.triangle.infected)
{
osub.seg = this.subsegMap[otri2.triangle.hash];
if (!item.Equal(osub))
{
if (this.SegmentsIntersect(vertex4, vertex5, point1, point2, out point, true))
{
point.id = count + this.segIndex;
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
if (this.SegmentsIntersect(osub.SegOrg(), osub.SegDest(), point1, point2, out point, true))
{
point.id = count + this.segIndex;
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
}
else if (this.SegmentsIntersect(vertex4, vertex5, new Point((vertex2.X + vertex3.X) / 2, (vertex2.Y + vertex3.Y) / 2), point2, out point, false))
{
point.id = count + this.segIndex;
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
}
else
{
vertex3 = otri.Dest();
vertex1 = otri.Apex();
if (this.SegmentsIntersect(vertex4, vertex5, new Point((vertex3.X + vertex1.X) / 2, (vertex3.Y + vertex1.Y) / 2), point1, out point, false))
{
point.id = count + this.segIndex;
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
if (this.SegmentsIntersect(vertex4, vertex5, point1, point2, out point, true))
{
point.id = count + this.segIndex;
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
}
}
else
{
points.Add(point1);
if (otri2.triangle.infected)
{
osub.seg = this.subsegMap[otri2.triangle.hash];
if (this.SegmentsIntersect(osub.SegOrg(), osub.SegDest(), point1, point2, out point, true))
{
point.id = count + this.segIndex;
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
}
}
otri2.Copy(ref otri);
otri2.OnextSelf();
}
else
{
if (!otri.triangle.infected)
{
points.Add(point1);
}
vertex2 = otri.Org();
vertex1 = otri.Apex();
point = new Point((vertex2.X + vertex1.X) / 2, (vertex2.Y + vertex1.Y) / 2)
{
id = count + this.segIndex
};
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
break;
}
}
while (!otri.Equal(otri1));
voronoiRegion.Add(points);
}
private void ConstructBvdCell(Vertex vertex)
{
Point point;
VoronoiRegion voronoiRegion = new VoronoiRegion(vertex);
this.regions.Add(voronoiRegion);
Otri otri = new Otri();
Otri otri1 = new Otri();
Otri otri2 = new Otri();
Osub item = new Osub();
Osub osub = new Osub();
int count = this.mesh.triangles.Count;
List<Point> points = new List<Point>();
vertex.tri.Copy(ref otri1);
if (otri1.Org() != vertex)
{
throw new Exception("ConstructBvdCell: inconsistent topology.");
}
otri1.Copy(ref otri);
otri1.Onext(ref otri2);
do
{
Point point1 = this.points[otri.triangle.id];
Point point2 = this.points[otri2.triangle.id];
if (otri.triangle.infected)
{
item.seg = this.subsegMap[otri.triangle.hash];
if (otri2.triangle.infected)
{
osub.seg = this.subsegMap[otri2.triangle.hash];
if (!item.Equal(osub))
{
if (this.SegmentsIntersect(item.SegOrg(), item.SegDest(), point1, point2, out point, true))
{
point.id = count + this.segIndex;
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
if (this.SegmentsIntersect(osub.SegOrg(), osub.SegDest(), point1, point2, out point, true))
{
point.id = count + this.segIndex;
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
}
}
else if (this.SegmentsIntersect(item.SegOrg(), item.SegDest(), point1, point2, out point, true))
{
point.id = count + this.segIndex;
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
}
else
{
points.Add(point1);
if (otri2.triangle.infected)
{
osub.seg = this.subsegMap[otri2.triangle.hash];
if (this.SegmentsIntersect(osub.SegOrg(), osub.SegDest(), point1, point2, out point, true))
{
point.id = count + this.segIndex;
this.points[count + this.segIndex] = point;
this.segIndex = this.segIndex + 1;
points.Add(point);
}
}
}
otri2.Copy(ref otri);
otri2.OnextSelf();
}
while (!otri.Equal(otri1));
voronoiRegion.Add(points);
}
private void Generate()
{
this.mesh.Renumber();
this.mesh.MakeVertexMap();
this.points = new Point[this.mesh.triangles.Count + this.mesh.subsegs.Count * 5];
this.regions = new List<VoronoiRegion>(this.mesh.vertices.Count);
this.ComputeCircumCenters();
this.TagBlindTriangles();
foreach (Vertex value in this.mesh.vertices.Values)
{
if (value.type == VertexType.FreeVertex || value.Boundary == 0)
{
this.ConstructBvdCell(value);
}
else
{
if (!this.includeBoundary)
{
continue;
}
this.ConstructBoundaryBvdCell(value);
}
}
}
private bool SegmentsIntersect(Point p1, Point p2, Point p3, Point p4, out Point p, bool strictIntersect)
{
p = null;
double x = p1.X;
double y = p1.Y;
double num = p2.X;
double y1 = p2.Y;
double x1 = p3.X;
double num1 = p3.Y;
double x2 = p4.X;
double y2 = p4.Y;
if (x == num && y == y1 || x1 == x2 && num1 == y2)
{
return false;
}
if (x == x1 && y == num1 || num == x1 && y1 == num1 || x == x2 && y == y2 || num == x2 && y1 == y2)
{
return false;
}
num = num - x;
y1 = y1 - y;
x1 = x1 - x;
num1 = num1 - y;
x2 = x2 - x;
y2 = y2 - y;
double num2 = Math.Sqrt(num * num + y1 * y1);
double num3 = num / num2;
double num4 = y1 / num2;
double num5 = x1 * num3 + num1 * num4;
num1 = num1 * num3 - x1 * num4;
x1 = num5;
double num6 = x2 * num3 + y2 * num4;
y2 = y2 * num3 - x2 * num4;
x2 = num6;
if (num1 >= 0 || y2 >= 0)
{
if (!((num1 < 0 ? false : y2 >= 0) & strictIntersect))
{
double num7 = x2 + (x1 - x2) * y2 / (y2 - num1);
if (num7 < 0 || num7 > num2 & strictIntersect)
{
return false;
}
p = new Point(x + num7 * num3, y + num7 * num4);
return true;
}
}
return false;
}
private void TagBlindTriangles()
{
int num = 0;
this.subsegMap = new Dictionary<int, Segment>();
Otri otri = new Otri();
Otri otri1 = new Otri();
Osub osub = new Osub();
Osub osub1 = new Osub();
foreach (Triangle value in this.mesh.triangles.Values)
{
value.infected = false;
}
foreach (Segment segment in this.mesh.subsegs.Values)
{
Stack<Triangle> triangles = new Stack<Triangle>();
osub.seg = segment;
osub.orient = 0;
osub.TriPivot(ref otri);
if (otri.triangle != Mesh.dummytri && !otri.triangle.infected)
{
triangles.Push(otri.triangle);
}
osub.SymSelf();
osub.TriPivot(ref otri);
if (otri.triangle != Mesh.dummytri && !otri.triangle.infected)
{
triangles.Push(otri.triangle);
}
while (triangles.Count > 0)
{
otri.triangle = triangles.Pop();
otri.orient = 0;
if (!this.TriangleIsBlinded(ref otri, ref osub))
{
continue;
}
otri.triangle.infected = true;
num++;
this.subsegMap.Add(otri.triangle.hash, osub.seg);
otri.orient = 0;
while (otri.orient < 3)
{
otri.Sym(ref otri1);
otri1.SegPivot(ref osub1);
if (otri1.triangle != Mesh.dummytri && !otri1.triangle.infected && osub1.seg == Mesh.dummysub)
{
triangles.Push(otri1.triangle);
}
otri.orient = otri.orient + 1;
}
}
}
num = 0;
}
private bool TriangleIsBlinded(ref Otri tri, ref Osub seg)
{
Point point;
Vertex vertex = tri.Org();
Vertex vertex1 = tri.Dest();
Vertex vertex2 = tri.Apex();
Vertex vertex3 = seg.Org();
Vertex vertex4 = seg.Dest();
Point point1 = this.points[tri.triangle.id];
if (this.SegmentsIntersect(vertex3, vertex4, point1, vertex, out point, true))
{
return true;
}
if (this.SegmentsIntersect(vertex3, vertex4, point1, vertex1, out point, true))
{
return true;
}
if (this.SegmentsIntersect(vertex3, vertex4, point1, vertex2, out point, true))
{
return true;
}
return false;
}
}
}
| |
// <copyright file="DesiredCapabilities.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// Internal class to specify the requested capabilities of the browser for <see cref="IWebDriver"/>.
/// </summary>
internal class DesiredCapabilities : IWritableCapabilities, IHasCapabilitiesDictionary
{
private readonly Dictionary<string, object> capabilities = new Dictionary<string, object>();
/// <summary>
/// Initializes a new instance of the <see cref="DesiredCapabilities"/> class
/// </summary>
/// <param name="browser">Name of the browser e.g. firefox, internet explorer, safari</param>
/// <param name="version">Version of the browser</param>
/// <param name="platform">The platform it works on</param>
public DesiredCapabilities(string browser, string version, Platform platform)
{
this.SetCapability(CapabilityType.BrowserName, browser);
this.SetCapability(CapabilityType.Version, version);
this.SetCapability(CapabilityType.Platform, platform);
}
/// <summary>
/// Initializes a new instance of the <see cref="DesiredCapabilities"/> class
/// </summary>
public DesiredCapabilities()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DesiredCapabilities"/> class
/// </summary>
/// <param name="rawMap">Dictionary of items for the remote driver</param>
/// <example>
/// <code>
/// DesiredCapabilities capabilities = new DesiredCapabilities(new Dictionary<![CDATA[<string,object>]]>(){["browserName","firefox"],["version",string.Empty],["javaScript",true]});
/// </code>
/// </example>
public DesiredCapabilities(Dictionary<string, object> rawMap)
{
if (rawMap != null)
{
foreach (string key in rawMap.Keys)
{
if (key == CapabilityType.Platform)
{
object raw = rawMap[CapabilityType.Platform];
string rawAsString = raw as string;
Platform rawAsPlatform = raw as Platform;
if (rawAsString != null)
{
this.SetCapability(CapabilityType.Platform, Platform.FromString(rawAsString));
}
else if (rawAsPlatform != null)
{
this.SetCapability(CapabilityType.Platform, rawAsPlatform);
}
}
else
{
this.SetCapability(key, rawMap[key]);
}
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DesiredCapabilities"/> class
/// </summary>
/// <param name="browser">Name of the browser e.g. firefox, internet explorer, safari</param>
/// <param name="version">Version of the browser</param>
/// <param name="platform">The platform it works on</param>
/// <param name="isSpecCompliant">Sets a value indicating whether the capabilities are
/// compliant with the W3C WebDriver specification.</param>
internal DesiredCapabilities(string browser, string version, Platform platform, bool isSpecCompliant)
{
this.SetCapability(CapabilityType.BrowserName, browser);
this.SetCapability(CapabilityType.Version, version);
this.SetCapability(CapabilityType.Platform, platform);
}
/// <summary>
/// Gets the browser name
/// </summary>
public string BrowserName
{
get
{
string name = string.Empty;
object capabilityValue = this.GetCapability(CapabilityType.BrowserName);
if (capabilityValue != null)
{
name = capabilityValue.ToString();
}
return name;
}
}
/// <summary>
/// Gets or sets the platform
/// </summary>
public Platform Platform
{
get
{
return this.GetCapability(CapabilityType.Platform) as Platform ?? new Platform(PlatformType.Any);
}
set
{
this.SetCapability(CapabilityType.Platform, value);
}
}
/// <summary>
/// Gets the browser version
/// </summary>
public string Version
{
get
{
string browserVersion = string.Empty;
object capabilityValue = this.GetCapability(CapabilityType.Version);
if (capabilityValue != null)
{
browserVersion = capabilityValue.ToString();
}
return browserVersion;
}
}
/// <summary>
/// Gets or sets a value indicating whether the browser accepts SSL certificates.
/// </summary>
public bool AcceptInsecureCerts
{
get
{
bool acceptSSLCerts = false;
object capabilityValue = this.GetCapability(CapabilityType.AcceptInsecureCertificates);
if (capabilityValue != null)
{
acceptSSLCerts = (bool)capabilityValue;
}
return acceptSSLCerts;
}
set
{
this.SetCapability(CapabilityType.AcceptInsecureCertificates, value);
}
}
/// <summary>
/// Gets the underlying Dictionary for a given set of capabilities.
/// </summary>
IDictionary<string, object> IHasCapabilitiesDictionary.CapabilitiesDictionary
{
get { return this.CapabilitiesDictionary; }
}
/// <summary>
/// Gets the underlying Dictionary for a given set of capabilities.
/// </summary>
internal IDictionary<string, object> CapabilitiesDictionary
{
get { return new ReadOnlyDictionary<string, object>(this.capabilities); }
}
/// <summary>
/// Gets the capability value with the specified name.
/// </summary>
/// <param name="capabilityName">The name of the capability to get.</param>
/// <returns>The value of the capability.</returns>
/// <exception cref="ArgumentException">
/// The specified capability name is not in the set of capabilities.
/// </exception>
public object this[string capabilityName]
{
get
{
if (!this.capabilities.ContainsKey(capabilityName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The capability {0} is not present in this set of capabilities", capabilityName));
}
return this.capabilities[capabilityName];
}
}
/// <summary>
/// Gets a value indicating whether the browser has a given capability.
/// </summary>
/// <param name="capability">The capability to get.</param>
/// <returns>Returns <see langword="true"/> if the browser has the capability; otherwise, <see langword="false"/>.</returns>
public bool HasCapability(string capability)
{
return this.capabilities.ContainsKey(capability);
}
/// <summary>
/// Gets a capability of the browser.
/// </summary>
/// <param name="capability">The capability to get.</param>
/// <returns>An object associated with the capability, or <see langword="null"/>
/// if the capability is not set on the browser.</returns>
public object GetCapability(string capability)
{
object capabilityValue = null;
if (this.capabilities.ContainsKey(capability))
{
capabilityValue = this.capabilities[capability];
string capabilityValueString = capabilityValue as string;
if (capability == CapabilityType.Platform && capabilityValueString != null)
{
capabilityValue = Platform.FromString(capabilityValue.ToString());
}
}
return capabilityValue;
}
/// <summary>
/// Sets a capability of the browser.
/// </summary>
/// <param name="capability">The capability to get.</param>
/// <param name="capabilityValue">The value for the capability.</param>
public void SetCapability(string capability, object capabilityValue)
{
// Handle the special case of Platform objects. These should
// be stored in the underlying dictionary as their protocol
// string representation.
Platform platformCapabilityValue = capabilityValue as Platform;
if (platformCapabilityValue != null)
{
this.capabilities[capability] = platformCapabilityValue.ProtocolPlatformType;
}
else
{
this.capabilities[capability] = capabilityValue;
}
}
/// <summary>
/// Return HashCode for the DesiredCapabilities that has been created
/// </summary>
/// <returns>Integer of HashCode generated</returns>
public override int GetHashCode()
{
int result;
result = this.BrowserName != null ? this.BrowserName.GetHashCode() : 0;
result = (31 * result) + (this.Version != null ? this.Version.GetHashCode() : 0);
result = (31 * result) + (this.Platform != null ? this.Platform.GetHashCode() : 0);
return result;
}
/// <summary>
/// Return a string of capabilities being used
/// </summary>
/// <returns>String of capabilities being used</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "Capabilities [BrowserName={0}, Platform={1}, Version={2}]", this.BrowserName, this.Platform.PlatformType.ToString(), this.Version);
}
/// <summary>
/// Compare two DesiredCapabilities and will return either true or false
/// </summary>
/// <param name="obj">DesiredCapabilities you wish to compare</param>
/// <returns>true if they are the same or false if they are not</returns>
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
DesiredCapabilities other = obj as DesiredCapabilities;
if (other == null)
{
return false;
}
if (this.BrowserName != null ? this.BrowserName != other.BrowserName : other.BrowserName != null)
{
return false;
}
if (!this.Platform.IsPlatformType(other.Platform.PlatformType))
{
return false;
}
if (this.Version != null ? this.Version != other.Version : other.Version != null)
{
return false;
}
return true;
}
/// <summary>
/// Returns a read-only version of this capabilities object.
/// </summary>
/// <returns>A read-only version of this capabilities object.</returns>
public ICapabilities AsReadOnly()
{
ReadOnlyDesiredCapabilities readOnlyCapabilities = new ReadOnlyDesiredCapabilities(this);
return readOnlyCapabilities;
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Activities.Presentation.Internal.PropertyEditing.Model
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Activities.Presentation.Model;
// <summary>
// Helper class that knows how to merge ModelProperties across multiple ModelItems
// </summary>
internal static class ModelPropertyMerger
{
private static IEnumerable<IList<ModelProperty>> _emptyCollection;
private static IEnumerable<IList<ModelProperty>> EmptyCollection
{
get
{
if (_emptyCollection == null)
{
_emptyCollection = new List<IList<ModelProperty>>();
}
return _emptyCollection;
}
}
// <summary>
// Uber method that returns a list of list of ModelProperties that represent the
// merged set of properties across the specified ModelItems
// </summary>
// <param name="items">ModelItems to examine</param>
// <param name="itemCount">Count on ModelItems to examine</param>
// <returns>List of list of merged properties</returns>
public static IEnumerable<IList<ModelProperty>> GetMergedProperties(IEnumerable<ModelItem> items, int itemCount)
{
return GetMergedPropertiesHelper(new ModelItemExpander(items, itemCount));
}
// <summary>
// Uber method that returns a list of list of ModelProperties that represent the
// merged set of sub-properties across the values of the specified parent properties
// </summary>
// <param name="parentProperties">ModelProperties to examine</param>
// <returns>List of list of merged properties</returns>
public static IEnumerable<IList<ModelProperty>> GetMergedSubProperties(ICollection<ModelProperty> parentProperties)
{
return GetMergedPropertiesHelper(new SubPropertyExpander(parentProperties));
}
// <summary>
// Finds the consolidated default property name and returns it. If there is no shared
// default property betweem the specified items, null is returned.
// </summary>
// <param name="items">Items to examine</param>
// <returns>Shared default property, if any.</returns>
public static string GetMergedDefaultProperty(IEnumerable<ModelItem> items)
{
if (items == null)
{
return null;
}
bool firstIteration = true;
string mergedDefaultProperty = null;
foreach (ModelItem item in items)
{
string currentDefaultProperty = ExtensibilityAccessor.GetDefaultProperty(item.ItemType);
if (firstIteration)
{
mergedDefaultProperty = currentDefaultProperty;
}
else if (!string.Equals(currentDefaultProperty, mergedDefaultProperty))
{
mergedDefaultProperty = null;
}
if (string.IsNullOrEmpty(mergedDefaultProperty))
{
return null;
}
firstIteration = false;
}
return mergedDefaultProperty;
}
// Optimization that speeds up the common case (single selection)
private static IEnumerable<IList<ModelProperty>> GetMergedPropertiesHelper(PropertyExpander expander)
{
// Check empty list
if (expander == null || expander.ContainerCount == 0)
{
return EmptyCollection;
}
if (expander.ContainerCount == 1)
{
// Corner case - one object selected, don't bother with merging
return GetFirstProperties(expander);
}
else
{
// Calculate the list anew
return GetMergedPropertiesCore(expander);
}
}
// Optimization that speeds up the common case (single selection)
private static IEnumerable<IList<ModelProperty>> GetFirstProperties(PropertyExpander expander)
{
IEnumerator<IEnumerable<ModelProperty>> propertyContainers = expander.GetEnumerator();
propertyContainers.MoveNext();
if (propertyContainers.Current != null)
{
foreach (ModelProperty property in propertyContainers.Current)
{
yield return new ModelProperty[] { property };
}
}
}
private static IEnumerable<IList<ModelProperty>> GetMergedPropertiesCore(PropertyExpander expander)
{
Dictionary<string, IList<ModelProperty>> counter = new Dictionary<string, IList<ModelProperty>>();
int containerCounter = 0;
foreach (IEnumerable<ModelProperty> properties in expander)
{
if (properties == null)
{
yield break;
}
foreach (ModelProperty property in properties)
{
IList<ModelProperty> existingModelPropertiesForProperty;
if (!counter.TryGetValue(property.Name, out existingModelPropertiesForProperty))
{
if (containerCounter == 0)
{
existingModelPropertiesForProperty = new List<ModelProperty>(expander.ContainerCount);
counter[property.Name] = existingModelPropertiesForProperty;
}
else
{
// This property has not been encountered yet in the previous objects,
// so skip it altogether.
continue;
}
}
if (existingModelPropertiesForProperty.Count < containerCounter)
{
// There has been a ModelItem in the list that didn't have this property,
// so delete any record of it and skip it in the future.
counter.Remove(property.Name);
continue;
}
// Verify that the properties are equivalent
if (containerCounter > 0 &&
!ModelUtilities.AreEquivalent(
existingModelPropertiesForProperty[containerCounter - 1], property))
{
// They are not, so scrap this property altogether
counter.Remove(property.Name);
continue;
}
existingModelPropertiesForProperty.Add(property);
}
containerCounter++;
}
foreach (KeyValuePair<string, IList<ModelProperty>> pair in counter)
{
// Once again, if there is a property that is not shared by all
// selected items, ignore it
if (pair.Value.Count < containerCounter)
{
continue;
}
// We should not set the same instance to multiple properties,
// so ignore types that are not value type or string in case of multi-selection
if (pair.Value.Count > 1 && !(pair.Value[0].PropertyType.IsValueType || pair.Value[0].PropertyType.Equals(typeof(string))))
{
continue;
}
yield return (IList<ModelProperty>)pair.Value;
}
}
// <summary>
// We use the same code to merge properties across a set of ModelItems as well
// as to merge sub-properties across a set of ModelProperties. PropertyExpander
// class is a helper that abstracts the difference between these two inputs, so
// that the merge methods don't have to worry about it.
// </summary>
private abstract class PropertyExpander : IEnumerable<IEnumerable<ModelProperty>>
{
public abstract int ContainerCount
{ get; }
public abstract IEnumerator<IEnumerable<ModelProperty>> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
// <summary>
// Version of PropertyExpander that returns the properties of a set of ModelItems
// </summary>
private class ModelItemExpander : PropertyExpander
{
private IEnumerable<ModelItem> _items;
private int _itemCount;
public ModelItemExpander(IEnumerable<ModelItem> items, int itemCount)
{
_items = items;
_itemCount = itemCount;
}
public override int ContainerCount
{
get { return _itemCount; }
}
public override IEnumerator<IEnumerable<ModelProperty>> GetEnumerator()
{
if (_items == null)
{
yield break;
}
foreach (ModelItem item in _items)
{
if (item.Properties == null)
{
continue;
}
yield return item.Properties;
}
}
}
// <summary>
// Version of PropertyExpander that returns the sub-properties of a set of
// ModelProperty values.
// </summary>
private class SubPropertyExpander : PropertyExpander
{
private ICollection<ModelProperty> _parentProperties;
public SubPropertyExpander(ICollection<ModelProperty> parentProperties)
{
_parentProperties = parentProperties;
}
public override int ContainerCount
{
get { return _parentProperties == null ? 0 : _parentProperties.Count; }
}
public override IEnumerator<IEnumerable<ModelProperty>> GetEnumerator()
{
if (_parentProperties == null)
{
yield break;
}
foreach (ModelProperty property in _parentProperties)
{
yield return ExtensibilityAccessor.GetSubProperties(property);
}
}
}
}
}
| |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V10.Resources.AdGroupBidModifier;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example gets ad group bid modifiers.
/// </summary>
public class GetAdGroupBidModifiers : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="GetAdGroupBidModifiers"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// The ad group ID for which ad group bid modiifers will be retrieved.
/// </summary>
[Option("adGroupId", Required = false, HelpText =
"The ad group ID for which ad group bid modiifers will be retrieved.")]
public long? AdGroupId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// The ad group ID for which ad group bid modiifers will be retrieved.
options.AdGroupId = long.Parse("INSERT_AD_GROUP_ID_HERE");
return 0;
});
GetAdGroupBidModifiers codeExample = new GetAdGroupBidModifiers();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.AdGroupId);
}
/// <summary>
/// The page size to be used by default.
/// </summary>
private const int PAGE_SIZE = 1_000;
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description => "This code example gets ad group bid modifiers.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="adGroupId">The ad group ID for which ad group bid modiifers will
/// be retrieved.</param>
public void Run(GoogleAdsClient client, long customerId, long? adGroupId)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService =
client.GetService(Services.V10.GoogleAdsService);
string searchQuery = @"
SELECT
ad_group.id,
ad_group_bid_modifier.criterion_id,
campaign.id,
ad_group_bid_modifier.bid_modifier,
ad_group_bid_modifier.device.type,
ad_group_bid_modifier.hotel_date_selection_type.type,
ad_group_bid_modifier.hotel_advance_booking_window.min_days,
ad_group_bid_modifier.hotel_advance_booking_window.max_days,
ad_group_bid_modifier.hotel_length_of_stay.min_nights,
ad_group_bid_modifier.hotel_length_of_stay.max_nights,
ad_group_bid_modifier.hotel_check_in_day.day_of_week,
ad_group_bid_modifier.hotel_check_in_date_range.start_date,
ad_group_bid_modifier.hotel_check_in_date_range.end_date,
ad_group_bid_modifier.preferred_content.type
FROM
ad_group_bid_modifier";
if (adGroupId != null)
{
searchQuery += $" WHERE ad_group.id = {adGroupId}";
}
searchQuery += " LIMIT 10000";
// Creates a request that will retrieve ad group bid modifiers using pages of the
// specified page size.
SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
{
CustomerId = customerId.ToString(),
Query = searchQuery,
PageSize = PAGE_SIZE
};
try
{
// Issue the search request.
PagedEnumerable<SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
googleAdsService.Search(request);
// Iterates over all rows in all pages and prints the requested field values for
// the ad group bid modifiers in each row.
foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
{
AdGroupBidModifier agBidModifier = googleAdsRow.AdGroupBidModifier;
AdGroup adGroup = googleAdsRow.AdGroup;
Campaign campaign = googleAdsRow.Campaign;
Console.WriteLine("Ad group bid modifier with criterion ID {0}, bid " +
"modifier value {1:0.00} was found in an ad group with ID {2} of " +
"campaign ID {3}.",
agBidModifier.CriterionId,
agBidModifier.BidModifier,
adGroup.Id, campaign.Id);
string criterionDetails = " - Criterion type: " +
$"{agBidModifier.CriterionCase}, ";
switch (agBidModifier.CriterionCase)
{
case CriterionOneofCase.Device:
criterionDetails += $"Type: {agBidModifier.Device.Type}";
break;
case CriterionOneofCase.HotelAdvanceBookingWindow:
criterionDetails +=
$"Min Days: {agBidModifier.HotelAdvanceBookingWindow.MinDays}," +
$"Max Days: {agBidModifier.HotelAdvanceBookingWindow.MaxDays}";
break;
case CriterionOneofCase.HotelCheckInDay:
criterionDetails += $"Day of the week: " +
$"{agBidModifier.HotelCheckInDay.DayOfWeek}";
break;
case CriterionOneofCase.HotelDateSelectionType:
criterionDetails += $"Date selection type: " +
$"{agBidModifier.HotelDateSelectionType.Type}";
break;
case CriterionOneofCase.HotelLengthOfStay:
criterionDetails +=
$"Min Nights: {agBidModifier.HotelLengthOfStay.MinNights}," +
$"Max Nights: {agBidModifier.HotelLengthOfStay.MaxNights}";
break;
case CriterionOneofCase.HotelCheckInDateRange:
criterionDetails +=
$"Start Date: {agBidModifier.HotelCheckInDateRange.StartDate}," +
$"End Date: {agBidModifier.HotelCheckInDateRange.EndDate}";
break;
case CriterionOneofCase.PreferredContent:
criterionDetails +=
$"Type: {agBidModifier.PreferredContent.Type}";
break;
}
Console.WriteLine(criterionDetails);
}
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System.Text;
using System.Collections.Generic;
using NUnit.Framework;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki.Tests.SiteTests
{
[TestFixture]
public class SettingsTests
{
[Test]
public void GetSettings()
{
// GET:site/settings
// http://developer.mindtouch.com/Deki/API_Reference/GET%3asite%2f%2fsettings
Plug p = Utils.BuildPlugForAdmin();
DreamMessage msg = p.At("site", "settings").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
}
[Test]
public void PutSettings()
{
// PUT:site/settings
// http://developer.mindtouch.com/Deki/API_Reference/PUT%3asite%2f%2fsettings
Plug p = Utils.BuildPlugForAdmin();
DreamMessage msg = p.At("site", "settings").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
XDoc settingsDoc = msg.ToDocument();
Assert.IsFalse(settingsDoc.IsEmpty);
XDoc safeHtml = settingsDoc["editor/safe-html"];
safeHtml.ReplaceValue(false);
msg = p.At("site", "settings").Put(settingsDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msg = p.At("site", "settings").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsFalse(msg.ToDocument()["editor/safe-html"].AsBool.Value);
settingsDoc = msg.ToDocument();
safeHtml = settingsDoc["editor/safe-html"];
safeHtml.ReplaceValue(true);
msg = p.At("site", "settings").Put(settingsDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msg = p.At("site", "settings").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsTrue(msg.ToDocument()["editor/safe-html"].AsBool.Value);
}
private string GenerateBigRandomCss()
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < Utils.Settings.SizeOfSmallContent; i++)
{
builder.AppendFormat(".note{0}", Utils.GenerateUniqueName());
builder.AppendLine("{ color: red; background: yellow; font-weight: bold; }");
}
return builder.ToString();
}
[Test]
public void PutSettingsManyTimes()
{
Plug p = Utils.BuildPlugForAdmin();
XDoc settingsDoc = null;
DreamMessage msg = p.At("site", "settings").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
XDoc originalSettings = msg.ToDocument();
Assert.IsFalse(originalSettings.IsEmpty);
string bodycss1 = GenerateBigRandomCss();
string bodycss2 = GenerateBigRandomCss();
string css1 = GenerateBigRandomCss();
string css2 = GenerateBigRandomCss();
string html01 = Utils.GetRandomTextByAlphabet(Utils.Settings.SizeOfBigContent);
string html02 = Utils.GetRandomTextByAlphabet(Utils.Settings.SizeOfBigContent);
string html11 = Utils.GetRandomTextByAlphabet(Utils.Settings.SizeOfBigContent);
string html12 = Utils.GetRandomTextByAlphabet(Utils.Settings.SizeOfBigContent);
try
{
for (int i = 0; i < Utils.Settings.CountOfRepeats; i++)
{
settingsDoc = new XDoc("config")
.Start("cache")
.Elem("pages", true)
.Elem("permissions", true)
.Elem("roles", true)
.Elem("services", true)
.Elem("users", true)
.End()
.Start("editor")
.Elem("safe-html", true)
.End()
.Start("storage")
.Start("fs")
.Elem("path", "/var/www/deki-hayes-trunk/attachments")
.End()
.Elem("type", "fs")
.End()
.Start("files")
.Elem("blocked-extensions", "html, htm, exe, vbs, scr, reg, bat, comhtml, htm, exe, vbs, scr, reg, bat, com, cmd")
.End()
.Start("ui")
.Start("custom")
.Elem("bodycss", bodycss1)
.Elem("css", css1)
.Start("html")
.Start("ace")
.Start("neutral")
.Elem("html0", html01)
.Elem("html1", html11)
.End()
.End()
.End()
.End()
.Elem("language", "en-us")
.Elem("sitename", "Deki Wiki")
.End()
.Start("security")
.Elem("new-account-role", "Contributor")
.End();
msg = p.At("site", "settings").Put(settingsDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msg = p.At("site", "settings").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
XDoc msgDoc = msg.ToDocument();
Assert.AreEqual(msgDoc["cache/pages"].AsBool, true);
Assert.AreEqual(msgDoc["cache/permissions"].AsBool, true);
Assert.AreEqual(msgDoc["cache/roles"].AsBool, true);
Assert.AreEqual(msgDoc["cache/services"].AsBool, true);
Assert.AreEqual(msgDoc["cache/users"].AsBool, true);
Assert.AreEqual(msgDoc["editor/safe-html"].AsBool, true);
Assert.AreEqual(msgDoc["ui/custom/bodycss"].AsText, bodycss1);
Assert.AreEqual(msgDoc["ui/custom/css"].AsText, css1);
Assert.AreEqual(msgDoc["ui/custom/html/ace/neutral/html0"].AsText, html01);
Assert.AreEqual(msgDoc["ui/custom/html/ace/neutral/html1"].AsText, html11);
settingsDoc = new XDoc("config")
.Start("cache")
.Elem("pages", false)
.Elem("permissions", false)
.Elem("roles", false)
.Elem("services", false)
.Elem("users", false)
.End()
.Start("editor")
.Elem("safe-html", false)
.End()
.Start("storage")
.Start("fs")
.Elem("path", "/var/www/deki-hayes-trunk/attachments")
.End()
.Elem("type", "fs")
.End()
.Start("files")
.Elem("blocked-extensions", "html, htm, exe, vbs, scr, reg, bat, comhtml, htm, exe, vbs, scr, reg, bat, com, cmd")
.End()
.Start("ui")
.Start("custom")
.Elem("bodycss", bodycss2)
.Elem("css", css2)
.Start("html")
.Start("ace")
.Start("neutral")
.Elem("html0", html02)
.Elem("html1", html12)
.End()
.End()
.End()
.End()
.Elem("language", "en-us")
.Elem("sitename", "Deki Wiki")
.End()
.Start("security")
.Elem("new-account-role", "Contributor")
.End();
msg = p.At("site", "settings").Put(settingsDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msg = p.At("site", "settings").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msgDoc = msg.ToDocument();
Assert.AreEqual(msgDoc["cache/pages"].AsBool, false);
Assert.AreEqual(msgDoc["cache/permissions"].AsBool, false);
Assert.AreEqual(msgDoc["cache/roles"].AsBool, false);
Assert.AreEqual(msgDoc["cache/services"].AsBool, false);
Assert.AreEqual(msgDoc["cache/users"].AsBool, false);
Assert.AreEqual(msgDoc["editor/safe-html"].AsBool, false);
Assert.AreEqual(msgDoc["ui/custom/bodycss"].AsText, bodycss2);
Assert.AreEqual(msgDoc["ui/custom/css"].AsText, css2);
Assert.AreEqual(msgDoc["ui/custom/html/ace/neutral/html0"].AsText, html02);
Assert.AreEqual(msgDoc["ui/custom/html/ace/neutral/html1"].AsText, html12);
}
}
//catch (DreamResponseException ex)
//{
// throw;
//}
finally
{
msg = p.At("site", "settings").PutAsync(originalSettings).Wait();
Assert.IsTrue(msg.Status == DreamStatus.Ok, "Put original settings is failed: {0}", msg.ToString());
}
}
[Test]
public void StripLeafNodes() {
XDoc doc = null;
doc = new XDoc("root").Start("outer").Attr("someattr", "myval").Start("inner").End().End();
MindTouch.Deki.Utils.RemoveEmptyNodes(doc);
XDocAssertEqual(
new XDoc("root").Start("outer").Attr("someattr", "myval").End(),
doc);
doc = new XDoc("root").Start("outer").Start("inner").End().End();
MindTouch.Deki.Utils.RemoveEmptyNodes(doc);
XDocAssertEqual(new XDoc("root"), doc);
doc = new XDoc("root").Start("outer").Start("inner").Value("zzz").End().End();
MindTouch.Deki.Utils.RemoveEmptyNodes(doc);
XDocAssertEqual(new XDoc("root").Start("outer").Start("inner").Value("zzz").End().End(), doc);
}
private void XDocAssertEqual(XDoc expected, XDoc actual) {
Assert.IsNotNull(expected);
Assert.IsNotNull(actual);
KeyValuePair<string, string>[] e = expected.ToKeyValuePairs();
KeyValuePair<string, string>[] a = actual.ToKeyValuePairs();
Assert.AreEqual(e.Length, a.Length, "Number of items in XDoc mismatched");
for(int i = 0; i < e.Length; i++) {
Assert.AreEqual(e[i].Key, a[i].Key);
Assert.AreEqual(e[i].Value, a[i].Value);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using 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>
/// ReplicationVaultHealthOperations operations.
/// </summary>
internal partial class ReplicationVaultHealthOperations : IServiceOperations<SiteRecoveryManagementClient>, IReplicationVaultHealthOperations
{
/// <summary>
/// Initializes a new instance of the ReplicationVaultHealthOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ReplicationVaultHealthOperations(SiteRecoveryManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SiteRecoveryManagementClient
/// </summary>
public SiteRecoveryManagementClient Client { get; private set; }
/// <summary>
/// Gets the health summary for the vault.
/// </summary>
/// <remarks>
/// Gets the health details of the vault.
/// </remarks>
/// <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<VaultHealthDetails>> GetWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
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/{resourceName}/replicationVaultHealth").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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);
}
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<VaultHealthDetails>();
_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<VaultHealthDetails>(_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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
internal sealed class DelegateSerializationHolder : IObjectReference, ISerializable
{
#region Static Members
internal static DelegateEntry GetDelegateSerializationInfo(
SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
{
// Used for MulticastDelegate
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
Type c = delegateType.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type");
if (method.DeclaringType == null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target,
method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);
if (info.MemberCount == 0)
{
info.SetType(typeof(DelegateSerializationHolder));
info.AddValue("Delegate", de, typeof(DelegateEntry));
}
// target can be an object so it needs to be added to the info, or else a fixup is needed
// when deserializing, and the fixup will occur too late. If it is added directly to the
// info then the rules of deserialization will guarantee that it will be available when
// needed
if (target != null)
{
String targetName = "target" + targetIndex;
info.AddValue(targetName, de.target);
de.target = targetName;
}
// Due to a number of additions (delegate signature binding relaxation, delegates with open this or closed over the
// first parameter and delegates over generic methods) we need to send a deal more information than previously. We can
// get this by serializing the target MethodInfo. We still need to send the same information as before though (the
// DelegateEntry above) for backwards compatibility. And we want to send the MethodInfo (which is serialized via an
// ISerializable holder) as a top-level child of the info for the same reason as the target above -- we wouldn't have an
// order of deserialization guarantee otherwise.
String methodInfoName = "method" + targetIndex;
info.AddValue(methodInfoName, method);
return de;
}
#endregion
#region Definitions
[Serializable]
internal class DelegateEntry
{
#region Internal Data Members
internal String type;
internal String assembly;
internal Object target;
internal String targetTypeAssembly;
internal String targetTypeName;
internal String methodName;
internal DelegateEntry delegateEntry;
#endregion
#region Constructor
internal DelegateEntry(
String type, String assembly, Object target, String targetTypeAssembly, String targetTypeName, String methodName)
{
this.type = type;
this.assembly = assembly;
this.target = target;
this.targetTypeAssembly = targetTypeAssembly;
this.targetTypeName = targetTypeName;
this.methodName = methodName;
}
#endregion
#region Internal Members
internal DelegateEntry Entry
{
get { return delegateEntry; }
set { delegateEntry = value; }
}
#endregion
}
#endregion
#region Private Data Members
private DelegateEntry m_delegateEntry;
private MethodInfo[] m_methods;
#endregion
#region Constructor
private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
bool bNewWire = true;
try
{
m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
}
catch
{
// Old wire format
m_delegateEntry = OldDelegateWireFormat(info, context);
bNewWire = false;
}
if (bNewWire)
{
// retrieve the targets
DelegateEntry deiter = m_delegateEntry;
int count = 0;
while (deiter != null)
{
if (deiter.target != null)
{
string stringTarget = deiter.target as string; //need test to pass older wire format
if (stringTarget != null)
deiter.target = info.GetValue(stringTarget, typeof(Object));
}
count++;
deiter = deiter.delegateEntry;
}
// If the sender is as recent as us they'll have provided MethodInfos for each delegate. Look for these and pack
// them into an ordered array if present.
MethodInfo[] methods = new MethodInfo[count];
int i;
for (i = 0; i < count; i++)
{
String methodInfoName = "method" + i;
methods[i] = (MethodInfo)info.GetValueNoThrow(methodInfoName, typeof(MethodInfo));
if (methods[i] == null)
break;
}
// If we got the info then make the array available for deserialization.
if (i == count)
m_methods = methods;
}
}
#endregion
#region Private Members
private void ThrowInsufficientState(string field)
{
throw new SerializationException(
Environment.GetResourceString("Serialization_InsufficientDeserializationState", field));
}
private DelegateEntry OldDelegateWireFormat(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
String delegateType = info.GetString("DelegateType");
String delegateAssembly = info.GetString("DelegateAssembly");
Object target = info.GetValue("Target", typeof(Object));
String targetTypeAssembly = info.GetString("TargetTypeAssembly");
String targetTypeName = info.GetString("TargetTypeName");
String methodName = info.GetString("MethodName");
return new DelegateEntry(delegateType, delegateAssembly, target, targetTypeAssembly, targetTypeName, methodName);
}
private Delegate GetDelegate(DelegateEntry de, int index)
{
Delegate d;
try
{
if (de.methodName == null || de.methodName.Length == 0)
ThrowInsufficientState("MethodName");
if (de.assembly == null || de.assembly.Length == 0)
ThrowInsufficientState("DelegateAssembly");
if (de.targetTypeName == null || de.targetTypeName.Length == 0)
ThrowInsufficientState("TargetTypeName");
// We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load.
RuntimeType type = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type);
RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);
// If we received the new style delegate encoding we already have the target MethodInfo in hand.
if (m_methods != null)
{
if (de.target != null && !targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
Object target = de.target;
d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
}
else
{
if (de.target != null)
{
if (!targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
d = Delegate.CreateDelegate(type, de.target, de.methodName);
}
else
d = Delegate.CreateDelegate(type, targetType, de.methodName);
}
}
catch (Exception e)
{
if (e is SerializationException)
throw e;
throw new SerializationException(e.Message, e);
}
return d;
}
#endregion
#region IObjectReference
public Object GetRealObject(StreamingContext context)
{
int count = 0;
for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
count++;
int maxindex = count - 1;
if (count == 1)
{
return GetDelegate(m_delegateEntry, 0);
}
else
{
object[] invocationList = new object[count];
for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
{
// Be careful to match the index we pass to GetDelegate (used to look up extra information for each delegate) to
// the order we process the entries: we're actually looking at them in reverse order.
--count;
invocationList[count] = GetDelegate(de, maxindex - count);
}
return ((MulticastDelegate)invocationList[0]).NewMulticastDelegate(invocationList, invocationList.Length);
}
}
#endregion
#region ISerializable
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DelegateSerHolderSerial"));
}
#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.Collections.Generic;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class NewTests
{
#region Test methods
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewCustomTest(bool useInterpreter)
{
Expression<Func<C>> e =
Expression.Lambda<Func<C>>(
Expression.New(typeof(C)),
Enumerable.Empty<ParameterExpression>());
Func<C> f = e.Compile(useInterpreter);
Assert.Equal(new C(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewEnumTest(bool useInterpreter)
{
Expression<Func<E>> e =
Expression.Lambda<Func<E>>(
Expression.New(typeof(E)),
Enumerable.Empty<ParameterExpression>());
Func<E> f = e.Compile(useInterpreter);
Assert.Equal(new E(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableEnumTest(bool useInterpreter)
{
Expression<Func<E?>> e =
Expression.Lambda<Func<E?>>(
Expression.New(typeof(E?)),
Enumerable.Empty<ParameterExpression>());
Func<E?> f = e.Compile(useInterpreter);
Assert.Equal(new E?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableIntTest(bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.New(typeof(int?)),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile(useInterpreter);
Assert.Equal(new int?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewStructTest(bool useInterpreter)
{
Expression<Func<S>> e =
Expression.Lambda<Func<S>>(
Expression.New(typeof(S)),
Enumerable.Empty<ParameterExpression>());
Func<S> f = e.Compile(useInterpreter);
Assert.Equal(new S(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableStructTest(bool useInterpreter)
{
Expression<Func<S?>> e =
Expression.Lambda<Func<S?>>(
Expression.New(typeof(S?)),
Enumerable.Empty<ParameterExpression>());
Func<S?> f = e.Compile(useInterpreter);
Assert.Equal(new S?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewStructWithStringTest(bool useInterpreter)
{
Expression<Func<Sc>> e =
Expression.Lambda<Func<Sc>>(
Expression.New(typeof(Sc)),
Enumerable.Empty<ParameterExpression>());
Func<Sc> f = e.Compile(useInterpreter);
Assert.Equal(new Sc(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableStructWithStringTest(bool useInterpreter)
{
Expression<Func<Sc?>> e =
Expression.Lambda<Func<Sc?>>(
Expression.New(typeof(Sc?)),
Enumerable.Empty<ParameterExpression>());
Func<Sc?> f = e.Compile(useInterpreter);
Assert.Equal(new Sc?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewStructWithStringAndFieldTest(bool useInterpreter)
{
Expression<Func<Scs>> e =
Expression.Lambda<Func<Scs>>(
Expression.New(typeof(Scs)),
Enumerable.Empty<ParameterExpression>());
Func<Scs> f = e.Compile(useInterpreter);
Assert.Equal(new Scs(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableStructWithStringAndFieldTest(bool useInterpreter)
{
Expression<Func<Scs?>> e =
Expression.Lambda<Func<Scs?>>(
Expression.New(typeof(Scs?)),
Enumerable.Empty<ParameterExpression>());
Func<Scs?> f = e.Compile(useInterpreter);
Assert.Equal(new Scs?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewStructWithTwoValuesTest(bool useInterpreter)
{
Expression<Func<Sp>> e =
Expression.Lambda<Func<Sp>>(
Expression.New(typeof(Sp)),
Enumerable.Empty<ParameterExpression>());
Func<Sp> f = e.Compile(useInterpreter);
Assert.Equal(new Sp(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableStructWithTwoValuesTest(bool useInterpreter)
{
Expression<Func<Sp?>> e =
Expression.Lambda<Func<Sp?>>(
Expression.New(typeof(Sp?)),
Enumerable.Empty<ParameterExpression>());
Func<Sp?> f = e.Compile(useInterpreter);
Assert.Equal(new Sp?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewGenericWithStructRestrictionWithEnumTest(bool useInterpreter)
{
CheckNewGenericWithStructRestrictionHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewGenericWithStructRestrictionWithStructTest(bool useInterpreter)
{
CheckNewGenericWithStructRestrictionHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewGenericWithStructRestrictionWithStructWithStringAndFieldTest(bool useInterpreter)
{
CheckNewGenericWithStructRestrictionHelper<Scs>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableGenericWithStructRestrictionWithEnumTest(bool useInterpreter)
{
CheckNewNullableGenericWithStructRestrictionHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableGenericWithStructRestrictionWithStructTest(bool useInterpreter)
{
CheckNewNullableGenericWithStructRestrictionHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableGenericWithStructRestrictionWithStructWithStringAndFieldTest(bool useInterpreter)
{
CheckNewNullableGenericWithStructRestrictionHelper<Scs>(useInterpreter);
}
#endregion
#region Generic helpers
private static void CheckNewGenericWithStructRestrictionHelper<Ts>(bool useInterpreter) where Ts : struct
{
Expression<Func<Ts>> e =
Expression.Lambda<Func<Ts>>(
Expression.New(typeof(Ts)),
Enumerable.Empty<ParameterExpression>());
Func<Ts> f = e.Compile(useInterpreter);
Assert.Equal(new Ts(), f());
}
private static void CheckNewNullableGenericWithStructRestrictionHelper<Ts>(bool useInterpreter) where Ts : struct
{
Expression<Func<Ts?>> e =
Expression.Lambda<Func<Ts?>>(
Expression.New(typeof(Ts?)),
Enumerable.Empty<ParameterExpression>());
Func<Ts?> f = e.Compile(useInterpreter);
Assert.Equal(new Ts?(), f());
}
#endregion
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void PrivateDefaultConstructor(bool useInterpreter)
{
Assert.Equal("Test instance", TestPrivateDefaultConstructor.GetInstanceFunc(useInterpreter)().ToString());
}
class TestPrivateDefaultConstructor
{
private TestPrivateDefaultConstructor() { }
public static Func<TestPrivateDefaultConstructor> GetInstanceFunc(bool useInterpreter)
{
var lambda = Expression.Lambda<Func<TestPrivateDefaultConstructor>>(Expression.New(typeof(TestPrivateDefaultConstructor)), new ParameterExpression[] { });
return lambda.Compile(useInterpreter);
}
public override string ToString() => "Test instance";
}
[Fact]
public static void New_NullConstructor_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("constructor", () => Expression.New((ConstructorInfo)null));
Assert.Throws<ArgumentNullException>("constructor", () => Expression.New(null, new Expression[0]));
Assert.Throws<ArgumentNullException>("constructor", () => Expression.New(null, (IEnumerable<Expression>)new Expression[0]));
Assert.Throws<ArgumentNullException>("constructor", () => Expression.New(null, new Expression[0], new MemberInfo[0]));
Assert.Throws<ArgumentNullException>("constructor", () => Expression.New(null, new Expression[0], (IEnumerable<MemberInfo>)new MemberInfo[0]));
}
[Fact]
public static void StaticConstructor_ThrowsArgumentException()
{
var cctor = typeof(StaticCtor).GetTypeInfo().DeclaredConstructors.Single(c => c.IsStatic);
Assert.Throws<ArgumentException>("constructor", () => Expression.New(cctor));
Assert.Throws<ArgumentException>("constructor", () => Expression.New(cctor, new Expression[0]));
Assert.Throws<ArgumentException>("constructor", () => Expression.New(cctor, (IEnumerable<Expression>)new Expression[0]));
Assert.Throws<ArgumentException>("constructor", () => Expression.New(cctor, new Expression[0], new MemberInfo[0]));
Assert.Throws<ArgumentException>("constructor", () => Expression.New(cctor, new Expression[0], (IEnumerable<MemberInfo>)new MemberInfo[0]));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void Compile_AbstractCtor_ThrowsInvalidOperationExeption(bool useInterpretation)
{
var ctor = typeof(AbstractCtor).GetTypeInfo().DeclaredConstructors.Single();
var f = Expression.Lambda<Func<AbstractCtor>>(Expression.New(ctor));
Assert.Throws<InvalidOperationException>(() => f.Compile(useInterpretation));
}
[Fact]
public static void ConstructorDeclaringType_GenericTypeDefinition_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(GenericClass<>).GetConstructor(new Type[0]);
Assert.Throws<ArgumentException>("constructor", () => Expression.New(constructor));
Assert.Throws<ArgumentException>("constructor", () => Expression.New(constructor, new Expression[0]));
Assert.Throws<ArgumentException>("constructor", () => Expression.New(constructor, (IEnumerable<Expression>)new Expression[0]));
}
[Fact]
public static void ConstructorDeclaringType_GenericTypeDefintion_Works()
{
// Should probably throw an ArgumentException, similar to other overloads
ConstructorInfo constructor = typeof(GenericClass<>).GetConstructor(new Type[0]);
Expression.New(constructor, new Expression[0], new MemberInfo[0]);
Expression.New(constructor, new Expression[0], new MemberInfo[0]);
}
public static IEnumerable<object[]> ConstructorAndArguments_DifferentLengths_TestData()
{
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[0]), new Expression[2] };
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) }), new Expression[0] };
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) }), new Expression[2] };
}
[Theory]
[MemberData(nameof(ConstructorAndArguments_DifferentLengths_TestData))]
public static void ConstructorAndArguments_DifferentLengths_ThrowsArgumentException(ConstructorInfo constructor, Expression[] expressions)
{
if (expressions.Length == 0)
{
Assert.Throws<ArgumentException>(null, () => Expression.New(constructor));
}
Assert.Throws<ArgumentException>(null, () => Expression.New(constructor, expressions));
Assert.Throws<ArgumentException>(null, () => Expression.New(constructor, (IEnumerable<Expression>)expressions));
Assert.Throws<ArgumentException>(null, () => Expression.New(constructor, expressions, new MemberInfo[expressions.Length]));
Assert.Throws<ArgumentException>(null, () => Expression.New(constructor, expressions, (IEnumerable<MemberInfo>)new MemberInfo[expressions.Length]));
}
[Fact]
public static void Arguments_ExpressionNotReadable_ThrowsArgumentExeption()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] expressions = new Expression[] { Expression.Property(null, typeof(Unreachable<string>), nameof(Unreachable<string>.WriteOnly)) };
Assert.Throws<ArgumentException>("arguments", () => Expression.New(constructor, expressions));
Assert.Throws<ArgumentException>("arguments", () => Expression.New(constructor, (IEnumerable<Expression>)expressions));
Assert.Throws<ArgumentException>("arguments", () => Expression.New(constructor, expressions, new MemberInfo[1]));
Assert.Throws<ArgumentException>("arguments", () => Expression.New(constructor, expressions, (IEnumerable<MemberInfo>)new MemberInfo[1]));
}
[Fact]
public static void ConstructorAndArguments_IncompatibleTypes_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] expressions = new Expression[] { Expression.Constant(5) };
Assert.Throws<ArgumentException>("arguments", () => Expression.New(constructor, expressions));
Assert.Throws<ArgumentException>("arguments", () => Expression.New(constructor, (IEnumerable<Expression>)expressions));
MemberInfo[] members = new MemberInfo[] { typeof(ClassWithCtors).GetProperty(nameof(ClassWithCtors.IntProperty)) };
Assert.Throws<ArgumentException>("arguments", () => Expression.New(constructor, expressions, members));
Assert.Throws<ArgumentException>("arguments", () => Expression.New(constructor, expressions, members));
}
public static IEnumerable<object[]> ArgumentsAndMembers_DifferentLengths_TestData()
{
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[0]), new Expression[0], new MemberInfo[1] };
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) }), new Expression[1], new MemberInfo[0] };
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) }), new Expression[1], new MemberInfo[2] };
}
[Theory]
[MemberData(nameof(ArgumentsAndMembers_DifferentLengths_TestData))]
public static void ArgumentsAndMembers_DifferentLengths_ThrowsArgumentException(ConstructorInfo constructor, Expression[] arguments, MemberInfo[] members)
{
Assert.Throws<ArgumentException>(null, () => Expression.New(constructor, arguments, members));
Assert.Throws<ArgumentException>(null, () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Members_MemberNotOnDeclaringType_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { typeof(Unreachable<string>).GetProperty(nameof(Unreachable<string>.WriteOnly)) };
Assert.Throws<ArgumentException>("members", () => Expression.New(constructor, arguments, members));
Assert.Throws<ArgumentException>("members", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Theory]
[InlineData(nameof(ClassWithCtors.s_field))]
[InlineData(nameof(ClassWithCtors.StaticProperty))]
[InlineData(nameof(ClassWithCtors.StaticMethod))]
public static void Members_StaticMember_ThrowsArgumentException(string memberName)
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { typeof(ClassWithCtors).GetMember(memberName).First() };
Assert.Throws<ArgumentException>("members", () => Expression.New(constructor, arguments, members));
Assert.Throws<ArgumentException>("members", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Members_MemberWriteOnly_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { typeof(ClassWithCtors).GetProperty(nameof(ClassWithCtors.WriteOnlyProperty)) };
Assert.Throws<ArgumentException>("members", () => Expression.New(constructor, arguments, members));
Assert.Throws<ArgumentException>("members", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Members_MemberNotPropertyAccessor_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { typeof(ClassWithCtors).GetMethod(nameof(ClassWithCtors.InstanceMethod)) };
Assert.Throws<ArgumentException>("members", () => Expression.New(constructor, arguments, members));
Assert.Throws<ArgumentException>("members", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Members_MemberNotFieldPropertyOrMethod_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { constructor };
Assert.Throws<ArgumentException>("members", () => Expression.New(constructor, arguments, members));
Assert.Throws<ArgumentException>("members", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Members_ArgumentTypeAndMemberTypeDontMatch_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { typeof(ClassWithCtors).GetField(nameof(ClassWithCtors._field)) };
Assert.Throws<ArgumentException>(null, () => Expression.New(constructor, arguments, members));
Assert.Throws<ArgumentException>(null, () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Type_Null_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("type", () => Expression.New((Type)null));
}
public static IEnumerable<object[]> Type_InvalidType_TestData()
{
yield return new object[] { typeof(void) };
yield return new object[] { typeof(int).MakeByRefType() };
yield return new object[] { typeof(StaticCtor) };
yield return new object[] { typeof(ClassWithNoDefaultCtor) };
}
[Theory]
[MemberData(nameof(Type_InvalidType_TestData))]
[InlineData(typeof(int*))]
public static void Type_InvalidType_ThrowsArgumentException(Type type)
{
Assert.Throws<ArgumentException>("type", () => Expression.New(type));
}
static class StaticCtor
{
static StaticCtor() { }
}
abstract class AbstractCtor
{
public AbstractCtor() { }
}
class GenericClass<T>
{
public GenericClass() { }
}
class ClassWithCtors
{
public ClassWithCtors() { }
public ClassWithCtors(string obj) { }
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public int WriteOnlyProperty { set { } }
#pragma warning disable 0649
public int _field;
public static int s_field;
#pragma warning restore 0649
public static string StaticProperty { get; set; }
public static void StaticMethod() { }
public void InstanceMethod() { }
}
class ClassWithNoDefaultCtor
{
public ClassWithNoDefaultCtor(string s) { }
}
static class Unreachable<T>
{
public static T WriteOnly { set { } }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptographicException))]
namespace System.Security.Cryptography
{
public abstract partial class AsymmetricAlgorithm : System.IDisposable
{
protected int KeySizeValue;
protected System.Security.Cryptography.KeySizes[] LegalKeySizesValue;
protected AsymmetricAlgorithm() { }
public virtual string KeyExchangeAlgorithm { get { throw null; } }
public virtual int KeySize { get { throw null; } set { } }
public virtual System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public static System.Security.Cryptography.AsymmetricAlgorithm Create() { throw null; }
public static System.Security.Cryptography.AsymmetricAlgorithm Create(string algName) { throw null; }
public virtual string SignatureAlgorithm { get { throw null; } }
public void Clear() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual void FromXmlString(string xmlString) { }
public virtual string ToXmlString(bool includePrivateParameters) { throw null; }
}
public enum CipherMode
{
CBC = 1,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
CFB = 4,
CTS = 5,
ECB = 2,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
OFB = 3,
}
public partial class CryptographicUnexpectedOperationException : System.Security.Cryptography.CryptographicException
{
public CryptographicUnexpectedOperationException() { }
protected CryptographicUnexpectedOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public CryptographicUnexpectedOperationException(string message) { }
public CryptographicUnexpectedOperationException(string message, System.Exception inner) { }
public CryptographicUnexpectedOperationException(string format, string insert) { }
}
public partial class CryptoStream : System.IO.Stream, System.IDisposable
{
public CryptoStream(System.IO.Stream stream, System.Security.Cryptography.ICryptoTransform transform, System.Security.Cryptography.CryptoStreamMode mode) { }
public CryptoStream(System.IO.Stream stream, System.Security.Cryptography.ICryptoTransform transform, System.Security.Cryptography.CryptoStreamMode mode, bool leaveOpen) { }
public override bool CanRead { get { throw null; } }
public override bool CanSeek { get { throw null; } }
public override bool CanWrite { get { throw null; } }
public void Clear() { }
public bool HasFlushedFinalBlock { get { throw null; } }
public override long Length { get { throw null; } }
public override long Position { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
public void FlushFinalBlock() { }
public override int Read(byte[] buffer, int offset, int count) { throw null; }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override int ReadByte() { throw null; }
public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
public override void SetLength(long value) { }
public override void Write(byte[] buffer, int offset, int count) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override void WriteByte(byte value) { }
}
public enum CryptoStreamMode
{
Read = 0,
Write = 1,
}
public abstract partial class HashAlgorithm : System.IDisposable, System.Security.Cryptography.ICryptoTransform
{
protected internal byte[] HashValue;
protected int HashSizeValue;
protected int State;
protected HashAlgorithm() { }
public virtual bool CanReuseTransform { get { throw null; } }
public virtual bool CanTransformMultipleBlocks { get { throw null; } }
public virtual byte[] Hash { get { throw null; } }
public virtual int HashSize { get { throw null; } }
public virtual int InputBlockSize { get { throw null; } }
public virtual int OutputBlockSize { get { throw null; } }
public void Clear() { }
public byte[] ComputeHash(byte[] buffer) { throw null; }
public byte[] ComputeHash(byte[] buffer, int offset, int count) { throw null; }
public byte[] ComputeHash(System.IO.Stream inputStream) { throw null; }
public static System.Security.Cryptography.HashAlgorithm Create() { throw null; }
public static System.Security.Cryptography.HashAlgorithm Create(string hashName) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected abstract void HashCore(byte[] array, int ibStart, int cbSize);
protected virtual void HashCore(ReadOnlySpan<byte> source) { throw null; }
protected abstract byte[] HashFinal();
public abstract void Initialize();
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { throw null; }
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { throw null; }
public bool TryComputeHash(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten) { throw null; }
protected virtual bool TryHashFinal(Span<byte> destination, out int bytesWritten) { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct HashAlgorithmName : System.IEquatable<System.Security.Cryptography.HashAlgorithmName>
{
public HashAlgorithmName(string name) { throw null; }
public static System.Security.Cryptography.HashAlgorithmName MD5 { get { throw null; } }
public string Name { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA1 { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA256 { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA384 { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA512 { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.HashAlgorithmName other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.HashAlgorithmName left, System.Security.Cryptography.HashAlgorithmName right) { throw null; }
public static bool operator !=(System.Security.Cryptography.HashAlgorithmName left, System.Security.Cryptography.HashAlgorithmName right) { throw null; }
public override string ToString() { throw null; }
}
public abstract partial class HMAC : System.Security.Cryptography.KeyedHashAlgorithm
{
protected HMAC() { }
protected int BlockSizeValue { get { throw null; } set {} }
public string HashName { get { throw null; } set { } }
public override byte[] Key { get { throw null; } set { } }
public static new System.Security.Cryptography.HMAC Create() { throw null; }
public static new System.Security.Cryptography.HMAC Create(string algorithmName) { throw null; }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public partial interface ICryptoTransform : System.IDisposable
{
bool CanReuseTransform { get; }
bool CanTransformMultipleBlocks { get; }
int InputBlockSize { get; }
int OutputBlockSize { get; }
int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset);
byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount);
}
public abstract partial class KeyedHashAlgorithm : System.Security.Cryptography.HashAlgorithm
{
protected byte[] KeyValue;
protected KeyedHashAlgorithm() { }
public virtual byte[] Key { get { throw null; } set { } }
public static new System.Security.Cryptography.KeyedHashAlgorithm Create() { throw null; }
public static new System.Security.Cryptography.KeyedHashAlgorithm Create(string algName) { throw null; }
protected override void Dispose(bool disposing) { }
}
public sealed partial class KeySizes
{
public KeySizes(int minSize, int maxSize, int skipSize) { }
public int MaxSize { get { throw null; } }
public int MinSize { get { throw null; } }
public int SkipSize { get { throw null; } }
}
public enum PaddingMode
{
None = 1,
PKCS7 = 2,
Zeros = 3,
ANSIX923 = 4,
ISO10126 = 5,
}
public abstract partial class SymmetricAlgorithm : System.IDisposable
{
protected int FeedbackSizeValue;
protected int BlockSizeValue;
protected byte[] IVValue;
protected int KeySizeValue;
protected byte[] KeyValue;
protected System.Security.Cryptography.KeySizes[] LegalBlockSizesValue;
protected System.Security.Cryptography.KeySizes[] LegalKeySizesValue;
protected System.Security.Cryptography.CipherMode ModeValue;
protected System.Security.Cryptography.PaddingMode PaddingValue;
protected SymmetricAlgorithm() { }
public virtual int FeedbackSize { get { throw null; } set { } }
public virtual int BlockSize { get { throw null; } set { } }
public virtual byte[] IV { get { throw null; } set { } }
public virtual byte[] Key { get { throw null; } set { } }
public virtual int KeySize { get { throw null; } set { } }
public virtual System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } }
public virtual System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public virtual System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public virtual System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public static System.Security.Cryptography.SymmetricAlgorithm Create() { throw null; }
public static System.Security.Cryptography.SymmetricAlgorithm Create(string algName) { throw null; }
public virtual System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public abstract System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV);
public virtual System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public abstract System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV);
public void Clear() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void GenerateIV();
public abstract void GenerateKey();
public bool ValidKeySize(int bitLength) { throw null; }
}
}
| |
/*
* 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.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.CoreModules.World.Terrain;
using OpenSim.Region.CoreModules.World.Land;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using System.Threading;
namespace OpenSim.Region.CoreModules.World.Archiver
{
/// <summary>
/// Handles an individual archive read request
/// </summary>
public class ArchiveReadRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Contains data used while dearchiving a single scene.
/// </summary>
private class DearchiveContext
{
public Scene Scene { get; set; }
public List<string> SerialisedSceneObjects { get; set; }
public List<string> SerialisedParcels { get; set; }
public List<SceneObjectGroup> SceneObjects { get; set; }
public DearchiveContext(Scene scene)
{
Scene = scene;
SerialisedSceneObjects = new List<string>();
SerialisedParcels = new List<string>();
SceneObjects = new List<SceneObjectGroup>();
}
}
/// <summary>
/// The maximum major version of OAR that we can read. Minor versions shouldn't need a max number since version
/// bumps here should be compatible.
/// </summary>
public static int MAX_MAJOR_VERSION = 1;
/// <summary>
/// Has the control file been loaded for this archive?
/// </summary>
public bool ControlFileLoaded { get; private set; }
protected string m_loadPath;
protected Scene m_rootScene;
protected Stream m_loadStream;
protected Guid m_requestId;
protected string m_errorMessage;
/// <value>
/// Should the archive being loaded be merged with what is already on the region?
/// Merging usually suppresses terrain and parcel loading
/// </value>
protected bool m_merge;
/// <value>
/// If true, force the loading of terrain from the oar file
/// </value>
protected bool m_forceTerrain;
/// <value>
/// If true, force the loading of parcels from the oar file
/// </value>
protected bool m_forceParcels;
/// <value>
/// Should we ignore any assets when reloading the archive?
/// </value>
protected bool m_skipAssets;
/// <value>
/// Displacement added to each object as it is added to the world
/// </value>
protected Vector3 m_displacement = Vector3.Zero;
/// <value>
/// Rotation (in radians) to apply to the objects as they are loaded.
/// </value>
protected float m_rotation = 0f;
/// <value>
/// original oar region size. not using Constants.RegionSize
/// </value>
protected Vector3 m_incomingRegionSize = new Vector3(256f, 256f, float.MaxValue);
/// <value>
/// Center around which to apply the rotation relative to the original oar position
/// </value>
protected Vector3 m_rotationCenter = new Vector3(128f, 128f, 0f);
/// <value>
/// Corner 1 of a bounding cuboid which specifies which objects we load from the oar
/// </value>
protected Vector3 m_boundingOrigin = Vector3.Zero;
/// <value>
/// Size of a bounding cuboid which specifies which objects we load from the oar
/// </value>
protected Vector3 m_boundingSize = new Vector3(Constants.MaximumRegionSize, Constants.MaximumRegionSize, float.MaxValue);
protected bool m_noObjects = false;
protected bool m_boundingBox = false;
protected bool m_debug = false;
/// <summary>
/// Used to cache lookups for valid uuids.
/// </summary>
private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
private IUserManagement m_UserMan;
private IUserManagement UserManager
{
get
{
if (m_UserMan == null)
{
m_UserMan = m_rootScene.RequestModuleInterface<IUserManagement>();
}
return m_UserMan;
}
}
/// <summary>
/// Used to cache lookups for valid groups.
/// </summary>
private IDictionary<UUID, bool> m_validGroupUuids = new Dictionary<UUID, bool>();
private IGroupsModule m_groupsModule;
private IAssetService m_assetService = null;
private UUID m_defaultUser;
public ArchiveReadRequest(Scene scene, string loadPath, Guid requestId, Dictionary<string, object> options)
{
m_rootScene = scene;
if (options.ContainsKey("default-user"))
{
m_defaultUser = (UUID)options["default-user"];
m_log.InfoFormat("Using User {0} as default user", m_defaultUser.ToString());
}
else
{
m_defaultUser = scene.RegionInfo.EstateSettings.EstateOwner;
}
m_loadPath = loadPath;
try
{
m_loadStream = new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
}
m_errorMessage = String.Empty;
m_merge = options.ContainsKey("merge");
m_forceTerrain = options.ContainsKey("force-terrain");
m_forceParcels = options.ContainsKey("force-parcels");
m_noObjects = options.ContainsKey("no-objects");
m_skipAssets = options.ContainsKey("skipAssets");
m_requestId = requestId;
m_displacement = options.ContainsKey("displacement") ? (Vector3)options["displacement"] : Vector3.Zero;
m_rotation = options.ContainsKey("rotation") ? (float)options["rotation"] : 0f;
m_boundingOrigin = Vector3.Zero;
m_boundingSize = new Vector3(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY, float.MaxValue);
if (options.ContainsKey("bounding-origin"))
{
Vector3 boOption = (Vector3)options["bounding-origin"];
if (boOption != m_boundingOrigin)
{
m_boundingOrigin = boOption;
m_boundingBox = true;
}
}
if (options.ContainsKey("bounding-size"))
{
Vector3 bsOption = (Vector3)options["bounding-size"];
bool clip = false;
if (bsOption.X <= 0 || bsOption.X > m_boundingSize.X)
{
bsOption.X = m_boundingSize.X;
clip = true;
}
if (bsOption.Y <= 0 || bsOption.Y > m_boundingSize.Y)
{
bsOption.Y = m_boundingSize.Y;
clip = true;
}
if (bsOption != m_boundingSize)
{
m_boundingSize = bsOption;
m_boundingBox = true;
}
if (clip) m_log.InfoFormat("[ARCHIVER]: The bounding cube specified is larger than the destination region! Clipping to {0}.", m_boundingSize.ToString());
}
m_debug = options.ContainsKey("debug");
// Zero can never be a valid user id (or group)
m_validUserUuids[UUID.Zero] = false;
m_validGroupUuids[UUID.Zero] = false;
m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
m_assetService = m_rootScene.AssetService;
}
public ArchiveReadRequest(Scene scene, Stream loadStream, Guid requestId, Dictionary<string, object> options)
{
m_rootScene = scene;
m_loadPath = null;
m_loadStream = loadStream;
m_skipAssets = options.ContainsKey("skipAssets");
m_merge = options.ContainsKey("merge");
m_requestId = requestId;
m_defaultUser = scene.RegionInfo.EstateSettings.EstateOwner;
// Zero can never be a valid user id
m_validUserUuids[UUID.Zero] = false;
m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
m_assetService = m_rootScene.AssetService;
}
/// <summary>
/// Dearchive the region embodied in this request.
/// </summary>
public void DearchiveRegion()
{
int successfulAssetRestores = 0;
int failedAssetRestores = 0;
DearchiveScenesInfo dearchivedScenes;
// We dearchive all the scenes at once, because the files in the TAR archive might be mixed.
// Therefore, we have to keep track of the dearchive context of all the scenes.
Dictionary<UUID, DearchiveContext> sceneContexts = new Dictionary<UUID, DearchiveContext>();
string fullPath = "NONE";
TarArchiveReader archive = null;
byte[] data;
TarArchiveReader.TarEntryType entryType;
try
{
FindAndLoadControlFile(out archive, out dearchivedScenes);
while ((data = archive.ReadEntry(out fullPath, out entryType)) != null)
{
//m_log.DebugFormat(
// "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length);
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
continue;
// Find the scene that this file belongs to
Scene scene;
string filePath;
if (!dearchivedScenes.GetRegionFromPath(fullPath, out scene, out filePath))
continue; // this file belongs to a region that we're not loading
DearchiveContext sceneContext = null;
if (scene != null)
{
if (!sceneContexts.TryGetValue(scene.RegionInfo.RegionID, out sceneContext))
{
sceneContext = new DearchiveContext(scene);
sceneContexts.Add(scene.RegionInfo.RegionID, sceneContext);
}
}
// Process the file
if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH) && !m_noObjects)
{
sceneContext.SerialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
}
else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
{
if (LoadAsset(filePath, data))
successfulAssetRestores++;
else
failedAssetRestores++;
if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
}
else if (filePath.StartsWith(ArchiveConstants.TERRAINS_PATH) && (!m_merge || m_forceTerrain))
{
LoadTerrain(scene, filePath, data);
}
else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
{
LoadRegionSettings(scene, filePath, data, dearchivedScenes);
}
else if (filePath.StartsWith(ArchiveConstants.LANDDATA_PATH) && (!m_merge || m_forceParcels))
{
sceneContext.SerialisedParcels.Add(Encoding.UTF8.GetString(data));
}
else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
{
// Ignore, because we already read the control file
}
}
//m_log.Debug("[ARCHIVER]: Reached end of archive");
}
catch (Exception e)
{
m_log.Error(
String.Format("[ARCHIVER]: Aborting load with error in archive file {0} ", fullPath), e);
m_errorMessage += e.ToString();
m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
return;
}
finally
{
if (archive != null)
archive.Close();
}
if (!m_skipAssets)
{
m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
if (failedAssetRestores > 0)
{
m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
}
}
foreach (DearchiveContext sceneContext in sceneContexts.Values)
{
m_log.InfoFormat("[ARCHIVER]: Loading region {0}", sceneContext.Scene.RegionInfo.RegionName);
if (!m_merge)
{
m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
sceneContext.Scene.DeleteAllSceneObjects();
}
try
{
LoadParcels(sceneContext.Scene, sceneContext.SerialisedParcels);
LoadObjects(sceneContext.Scene, sceneContext.SerialisedSceneObjects, sceneContext.SceneObjects);
// Inform any interested parties that the region has changed. We waited until now so that all
// of the region's objects will be loaded when we send this notification.
IEstateModule estateModule = sceneContext.Scene.RequestModuleInterface<IEstateModule>();
if (estateModule != null)
estateModule.TriggerRegionInfoChange();
}
catch (Exception e)
{
m_log.Error("[ARCHIVER]: Error loading parcels or objects ", e);
m_errorMessage += e.ToString();
m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
return;
}
}
// Start the scripts. We delayed this because we want the OAR to finish loading ASAP, so
// that users can enter the scene. If we allow the scripts to start in the loop above
// then they significantly increase the time until the OAR finishes loading.
WorkManager.RunInThread(o =>
{
Thread.Sleep(15000);
m_log.Info("[ARCHIVER]: Starting scripts in scene objects");
foreach (DearchiveContext sceneContext in sceneContexts.Values)
{
foreach (SceneObjectGroup sceneObject in sceneContext.SceneObjects)
{
sceneObject.CreateScriptInstances(0, false, sceneContext.Scene.DefaultScriptEngine, 0); // StateSource.RegionStart
sceneObject.ResumeScripts();
}
sceneContext.SceneObjects.Clear();
}
}, null, string.Format("ReadArchiveStartScripts (request {0})", m_requestId));
m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, dearchivedScenes.GetLoadedScenes(), m_errorMessage);
}
/// <summary>
/// Searches through the files in the archive for the control file, and reads it.
/// We must read the control file first, in order to know which regions are available.
/// </summary>
/// <remarks>
/// In most cases the control file *is* first, since that's how we create archives. However,
/// it's possible that someone rewrote the archive externally so we can't rely on this fact.
/// </remarks>
/// <param name="archive"></param>
/// <param name="dearchivedScenes"></param>
private void FindAndLoadControlFile(out TarArchiveReader archive, out DearchiveScenesInfo dearchivedScenes)
{
archive = new TarArchiveReader(m_loadStream);
dearchivedScenes = new DearchiveScenesInfo();
string filePath;
byte[] data;
TarArchiveReader.TarEntryType entryType;
bool firstFile = true;
while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
{
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
continue;
if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
{
LoadControlFile(filePath, data, dearchivedScenes);
// Find which scenes are available in the simulator
ArchiveScenesGroup simulatorScenes = new ArchiveScenesGroup();
SceneManager.Instance.ForEachScene(delegate(Scene scene2)
{
simulatorScenes.AddScene(scene2);
});
simulatorScenes.CalcSceneLocations();
dearchivedScenes.SetSimulatorScenes(m_rootScene, simulatorScenes);
// If the control file wasn't the first file then reset the read pointer
if (!firstFile)
{
m_log.Warn("[ARCHIVER]: Control file wasn't the first file in the archive");
if (m_loadStream.CanSeek)
{
m_loadStream.Seek(0, SeekOrigin.Begin);
}
else if (m_loadPath != null)
{
archive.Close();
archive = null;
m_loadStream.Close();
m_loadStream = null;
m_loadStream = new GZipStream(ArchiveHelpers.GetStream(m_loadPath), CompressionMode.Decompress);
archive = new TarArchiveReader(m_loadStream);
}
else
{
// There isn't currently a scenario where this happens, but it's best to add a check just in case
throw new Exception("[ARCHIVER]: Error reading archive: control file wasn't the first file, and the input stream doesn't allow seeking");
}
}
return;
}
firstFile = false;
}
throw new Exception("[ARCHIVER]: Control file not found");
}
/// <summary>
/// Load serialized scene objects.
/// </summary>
protected void LoadObjects(Scene scene, List<string> serialisedSceneObjects, List<SceneObjectGroup> sceneObjects)
{
// Reload serialized prims
m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count);
// Convert rotation to radians
double rotation = Math.PI * m_rotation / 180f;
OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, (float)rotation);
UUID oldTelehubUUID = scene.RegionInfo.RegionSettings.TelehubObject;
IRegionSerialiserModule serialiser = scene.RequestModuleInterface<IRegionSerialiserModule>();
int sceneObjectsLoadedCount = 0;
Vector3 boundingExtent = new Vector3(m_boundingOrigin.X + m_boundingSize.X, m_boundingOrigin.Y + m_boundingSize.Y, m_boundingOrigin.Z + m_boundingSize.Z);
foreach (string serialisedSceneObject in serialisedSceneObjects)
{
/*
m_log.DebugFormat("[ARCHIVER]: Loading xml with raw size {0}", serialisedSceneObject.Length);
// Really large xml files (multi megabyte) appear to cause
// memory problems
// when loading the xml. But don't enable this check yet
if (serialisedSceneObject.Length > 5000000)
{
m_log.Error("[ARCHIVER]: Ignoring xml since size > 5000000);");
continue;
}
*/
SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
Vector3 pos = sceneObject.AbsolutePosition;
if (m_debug)
m_log.DebugFormat("[ARCHIVER]: Loading object from OAR with original scene position {0}.", pos.ToString());
// Happily this does not do much to the object since it hasn't been added to the scene yet
if (!sceneObject.IsAttachment)
{
if (m_rotation != 0f)
{
//fix the rotation center to the middle of the incoming region now as it's otherwise hopelessly confusing on varRegions
//as it only works with objects and terrain (using old Merge method) and not parcels
m_rotationCenter.X = m_incomingRegionSize.X / 2;
m_rotationCenter.Y = m_incomingRegionSize.Y / 2;
// Rotate the object
sceneObject.RootPart.RotationOffset = rot * sceneObject.GroupRotation;
// Get object position relative to rotation axis
Vector3 offset = pos - m_rotationCenter;
// Rotate the object position
offset *= rot;
// Restore the object position back to relative to the region
pos = m_rotationCenter + offset;
if (m_debug) m_log.DebugFormat("[ARCHIVER]: After rotation, object from OAR is at scene position {0}.", pos.ToString());
}
if (m_boundingBox)
{
if (pos.X < m_boundingOrigin.X || pos.X >= boundingExtent.X
|| pos.Y < m_boundingOrigin.Y || pos.Y >= boundingExtent.Y
|| pos.Z < m_boundingOrigin.Z || pos.Z >= boundingExtent.Z)
{
if (m_debug) m_log.DebugFormat("[ARCHIVER]: Skipping object from OAR in scene because it's position {0} is outside of bounding cube.", pos.ToString());
continue;
}
//adjust object position to be relative to <0,0> so we can apply the displacement
pos.X -= m_boundingOrigin.X;
pos.Y -= m_boundingOrigin.Y;
}
if (m_displacement != Vector3.Zero)
{
pos += m_displacement;
if (m_debug) m_log.DebugFormat("[ARCHIVER]: After displacement, object from OAR is at scene position {0}.", pos.ToString());
}
sceneObject.AbsolutePosition = pos;
}
if (m_debug)
m_log.DebugFormat("[ARCHIVER]: Placing object from OAR in scene at position {0}. ", pos.ToString());
bool isTelehub = (sceneObject.UUID == oldTelehubUUID) && (oldTelehubUUID != UUID.Zero);
// For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
// on the same region server and multiple examples a single object archive to be imported
// to the same scene (when this is possible).
sceneObject.ResetIDs();
if (isTelehub)
{
// Change the Telehub Object to the new UUID
scene.RegionInfo.RegionSettings.TelehubObject = sceneObject.UUID;
scene.RegionInfo.RegionSettings.Save();
oldTelehubUUID = UUID.Zero;
}
ModifySceneObject(scene, sceneObject);
if (scene.AddRestoredSceneObject(sceneObject, true, false))
{
sceneObjectsLoadedCount++;
sceneObject.CreateScriptInstances(0, false, scene.DefaultScriptEngine, 0);
sceneObject.ResumeScripts();
}
}
m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount);
int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount;
if (ignoredObjects > 0)
m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene or were out of bounds", ignoredObjects);
if (oldTelehubUUID != UUID.Zero)
{
m_log.WarnFormat("[ARCHIVER]: Telehub object not found: {0}", oldTelehubUUID);
scene.RegionInfo.RegionSettings.TelehubObject = UUID.Zero;
scene.RegionInfo.RegionSettings.ClearSpawnPoints();
}
}
/// <summary>
/// Optionally modify a loaded SceneObjectGroup. Currently this just ensures that the
/// User IDs and Group IDs are valid, but other manipulations could be done as well.
/// </summary>
private void ModifySceneObject(Scene scene, SceneObjectGroup sceneObject)
{
// Try to retain the original creator/owner/lastowner if their uuid is present on this grid
// or creator data is present. Otherwise, use the estate owner instead.
foreach (SceneObjectPart part in sceneObject.Parts)
{
if (string.IsNullOrEmpty(part.CreatorData))
{
if (!ResolveUserUuid(scene, part.CreatorID))
part.CreatorID = m_defaultUser;
}
if (UserManager != null)
UserManager.AddUser(part.CreatorID, part.CreatorData);
if (!(ResolveUserUuid(scene, part.OwnerID) || ResolveGroupUuid(part.OwnerID)))
part.OwnerID = m_defaultUser;
if (!(ResolveUserUuid(scene, part.LastOwnerID) || ResolveGroupUuid(part.LastOwnerID)))
part.LastOwnerID = m_defaultUser;
if (!ResolveGroupUuid(part.GroupID))
part.GroupID = UUID.Zero;
// And zap any troublesome sit target information
// part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
// part.SitTargetPosition = new Vector3(0, 0, 0);
// Fix ownership/creator of inventory items
// Not doing so results in inventory items
// being no copy/no mod for everyone
lock (part.TaskInventory)
{
/* avination code disabled for opensim
// And zap any troublesome sit target information
part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
part.SitTargetPosition = new Vector3(0, 0, 0);
*/
// Fix ownership/creator of inventory items
// Not doing so results in inventory items
// being no copy/no mod for everyone
part.TaskInventory.LockItemsForRead(true);
TaskInventoryDictionary inv = part.TaskInventory;
foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
{
if (!(ResolveUserUuid(scene, kvp.Value.OwnerID) || ResolveGroupUuid(kvp.Value.OwnerID)))
{
kvp.Value.OwnerID = m_defaultUser;
}
if (string.IsNullOrEmpty(kvp.Value.CreatorData))
{
if (!ResolveUserUuid(scene, kvp.Value.CreatorID))
kvp.Value.CreatorID = m_defaultUser;
}
if (UserManager != null)
UserManager.AddUser(kvp.Value.CreatorID, kvp.Value.CreatorData);
if (!ResolveGroupUuid(kvp.Value.GroupID))
kvp.Value.GroupID = UUID.Zero;
}
part.TaskInventory.LockItemsForRead(false);
}
}
}
/// <summary>
/// Load serialized parcels.
/// </summary>
/// <param name="scene"></param>
/// <param name="serialisedParcels"></param>
protected void LoadParcels(Scene scene, List<string> serialisedParcels)
{
// Reload serialized parcels
m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
List<LandData> landData = new List<LandData>();
ILandObject landObject = scene.RequestModuleInterface<ILandObject>();
List<ILandObject> parcels;
Vector3 parcelDisp = new Vector3(m_displacement.X, m_displacement.Y, 0f);
Vector2 displacement = new Vector2(m_displacement.X, m_displacement.Y);
Vector2 boundingOrigin = new Vector2(m_boundingOrigin.X, m_boundingOrigin.Y);
Vector2 boundingSize = new Vector2(m_boundingSize.X, m_boundingSize.Y);
Vector2 regionSize = new Vector2(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY);
// Gather any existing parcels before we add any more. Later as we add parcels we can check if the new parcel
// data overlays any of the old data, and we can modify and remove (if empty) the old parcel so that there's no conflict
parcels = scene.LandChannel.AllParcels();
foreach (string serialisedParcel in serialisedParcels)
{
LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
bool overrideRegionSize = true; //use the src land parcel data size not the dst region size
bool isEmptyNow;
Vector3 AABBMin;
Vector3 AABBMax;
// create a new LandObject that we can use to manipulate the incoming source parcel data
// this is ok, but just beware that some of the LandObject functions (that we haven't used here) still
// assume we're always using the destination region size
LandData ld = new LandData();
landObject = new LandObject(ld, scene);
landObject.LandData = parcel;
bool[,] srcLandBitmap = landObject.ConvertBytesToLandBitmap(overrideRegionSize);
if (landObject.IsLandBitmapEmpty(srcLandBitmap))
{
m_log.InfoFormat("[ARCHIVER]: Skipping source parcel {0} with GlobalID: {1} LocalID: {2} that has no claimed land.",
parcel.Name, parcel.GlobalID, parcel.LocalID);
continue;
}
//m_log.DebugFormat("[ARCHIVER]: Showing claimed land for source parcel: {0} with GlobalID: {1} LocalID: {2}.",
// parcel.Name, parcel.GlobalID, parcel.LocalID);
//landObject.DebugLandBitmap(srcLandBitmap);
bool[,] dstLandBitmap = landObject.RemapLandBitmap(srcLandBitmap, displacement, m_rotation, boundingOrigin, boundingSize, regionSize, out isEmptyNow, out AABBMin, out AABBMax);
if (isEmptyNow)
{
m_log.WarnFormat("[ARCHIVER]: Not adding destination parcel {0} with GlobalID: {1} LocalID: {2} because, after applying rotation, bounding and displacement, it has no claimed land.",
parcel.Name, parcel.GlobalID, parcel.LocalID);
continue;
}
//m_log.DebugFormat("[ARCHIVER]: Showing claimed land for destination parcel: {0} with GlobalID: {1} LocalID: {2} after applying rotation, bounding and displacement.",
// parcel.Name, parcel.GlobalID, parcel.LocalID);
//landObject.DebugLandBitmap(dstLandBitmap);
landObject.LandBitmap = dstLandBitmap;
parcel.Bitmap = landObject.ConvertLandBitmapToBytes();
parcel.AABBMin = AABBMin;
parcel.AABBMax = AABBMax;
if (m_merge)
{
// give the remapped parcel a new GlobalID, in case we're using the same OAR twice and a bounding cube, displacement and --merge
parcel.GlobalID = UUID.Random();
//now check if the area of this new incoming parcel overlays an area in any existing parcels
//and if so modify or lose the existing parcels
for (int i = 0; i < parcels.Count; i++)
{
if (parcels[i] != null)
{
bool[,] modLandBitmap = parcels[i].ConvertBytesToLandBitmap(overrideRegionSize);
modLandBitmap = parcels[i].RemoveFromLandBitmap(modLandBitmap, dstLandBitmap, out isEmptyNow, out AABBMin, out AABBMax);
if (isEmptyNow)
{
parcels[i] = null;
}
else
{
parcels[i].LandBitmap = modLandBitmap;
parcels[i].LandData.Bitmap = parcels[i].ConvertLandBitmapToBytes();
parcels[i].LandData.AABBMin = AABBMin;
parcels[i].LandData.AABBMax = AABBMax;
}
}
}
}
// Validate User and Group UUID's
if (!ResolveGroupUuid(parcel.GroupID))
parcel.GroupID = UUID.Zero;
if (parcel.IsGroupOwned)
{
if (parcel.GroupID != UUID.Zero)
{
// In group-owned parcels, OwnerID=GroupID. This should already be the case, but let's make sure.
parcel.OwnerID = parcel.GroupID;
}
else
{
parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
parcel.IsGroupOwned = false;
}
}
else
{
if (!ResolveUserUuid(scene, parcel.OwnerID))
parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
}
List<LandAccessEntry> accessList = new List<LandAccessEntry>();
foreach (LandAccessEntry entry in parcel.ParcelAccessList)
{
if (ResolveUserUuid(scene, entry.AgentID))
accessList.Add(entry);
// else, drop this access rule
}
parcel.ParcelAccessList = accessList;
if (m_debug) m_log.DebugFormat("[ARCHIVER]: Adding parcel {0}, local id {1}, owner {2}, group {3}, isGroupOwned {4}, area {5}",
parcel.Name, parcel.LocalID, parcel.OwnerID, parcel.GroupID, parcel.IsGroupOwned, parcel.Area);
landData.Add(parcel);
}
if (m_merge)
{
for (int i = 0; i < parcels.Count; i++) //if merging then we need to also add back in any existing parcels
{
if (parcels[i] != null) landData.Add(parcels[i].LandData);
}
}
m_log.InfoFormat("[ARCHIVER]: Clearing {0} parcels.", parcels.Count);
bool setupDefaultParcel = (landData.Count == 0);
scene.LandChannel.Clear(setupDefaultParcel);
scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count);
}
/// <summary>
/// Look up the given user id to check whether it's one that is valid for this grid.
/// </summary>
/// <param name="scene"></param>
/// <param name="uuid"></param>
/// <returns></returns>
private bool ResolveUserUuid(Scene scene, UUID uuid)
{
lock (m_validUserUuids)
{
if (!m_validUserUuids.ContainsKey(uuid))
{
// Note: we call GetUserAccount() inside the lock because this UserID is likely
// to occur many times, and we only want to query the users service once.
UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, uuid);
m_validUserUuids.Add(uuid, account != null);
}
return m_validUserUuids[uuid];
}
}
/// <summary>
/// Look up the given group id to check whether it's one that is valid for this grid.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
private bool ResolveGroupUuid(UUID uuid)
{
lock (m_validGroupUuids)
{
if (!m_validGroupUuids.ContainsKey(uuid))
{
bool exists;
if (m_groupsModule == null)
{
exists = false;
}
else
{
// Note: we call GetGroupRecord() inside the lock because this GroupID is likely
// to occur many times, and we only want to query the groups service once.
exists = (m_groupsModule.GetGroupRecord(uuid) != null);
}
m_validGroupUuids.Add(uuid, exists);
}
return m_validGroupUuids[uuid];
}
}
/// Load an asset
/// </summary>
/// <param name="assetFilename"></param>
/// <param name="data"></param>
/// <returns>true if asset was successfully loaded, false otherwise</returns>
private bool LoadAsset(string assetPath, byte[] data)
{
// Right now we're nastily obtaining the UUID from the filename
string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
if (i == -1)
{
m_log.ErrorFormat(
"[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
return false;
}
string extension = filename.Substring(i);
string uuid = filename.Remove(filename.Length - extension.Length);
if (m_assetService.GetMetadata(uuid) != null)
{
// m_log.DebugFormat("[ARCHIVER]: found existing asset {0}",uuid);
return true;
}
if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
{
sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
if (assetType == (sbyte)AssetType.Unknown)
{
m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
}
else if (assetType == (sbyte)AssetType.Object)
{
data = SceneObjectSerializer.ModifySerializedObject(UUID.Parse(uuid), data,
sog =>
{
ModifySceneObject(m_rootScene, sog);
return true;
});
if (data == null)
return false;
}
//m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
asset.Data = data;
// We're relying on the asset service to do the sensible thing and not store the asset if it already
// exists.
m_assetService.Store(asset);
/**
* Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
* it might be best done when dearchive takes place on a separate thread
if (asset.Type=AssetType.Texture)
{
IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
if (cacheLayerDecode != null)
cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
}
*/
return true;
}
else
{
m_log.ErrorFormat(
"[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
assetPath, extension);
return false;
}
}
/// <summary>
/// Load region settings data
/// </summary>
/// <param name="scene"></param>
/// <param name="settingsPath"></param>
/// <param name="data"></param>
/// <param name="dearchivedScenes"></param>
/// <returns>
/// true if settings were loaded successfully, false otherwise
/// </returns>
private bool LoadRegionSettings(Scene scene, string settingsPath, byte[] data, DearchiveScenesInfo dearchivedScenes)
{
RegionSettings loadedRegionSettings;
try
{
loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
settingsPath, e);
return false;
}
RegionSettings currentRegionSettings = scene.RegionInfo.RegionSettings;
currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
currentRegionSettings.SunPosition = loadedRegionSettings.SunPosition;
currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
currentRegionSettings.TelehubObject = loadedRegionSettings.TelehubObject;
currentRegionSettings.ClearSpawnPoints();
foreach (SpawnPoint sp in loadedRegionSettings.SpawnPoints())
currentRegionSettings.AddSpawnPoint(sp);
currentRegionSettings.LoadedCreationDateTime = dearchivedScenes.LoadedCreationDateTime;
currentRegionSettings.LoadedCreationID = dearchivedScenes.GetOriginalRegionID(scene.RegionInfo.RegionID).ToString();
currentRegionSettings.Save();
scene.TriggerEstateSunUpdate();
IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
if (estateModule != null)
estateModule.sendRegionHandshakeToAll();
return true;
}
/// <summary>
/// Load terrain data
/// </summary>
/// <param name="scene"></param>
/// <param name="terrainPath"></param>
/// <param name="data"></param>
/// <returns>
/// true if terrain was resolved successfully, false otherwise.
/// </returns>
private bool LoadTerrain(Scene scene, string terrainPath, byte[] data)
{
ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
using (MemoryStream ms = new MemoryStream(data))
{
if (m_displacement != Vector3.Zero || m_rotation != 0f || m_boundingBox)
{
Vector2 boundingOrigin = new Vector2(m_boundingOrigin.X, m_boundingOrigin.Y);
Vector2 boundingSize = new Vector2(m_boundingSize.X, m_boundingSize.Y);
terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, boundingOrigin, boundingSize, ms); ;
}
else
{
terrainModule.LoadFromStream(terrainPath, ms);
}
}
m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
return true;
}
/// <summary>
/// Load oar control file
/// </summary>
/// <param name="path"></param>
/// <param name="data"></param>
/// <param name="dearchivedScenes"></param>
public DearchiveScenesInfo LoadControlFile(string path, byte[] data, DearchiveScenesInfo dearchivedScenes)
{
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
XmlTextReader xtr = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
// Loaded metadata will be empty if no information exists in the archive
dearchivedScenes.LoadedCreationDateTime = 0;
dearchivedScenes.DefaultOriginalID = "";
bool multiRegion = false;
while (xtr.Read())
{
if (xtr.NodeType == XmlNodeType.Element)
{
if (xtr.Name.ToString() == "archive")
{
int majorVersion = int.Parse(xtr["major_version"]);
int minorVersion = int.Parse(xtr["minor_version"]);
string version = string.Format("{0}.{1}", majorVersion, minorVersion);
if (majorVersion > MAX_MAJOR_VERSION)
{
throw new Exception(
string.Format(
"The OAR you are trying to load has major version number of {0} but this version of OpenSim can only load OARs with major version number {1} and below",
majorVersion, MAX_MAJOR_VERSION));
}
m_log.InfoFormat("[ARCHIVER]: Loading OAR with version {0}", version);
}
else if (xtr.Name.ToString() == "datetime")
{
int value;
if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
dearchivedScenes.LoadedCreationDateTime = value;
}
else if (xtr.Name.ToString() == "row")
{
multiRegion = true;
dearchivedScenes.StartRow();
}
else if (xtr.Name.ToString() == "region")
{
dearchivedScenes.StartRegion();
}
else if (xtr.Name.ToString() == "id")
{
string id = xtr.ReadElementContentAsString();
dearchivedScenes.DefaultOriginalID = id;
if(multiRegion)
dearchivedScenes.SetRegionOriginalID(id);
}
else if (xtr.Name.ToString() == "dir")
{
dearchivedScenes.SetRegionDirectory(xtr.ReadElementContentAsString());
}
else if (xtr.Name.ToString() == "size_in_meters")
{
Vector3 value;
string size = "<" + xtr.ReadElementContentAsString() + ",0>";
if (Vector3.TryParse(size, out value))
{
m_incomingRegionSize = value;
if(multiRegion)
dearchivedScenes.SetRegionSize(m_incomingRegionSize);
m_log.DebugFormat("[ARCHIVER]: Found region_size info {0}",
m_incomingRegionSize.ToString());
}
}
}
}
dearchivedScenes.MultiRegionFormat = multiRegion;
if (!multiRegion)
{
// Add the single scene
dearchivedScenes.StartRow();
dearchivedScenes.StartRegion();
dearchivedScenes.SetRegionOriginalID(dearchivedScenes.DefaultOriginalID);
dearchivedScenes.SetRegionDirectory("");
dearchivedScenes.SetRegionSize(m_incomingRegionSize);
}
ControlFileLoaded = true;
return dearchivedScenes;
}
}
}
| |
/*
* 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.Net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Messages.Linden;
using OpenSim.Framework;
namespace OpenSim.Region.ClientStack.Linden
{
public class EventQueueHelper
{
private EventQueueHelper() {} // no construction possible, it's an utility class
private static byte[] ulongToByteArray(ulong uLongValue)
{
// Reverse endianness of RegionHandle
return new byte[8]
{
(byte)((uLongValue >> 56) & 0xff),
(byte)((uLongValue >> 48) & 0xff),
(byte)((uLongValue >> 40) & 0xff),
(byte)((uLongValue >> 32) & 0xff),
(byte)((uLongValue >> 24) & 0xff),
(byte)((uLongValue >> 16) & 0xff),
(byte)((uLongValue >> 8) & 0xff),
(byte)(uLongValue & 0xff)
};
}
// private static byte[] uintToByteArray(uint uIntValue)
// {
// byte[] result = new byte[4];
// Utils.UIntToBytesBig(uIntValue, result, 0);
// return result;
// }
public static OSD BuildEvent(string eventName, OSD eventBody)
{
OSDMap llsdEvent = new OSDMap(2);
llsdEvent.Add("message", new OSDString(eventName));
llsdEvent.Add("body", eventBody);
return llsdEvent;
}
public static OSD EnableSimulator(ulong handle, IPEndPoint endPoint, int regionSizeX, int regionSizeY)
{
OSDMap llsdSimInfo = new OSDMap(5);
llsdSimInfo.Add("Handle", new OSDBinary(ulongToByteArray(handle)));
llsdSimInfo.Add("IP", new OSDBinary(endPoint.Address.GetAddressBytes()));
llsdSimInfo.Add("Port", OSD.FromInteger(endPoint.Port));
llsdSimInfo.Add("RegionSizeX", OSD.FromUInteger((uint)regionSizeX));
llsdSimInfo.Add("RegionSizeY", OSD.FromUInteger((uint)regionSizeY));
OSDArray arr = new OSDArray(1);
arr.Add(llsdSimInfo);
OSDMap llsdBody = new OSDMap(1);
llsdBody.Add("SimulatorInfo", arr);
return BuildEvent("EnableSimulator", llsdBody);
}
/*
public static OSD DisableSimulator(ulong handle)
{
//OSDMap llsdSimInfo = new OSDMap(1);
//llsdSimInfo.Add("Handle", new OSDBinary(regionHandleToByteArray(handle)));
//OSDArray arr = new OSDArray(1);
//arr.Add(llsdSimInfo);
OSDMap llsdBody = new OSDMap(0);
//llsdBody.Add("SimulatorInfo", arr);
return BuildEvent("DisableSimulator", llsdBody);
}
*/
public static OSD CrossRegion(ulong handle, Vector3 pos, Vector3 lookAt,
IPEndPoint newRegionExternalEndPoint,
string capsURL, UUID agentID, UUID sessionID,
int regionSizeX, int regionSizeY)
{
OSDArray lookAtArr = new OSDArray(3);
lookAtArr.Add(OSD.FromReal(lookAt.X));
lookAtArr.Add(OSD.FromReal(lookAt.Y));
lookAtArr.Add(OSD.FromReal(lookAt.Z));
OSDArray positionArr = new OSDArray(3);
positionArr.Add(OSD.FromReal(pos.X));
positionArr.Add(OSD.FromReal(pos.Y));
positionArr.Add(OSD.FromReal(pos.Z));
OSDMap infoMap = new OSDMap(2);
infoMap.Add("LookAt", lookAtArr);
infoMap.Add("Position", positionArr);
OSDArray infoArr = new OSDArray(1);
infoArr.Add(infoMap);
OSDMap agentDataMap = new OSDMap(2);
agentDataMap.Add("AgentID", OSD.FromUUID(agentID));
agentDataMap.Add("SessionID", OSD.FromUUID(sessionID));
OSDArray agentDataArr = new OSDArray(1);
agentDataArr.Add(agentDataMap);
OSDMap regionDataMap = new OSDMap(6);
regionDataMap.Add("RegionHandle", OSD.FromBinary(ulongToByteArray(handle)));
regionDataMap.Add("SeedCapability", OSD.FromString(capsURL));
regionDataMap.Add("SimIP", OSD.FromBinary(newRegionExternalEndPoint.Address.GetAddressBytes()));
regionDataMap.Add("SimPort", OSD.FromInteger(newRegionExternalEndPoint.Port));
regionDataMap.Add("RegionSizeX", OSD.FromUInteger((uint)regionSizeX));
regionDataMap.Add("RegionSizeY", OSD.FromUInteger((uint)regionSizeY));
OSDArray regionDataArr = new OSDArray(1);
regionDataArr.Add(regionDataMap);
OSDMap llsdBody = new OSDMap(3);
llsdBody.Add("Info", infoArr);
llsdBody.Add("AgentData", agentDataArr);
llsdBody.Add("RegionData", regionDataArr);
return BuildEvent("CrossedRegion", llsdBody);
}
public static OSD TeleportFinishEvent(
ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL, UUID agentID,
int regionSizeX, int regionSizeY)
{
// not sure why flags get overwritten here
if ((flags & (uint)TeleportFlags.IsFlying) != 0)
flags = (uint)TeleportFlags.ViaLocation | (uint)TeleportFlags.IsFlying;
else
flags = (uint)TeleportFlags.ViaLocation;
OSDMap info = new OSDMap();
info.Add("AgentID", OSD.FromUUID(agentID));
info.Add("LocationID", OSD.FromInteger(4)); // TODO what is this?
info.Add("RegionHandle", OSD.FromBinary(ulongToByteArray(regionHandle)));
info.Add("SeedCapability", OSD.FromString(capsURL));
info.Add("SimAccess", OSD.FromInteger(simAccess));
info.Add("SimIP", OSD.FromBinary(regionExternalEndPoint.Address.GetAddressBytes()));
info.Add("SimPort", OSD.FromInteger(regionExternalEndPoint.Port));
// info.Add("TeleportFlags", OSD.FromULong(1L << 4)); // AgentManager.TeleportFlags.ViaLocation
info.Add("TeleportFlags", OSD.FromUInteger(flags));
info.Add("RegionSizeX", OSD.FromUInteger((uint)regionSizeX));
info.Add("RegionSizeY", OSD.FromUInteger((uint)regionSizeY));
OSDArray infoArr = new OSDArray();
infoArr.Add(info);
OSDMap body = new OSDMap();
body.Add("Info", infoArr);
return BuildEvent("TeleportFinish", body);
}
public static OSD ScriptRunningReplyEvent(UUID objectID, UUID itemID, bool running, bool mono)
{
OSDMap script = new OSDMap();
script.Add("ObjectID", OSD.FromUUID(objectID));
script.Add("ItemID", OSD.FromUUID(itemID));
script.Add("Running", OSD.FromBoolean(running));
script.Add("Mono", OSD.FromBoolean(mono));
OSDArray scriptArr = new OSDArray();
scriptArr.Add(script);
OSDMap body = new OSDMap();
body.Add("Script", scriptArr);
return BuildEvent("ScriptRunningReply", body);
}
public static OSD EstablishAgentCommunication(UUID agentID, string simIpAndPort, string seedcap,
ulong regionHandle, int regionSizeX, int regionSizeY)
{
OSDMap body = new OSDMap(6)
{
{"agent-id", new OSDUUID(agentID)},
{"sim-ip-and-port", new OSDString(simIpAndPort)},
{"seed-capability", new OSDString(seedcap)},
{"region-handle", OSD.FromULong(regionHandle)},
{"region-size-x", OSD.FromUInteger((uint)regionSizeX)},
{"region-size-y", OSD.FromUInteger((uint)regionSizeY)}
};
return BuildEvent("EstablishAgentCommunication", body);
}
public static OSD KeepAliveEvent()
{
return BuildEvent("FAKEEVENT", new OSDMap());
}
public static OSD AgentParams(UUID agentID, bool checkEstate, int godLevel, bool limitedToEstate)
{
OSDMap body = new OSDMap(4);
body.Add("agent_id", new OSDUUID(agentID));
body.Add("check_estate", new OSDInteger(checkEstate ? 1 : 0));
body.Add("god_level", new OSDInteger(godLevel));
body.Add("limited_to_estate", new OSDInteger(limitedToEstate ? 1 : 0));
return body;
}
public static OSD InstantMessageParams(UUID fromAgent, string message, UUID toAgent,
string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID,
Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket)
{
OSDMap messageParams = new OSDMap(15);
messageParams.Add("type", new OSDInteger((int)dialog));
OSDArray positionArray = new OSDArray(3);
positionArray.Add(OSD.FromReal(position.X));
positionArray.Add(OSD.FromReal(position.Y));
positionArray.Add(OSD.FromReal(position.Z));
messageParams.Add("position", positionArray);
messageParams.Add("region_id", new OSDUUID(UUID.Zero));
messageParams.Add("to_id", new OSDUUID(toAgent));
messageParams.Add("source", new OSDInteger(0));
OSDMap data = new OSDMap(1);
data.Add("binary_bucket", OSD.FromBinary(binaryBucket));
messageParams.Add("data", data);
messageParams.Add("message", new OSDString(message));
messageParams.Add("id", new OSDUUID(transactionID));
messageParams.Add("from_name", new OSDString(fromName));
messageParams.Add("timestamp", new OSDInteger((int)timeStamp));
messageParams.Add("offline", new OSDInteger(offline ? 1 : 0));
messageParams.Add("parent_estate_id", new OSDInteger(parentEstateID));
messageParams.Add("ttl", new OSDInteger((int)ttl));
messageParams.Add("from_id", new OSDUUID(fromAgent));
messageParams.Add("from_group", new OSDInteger(fromGroup ? 1 : 0));
return messageParams;
}
public static OSD InstantMessage(UUID fromAgent, string message, UUID toAgent,
string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID,
Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket,
bool checkEstate, int godLevel, bool limitedToEstate)
{
OSDMap im = new OSDMap(2);
im.Add("message_params", InstantMessageParams(fromAgent, message, toAgent,
fromName, dialog, timeStamp, offline, parentEstateID,
position, ttl, transactionID, fromGroup, binaryBucket));
im.Add("agent_params", AgentParams(fromAgent, checkEstate, godLevel, limitedToEstate));
return im;
}
public static OSD ChatterboxInvitation(UUID sessionID, string sessionName,
UUID fromAgent, string message, UUID toAgent, string fromName, byte dialog,
uint timeStamp, bool offline, int parentEstateID, Vector3 position,
uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket)
{
OSDMap body = new OSDMap(5);
body.Add("session_id", new OSDUUID(sessionID));
body.Add("from_name", new OSDString(fromName));
body.Add("session_name", new OSDString(sessionName));
body.Add("from_id", new OSDUUID(fromAgent));
body.Add("instantmessage", InstantMessage(fromAgent, message, toAgent,
fromName, dialog, timeStamp, offline, parentEstateID, position,
ttl, transactionID, fromGroup, binaryBucket, true, 0, true));
OSDMap chatterboxInvitation = new OSDMap(2);
chatterboxInvitation.Add("message", new OSDString("ChatterBoxInvitation"));
chatterboxInvitation.Add("body", body);
return chatterboxInvitation;
}
public static OSD ChatterBoxSessionAgentListUpdates(UUID sessionID,
UUID agentID, bool canVoiceChat, bool isModerator, bool textMute, bool isEnterorLeave)
{
OSDMap body = new OSDMap();
OSDMap agentUpdates = new OSDMap();
OSDMap infoDetail = new OSDMap();
OSDMap mutes = new OSDMap();
// this should be a list of agents and parameters
// foreach agent
mutes.Add("text", OSD.FromBoolean(textMute));
infoDetail.Add("can_voice_chat", OSD.FromBoolean(canVoiceChat));
infoDetail.Add("is_moderator", OSD.FromBoolean(isModerator));
infoDetail.Add("mutes", mutes);
OSDMap info = new OSDMap();
info.Add("info", infoDetail);
if(isEnterorLeave)
info.Add("transition",OSD.FromString("ENTER"));
else
info.Add("transition",OSD.FromString("LEAVE"));
agentUpdates.Add(agentID.ToString(), info);
// foreach end
body.Add("agent_updates", agentUpdates);
body.Add("session_id", OSD.FromUUID(sessionID));
body.Add("updates", new OSD());
OSDMap chatterBoxSessionAgentListUpdates = new OSDMap();
chatterBoxSessionAgentListUpdates.Add("message", OSD.FromString("ChatterBoxSessionAgentListUpdates"));
chatterBoxSessionAgentListUpdates.Add("body", body);
return chatterBoxSessionAgentListUpdates;
}
public static OSD ChatterBoxForceClose(UUID sessionID, string reason)
{
OSDMap body = new OSDMap(2);
body.Add("session_id", new OSDUUID(sessionID));
body.Add("reason", new OSDString(reason));
OSDMap chatterBoxForceClose = new OSDMap(2);
chatterBoxForceClose.Add("message", new OSDString("ForceCloseChatterBoxSession"));
chatterBoxForceClose.Add("body", body);
return chatterBoxForceClose;
}
public static OSD GroupMembershipData(UUID receiverAgent, GroupMembershipData[] data)
{
OSDArray AgentData = new OSDArray(1);
OSDMap AgentDataMap = new OSDMap(1);
AgentDataMap.Add("AgentID", OSD.FromUUID(receiverAgent));
AgentData.Add(AgentDataMap);
OSDArray GroupData = new OSDArray(data.Length);
OSDArray NewGroupData = new OSDArray(data.Length);
foreach (GroupMembershipData membership in data)
{
OSDMap GroupDataMap = new OSDMap(6);
OSDMap NewGroupDataMap = new OSDMap(1);
GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID));
GroupDataMap.Add("GroupPowers", OSD.FromULong(membership.GroupPowers));
GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices));
GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture));
GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution));
GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName));
NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile));
GroupData.Add(GroupDataMap);
NewGroupData.Add(NewGroupDataMap);
}
OSDMap llDataStruct = new OSDMap(3);
llDataStruct.Add("AgentData", AgentData);
llDataStruct.Add("GroupData", GroupData);
llDataStruct.Add("NewGroupData", NewGroupData);
return BuildEvent("AgentGroupDataUpdate", llDataStruct);
}
public static OSD PlacesQuery(PlacesReplyPacket PlacesReply)
{
OSDMap placesReply = new OSDMap();
placesReply.Add("message", OSD.FromString("PlacesReplyMessage"));
OSDMap body = new OSDMap();
OSDArray agentData = new OSDArray();
OSDMap agentDataMap = new OSDMap();
agentDataMap.Add("AgentID", OSD.FromUUID(PlacesReply.AgentData.AgentID));
agentDataMap.Add("QueryID", OSD.FromUUID(PlacesReply.AgentData.QueryID));
agentDataMap.Add("TransactionID", OSD.FromUUID(PlacesReply.TransactionData.TransactionID));
agentData.Add(agentDataMap);
body.Add("AgentData", agentData);
OSDArray QueryData = new OSDArray();
foreach (PlacesReplyPacket.QueryDataBlock groupDataBlock in PlacesReply.QueryData)
{
OSDMap QueryDataMap = new OSDMap();
QueryDataMap.Add("ActualArea", OSD.FromInteger(groupDataBlock.ActualArea));
QueryDataMap.Add("BillableArea", OSD.FromInteger(groupDataBlock.BillableArea));
QueryDataMap.Add("Description", OSD.FromBinary(groupDataBlock.Desc));
QueryDataMap.Add("Dwell", OSD.FromInteger((int)groupDataBlock.Dwell));
QueryDataMap.Add("Flags", OSD.FromString(Convert.ToString(groupDataBlock.Flags)));
QueryDataMap.Add("GlobalX", OSD.FromInteger((int)groupDataBlock.GlobalX));
QueryDataMap.Add("GlobalY", OSD.FromInteger((int)groupDataBlock.GlobalY));
QueryDataMap.Add("GlobalZ", OSD.FromInteger((int)groupDataBlock.GlobalZ));
QueryDataMap.Add("Name", OSD.FromBinary(groupDataBlock.Name));
QueryDataMap.Add("OwnerID", OSD.FromUUID(groupDataBlock.OwnerID));
QueryDataMap.Add("SimName", OSD.FromBinary(groupDataBlock.SimName));
QueryDataMap.Add("SnapShotID", OSD.FromUUID(groupDataBlock.SnapshotID));
QueryDataMap.Add("ProductSku", OSD.FromInteger(0));
QueryDataMap.Add("Price", OSD.FromInteger(groupDataBlock.Price));
QueryData.Add(QueryDataMap);
}
body.Add("QueryData", QueryData);
placesReply.Add("QueryData[]", body);
return placesReply;
}
public static OSD ParcelProperties(ParcelPropertiesMessage parcelPropertiesMessage)
{
OSDMap message = new OSDMap();
message.Add("message", OSD.FromString("ParcelProperties"));
OSD message_body = parcelPropertiesMessage.Serialize();
message.Add("body", message_body);
return message;
}
public static OSD partPhysicsProperties(uint localID, byte physhapetype,
float density, float friction, float bounce, float gravmod)
{
OSDMap physinfo = new OSDMap(6);
physinfo["LocalID"] = localID;
physinfo["Density"] = density;
physinfo["Friction"] = friction;
physinfo["GravityMultiplier"] = gravmod;
physinfo["Restitution"] = bounce;
physinfo["PhysicsShapeType"] = (int)physhapetype;
OSDArray array = new OSDArray(1);
array.Add(physinfo);
OSDMap llsdBody = new OSDMap(1);
llsdBody.Add("ObjectData", array);
return BuildEvent("ObjectPhysicsProperties", llsdBody);
}
}
}
| |
// 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.IO;
using System.Linq;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class CustomAttributeBuilderTests
{
public static IEnumerable<object[]> Ctor_TestData()
{
string stringValue1 = "TestString1";
string stringValue2 = "TestString2";
int intValue1 = 10;
int intValue2 = 20;
// 2 ctor, 0 properties, 1 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[0], new object[0],
new object[] { intValue2, null, stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt) }, new object[] { intValue2 },
new object[] { intValue2, null, stringValue1, intValue1 }
};
// 2 ctor, 0 properties, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[0], new object[0],
new object[] { 0, null, stringValue1, intValue1 },
new string[0], new object[0],
new object[] { 0, null, stringValue1, intValue1 }
};
// 0 ctor, 0 properties, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[0], new object[0],
new object[] { 0, null, null, 0 },
new string[0], new object[0],
new object[] { 0, null, null, 0 }
};
// 0 ctor, 0 properties, 1 field
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[0], new object[0],
new object[] { intValue1, null, null, 0 },
new string[] { nameof(TestAttribute.TestInt) }, new object[] { intValue1 },
new object[] { intValue1, null, null, 0 }
};
// 0 ctor, 0 properties, 2 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[0], new object[0],
new object[] { intValue1, stringValue1, null, 0 },
new string[] { nameof(TestAttribute.TestInt), nameof(TestAttribute.TestStringField) }, new object[] { intValue1, stringValue1 },
new object[] { intValue1, stringValue1, null, 0 }
};
// 2 ctor, 0 properties, 2 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[0], new object[0],
new object[] { intValue2, stringValue2, stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt), nameof(TestAttribute.TestStringField) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 }
};
// 0 ctor, 0 properties,1 field
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[0], new object[0],
new object[] { 0, stringValue1, null, 0 },
new string[] { nameof(TestAttribute.TestStringField) }, new object[] { stringValue1 },
new object[] { 0, stringValue1, null, 0 }
};
// 2 ctor, 2 properties, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 },
new object[0], new object[0],
new object[] { intValue2, stringValue2, stringValue1, intValue1 }
};
// 2 ctor, 1 property, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt32) }, new object[] { intValue2 },
new object[] { intValue2, null, stringValue1, intValue1 },
new object[0], new object[0],
new object[] { intValue2, null, stringValue1, intValue1 }
};
// 0 ctor, 1 property, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[] { nameof(TestAttribute.TestInt32) }, new object[] { intValue2 },
new object[] { intValue2, null, null, 0 },
new object[0], new object[0],
new object[] { intValue2, null, null, 0 }
};
// 0 ctor, 2 properties, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, null, 0 },
new object[0], new object[0],
new object[] { intValue2, stringValue2, null, 0 }
};
// 4 ctor, 0 fields, 2 properties
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int), typeof(string), typeof(int) }), new object[] { stringValue1, intValue1, stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 },
new string[0], new object[0],
new object[] { intValue2, stringValue2, stringValue1, intValue1 }
};
// 2 ctor, 2 property, 2 field
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt), nameof(TestAttribute.TestStringField) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 }
};
// 2 ctor, 1 property, 1 field
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestString) }, new object[] { stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt) }, new object[] { intValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 }
};
// 0 ctor, 2 property, 1 field
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { intValue1, stringValue1 },
new object[] { intValue2, stringValue1, null, 0 },
new string[] { nameof(TestAttribute.TestInt) }, new object[] { intValue2 },
new object[] { intValue2, stringValue1, null, 0 }
};
// 2 ctor, 1 property, 0 field
string shortString = new string('a', 128);
string longString = new string('a', 16384);
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { shortString, intValue1 },
new string[] { nameof(TestAttribute.TestString) }, new object[] { longString },
new object[] { 0, longString, shortString, intValue1 },
new string[0], new object[0],
new object[] { 0, longString, shortString, intValue1 }
};
// 0 ctor, 1 property, 1 field
yield return new object[]
{
typeof(SubAttribute).GetConstructor(new Type[0]), new object[0],
new string[] { nameof(TestAttribute.TestString) }, new object[] { stringValue1 },
new object[] { intValue1, stringValue1, null, 0 },
new string[] { nameof(TestAttribute.TestInt) }, new object[] { intValue1 },
new object[] { intValue1, stringValue1, null, 0 }
};
}
[Theory]
[MemberData(nameof(Ctor_TestData))]
public static void Ctor(ConstructorInfo con, object[] constructorArgs,
string[] propertyNames, object[] propertyValues,
object[] expectedPropertyValues,
string[] fieldNames, object[] fieldValues,
object[] expectedFieldValues)
{
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), propertyNames);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), fieldNames);
Action<CustomAttributeBuilder> verify = attr =>
{
VerifyCustomAttributeBuilder(attr, TestAttribute.AllProperties, expectedPropertyValues, TestAttribute.AllFields, expectedFieldValues);
};
if (namedProperties.Length == 0)
{
if (namedFields.Length == 0)
{
// Use CustomAttributeBuilder(ConstructorInfo, object[])
CustomAttributeBuilder attribute1 = new CustomAttributeBuilder(con, constructorArgs);
verify(attribute1);
}
// Use CustomAttributeBuilder(ConstructorInfo, object[], FieldInfo[], object[])
CustomAttributeBuilder attribute2 = new CustomAttributeBuilder(con, constructorArgs, namedFields, fieldValues);
verify(attribute2);
}
if (namedFields.Length == 0)
{
// Use CustomAttributeBuilder(ConstructorInfo, object[], PropertyInfo[], object[])
CustomAttributeBuilder attribute3 = new CustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues);
verify(attribute3);
}
// Use CustomAttributeBuilder(ConstructorInfo, object[], PropertyInfo[], object[], FieldInfo[], object[])
CustomAttributeBuilder attribute4 = new CustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
verify(attribute4);
}
private static void VerifyCustomAttributeBuilder(CustomAttributeBuilder builder,
PropertyInfo[] propertyNames, object[] propertyValues,
FieldInfo[] fieldNames, object[] fieldValues)
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(builder);
object[] customAttributes = assembly.GetCustomAttributes().ToArray();
Assert.Equal(1, customAttributes.Length);
object customAttribute = customAttributes[0];
for (int i = 0; i < fieldNames.Length; ++i)
{
FieldInfo field = typeof(TestAttribute).GetField(fieldNames[i].Name);
Assert.Equal(fieldValues[i], field.GetValue(customAttribute));
}
for (int i = 0; i < propertyNames.Length; ++i)
{
PropertyInfo property = typeof(TestAttribute).GetProperty(propertyNames[i].Name);
Assert.Equal(propertyValues[i], property.GetValue(customAttribute));
}
}
[Fact]
public static void Ctor_AllPrimitives()
{
ConstructorInfo con = typeof(Primitives).GetConstructors()[0];
object[] constructorArgs = new object[]
{
(sbyte)1, (byte)2, (short)3, (ushort)4, 5, (uint)6, (long)7, (ulong)8,
(SByteEnum)9, (ByteEnum)10, (ShortEnum)11, (UShortEnum)12, (IntEnum)13, (UIntEnum)14, (LongEnum)15, (ULongEnum)16,
(char)17, true, 2.0f, 2.1,
"abc", typeof(object), new int[] { 24, 25, 26 }, null
};
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(Primitives), new string[]
{
nameof(Primitives.SByteProperty), nameof(Primitives.ByteProperty), nameof(Primitives.ShortProperty), nameof(Primitives.UShortProperty), nameof(Primitives.IntProperty), nameof(Primitives.UIntProperty), nameof(Primitives.LongProperty), nameof(Primitives.ULongProperty),
nameof(Primitives.SByteEnumProperty), nameof(Primitives.ByteEnumProperty), nameof(Primitives.ShortEnumProperty), nameof(Primitives.UShortEnumProperty), nameof(Primitives.IntEnumProperty), nameof(Primitives.UIntEnumProperty), nameof(Primitives.LongEnumProperty), nameof(Primitives.ULongEnumProperty),
nameof(Primitives.CharProperty), nameof(Primitives.BoolProperty), nameof(Primitives.FloatProperty), nameof(Primitives.DoubleProperty),
nameof(Primitives.StringProperty), nameof(Primitives.TypeProperty), nameof(Primitives.ArrayProperty), nameof(Primitives.ObjectProperty)
});
object[] propertyValues = new object[]
{
(sbyte)27, (byte)28, (short)29, (ushort)30, 31, (uint)32, (long)33, (ulong)34,
(SByteEnum)35, (ByteEnum)36, (ShortEnum)37, (UShortEnum)38, (IntEnum)39, (UIntEnum)40, (LongEnum)41, (ULongEnum)42,
(char)43, false, 4.4f, 4.5,
"def", typeof(bool), new int[] { 48, 49, 50 }, "stringAsObject"
};
FieldInfo[] namedFields = Helpers.GetFields(typeof(Primitives), new string[]
{
nameof(Primitives.SByteField), nameof(Primitives.ByteField), nameof(Primitives.ShortField), nameof(Primitives.UShortField), nameof(Primitives.IntField), nameof(Primitives.UIntField), nameof(Primitives.LongField), nameof(Primitives.ULongField),
nameof(Primitives.SByteEnumField), nameof(Primitives.ByteEnumField), nameof(Primitives.ShortEnumField), nameof(Primitives.UShortEnumField), nameof(Primitives.IntEnumField), nameof(Primitives.UIntEnumField), nameof(Primitives.LongEnumField), nameof(Primitives.ULongEnumField),
nameof(Primitives.CharField), nameof(Primitives.BoolField), nameof(Primitives.FloatField), nameof(Primitives.DoubleField),
nameof(Primitives.StringField), nameof(Primitives.TypeField), nameof(Primitives.ArrayField), nameof(Primitives.ObjectField)
});
object[] fieldValues = new object[]
{
(sbyte)51, (byte)52, (short)53, (ushort)54, 55, (uint)56, (long)57, (ulong)58,
(SByteEnum)59, (ByteEnum)60, (ShortEnum)61, (UShortEnum)62, (IntEnum)63, (UIntEnum)64, (LongEnum)65, (ULongEnum)66,
(char)67, true, 6.8f, 6.9,
null, null, null, 70
};
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attributeBuilder);
object[] customAttributes = assembly.GetCustomAttributes().ToArray();
Assert.Equal(1, customAttributes.Length);
Primitives attribute = (Primitives)customAttributes[0];
// Constructor: primitives
Assert.Equal(constructorArgs[0], attribute.SByteConstructor);
Assert.Equal(constructorArgs[1], attribute.ByteConstructor);
Assert.Equal(constructorArgs[2], attribute.ShortConstructor);
Assert.Equal(constructorArgs[3], attribute.UShortConstructor);
Assert.Equal(constructorArgs[4], attribute.IntConstructor);
Assert.Equal(constructorArgs[5], attribute.UIntConstructor);
Assert.Equal(constructorArgs[6], attribute.LongConstructor);
Assert.Equal(constructorArgs[7], attribute.ULongConstructor);
// Constructors: enums
Assert.Equal(constructorArgs[8], attribute.SByteEnumConstructor);
Assert.Equal(constructorArgs[9], attribute.ByteEnumConstructor);
Assert.Equal(constructorArgs[10], attribute.ShortEnumConstructor);
Assert.Equal(constructorArgs[11], attribute.UShortEnumConstructor);
Assert.Equal(constructorArgs[12], attribute.IntEnumConstructor);
Assert.Equal(constructorArgs[13], attribute.UIntEnumConstructor);
Assert.Equal(constructorArgs[14], attribute.LongEnumConstructor);
Assert.Equal(constructorArgs[15], attribute.ULongEnumConstructor);
// Constructors: other primitives
Assert.Equal(constructorArgs[16], attribute.CharConstructor);
Assert.Equal(constructorArgs[17], attribute.BoolConstructor);
Assert.Equal(constructorArgs[18], attribute.FloatConstructor);
Assert.Equal(constructorArgs[19], attribute.DoubleConstructor);
// Constructors: misc
Assert.Equal(constructorArgs[20], attribute.StringConstructor);
Assert.Equal(constructorArgs[21], attribute.TypeConstructor);
Assert.Equal(constructorArgs[22], attribute.ArrayConstructor);
Assert.Equal(constructorArgs[23], attribute.ObjectConstructor);
// Field: primitives
Assert.Equal(fieldValues[0], attribute.SByteField);
Assert.Equal(fieldValues[1], attribute.ByteField);
Assert.Equal(fieldValues[2], attribute.ShortField);
Assert.Equal(fieldValues[3], attribute.UShortField);
Assert.Equal(fieldValues[4], attribute.IntField);
Assert.Equal(fieldValues[5], attribute.UIntField);
Assert.Equal(fieldValues[6], attribute.LongField);
Assert.Equal(fieldValues[7], attribute.ULongField);
// Fields: enums
Assert.Equal(fieldValues[8], attribute.SByteEnumField);
Assert.Equal(fieldValues[9], attribute.ByteEnumField);
Assert.Equal(fieldValues[10], attribute.ShortEnumField);
Assert.Equal(fieldValues[11], attribute.UShortEnumField);
Assert.Equal(fieldValues[12], attribute.IntEnumField);
Assert.Equal(fieldValues[13], attribute.UIntEnumField);
Assert.Equal(fieldValues[14], attribute.LongEnumField);
Assert.Equal(fieldValues[15], attribute.ULongEnumField);
// Fields: other primitives
Assert.Equal(fieldValues[16], attribute.CharField);
Assert.Equal(fieldValues[17], attribute.BoolField);
Assert.Equal(fieldValues[18], attribute.FloatField);
Assert.Equal(fieldValues[19], attribute.DoubleField);
// Fields: misc
Assert.Equal(fieldValues[20], attribute.StringField);
Assert.Equal(fieldValues[21], attribute.TypeField);
Assert.Equal(fieldValues[22], attribute.ArrayField);
Assert.Equal(fieldValues[23], attribute.ObjectField);
// Properties: primitives
Assert.Equal(propertyValues[0], attribute.SByteProperty);
Assert.Equal(propertyValues[1], attribute.ByteProperty);
Assert.Equal(propertyValues[2], attribute.ShortProperty);
Assert.Equal(propertyValues[3], attribute.UShortProperty);
Assert.Equal(propertyValues[4], attribute.IntProperty);
Assert.Equal(propertyValues[5], attribute.UIntProperty);
Assert.Equal(propertyValues[6], attribute.LongProperty);
Assert.Equal(propertyValues[7], attribute.ULongProperty);
// Properties: enums
Assert.Equal(propertyValues[8], attribute.SByteEnumProperty);
Assert.Equal(propertyValues[9], attribute.ByteEnumProperty);
Assert.Equal(propertyValues[10], attribute.ShortEnumProperty);
Assert.Equal(propertyValues[11], attribute.UShortEnumProperty);
Assert.Equal(propertyValues[12], attribute.IntEnumProperty);
Assert.Equal(propertyValues[13], attribute.UIntEnumProperty);
Assert.Equal(propertyValues[14], attribute.LongEnumProperty);
Assert.Equal(propertyValues[15], attribute.ULongEnumProperty);
// Properties: other primitives
Assert.Equal(propertyValues[16], attribute.CharProperty);
Assert.Equal(propertyValues[17], attribute.BoolProperty);
Assert.Equal(propertyValues[18], attribute.FloatProperty);
Assert.Equal(propertyValues[19], attribute.DoubleProperty);
// Properties: misc
Assert.Equal(propertyValues[20], attribute.StringProperty);
Assert.Equal(propertyValues[21], attribute.TypeProperty);
Assert.Equal(propertyValues[22], attribute.ArrayProperty);
Assert.Equal(propertyValues[23], attribute.ObjectProperty);
}
public static IEnumerable<object[]> Ctor_RefEmitParameters_TestData()
{
AssemblyBuilder assemblyBuilder = Helpers.DynamicAssembly();
TypeBuilder typeBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule").DefineType("DynamicType", TypeAttributes.Public, typeof(Attribute));
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]);
constructorBuilder.GetILGenerator().Emit(OpCodes.Ret);
FieldBuilder fieldBuilder = typeBuilder.DefineField("Field", typeof(int), FieldAttributes.Public);
FieldBuilder fieldBuilderProperty = typeBuilder.DefineField("PropertyField", typeof(int), FieldAttributes.Public);
PropertyBuilder propertyBuilder = typeBuilder.DefineProperty("Property", PropertyAttributes.None, typeof(int), new Type[0]);
MethodBuilder setMethod = typeBuilder.DefineMethod("set_Property", MethodAttributes.Public, typeof(void), new Type[] { typeof(int) });
ILGenerator setMethodGenerator = setMethod.GetILGenerator();
setMethodGenerator.Emit(OpCodes.Ldarg_0);
setMethodGenerator.Emit(OpCodes.Ldarg_1);
setMethodGenerator.Emit(OpCodes.Stfld, fieldBuilderProperty);
setMethodGenerator.Emit(OpCodes.Ret);
propertyBuilder.SetSetMethod(setMethod);
Type createdType = typeBuilder.CreateTypeInfo().AsType();
// ConstructorBuilder, PropertyInfo, FieldInfo
yield return new object[]
{
constructorBuilder, new object[0],
new PropertyInfo[] { createdType.GetProperty(propertyBuilder.Name) }, new object[] { 1 },
new FieldInfo[] { createdType.GetField(fieldBuilder.Name) }, new object[] { 2 }
};
// ConstructorInfo, PropertyBuilder, FieldBuilder
yield return new object[]
{
createdType.GetConstructor(new Type[0]), new object[0],
new PropertyInfo[] { propertyBuilder }, new object[] { 1 },
new FieldInfo[] { fieldBuilder }, new object[] { 2 }
};
// ConstructorBuilder, PropertyBuilder, FieldBuilder
yield return new object[]
{
constructorBuilder, new object[0],
new PropertyInfo[] { propertyBuilder }, new object[] { 1 },
new FieldInfo[] { fieldBuilder }, new object[] { 2 }
};
}
[Theory]
[MemberData(nameof(Ctor_RefEmitParameters_TestData))]
public static void Ctor_RefEmitParameters(ConstructorInfo con, object[] constructorArgs,
PropertyInfo[] namedProperties, object[] propertyValues,
FieldInfo[] namedFields, object[] fieldValues)
{
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, namedFields, fieldValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
object createdAttribute = assembly.GetCustomAttributes().First();
Assert.Equal(propertyValues[0], createdAttribute.GetType().GetField("PropertyField").GetValue(createdAttribute));
Assert.Equal(fieldValues[0], createdAttribute.GetType().GetField("Field").GetValue(createdAttribute));
}
[Theory]
[InlineData(nameof(TestAttribute.ReadonlyField))]
[InlineData(nameof(TestAttribute.StaticField))]
[InlineData(nameof(TestAttribute.StaticReadonlyField))]
public void NamedFields_ContainsReadonlyOrStaticField_Works(string name)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = new FieldInfo[] { typeof(TestAttribute).GetField(name) };
object[] fieldValues = new object[] { 5 };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
object customAttribute = assembly.GetCustomAttributes().First();
Assert.Equal(fieldValues[0], namedFields[0].GetValue(namedFields[0].IsStatic ? null : customAttribute));
}
[Fact]
public void NamedProperties_StaticProperty_Works()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = new PropertyInfo[] { typeof(TestAttribute).GetProperty(nameof(TestAttribute.StaticProperty)) };
object[] propertyValues = new object[] { 5 };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
object customAttribute = assembly.GetCustomAttributes().First();
Assert.Equal(propertyValues[0], TestAttribute.StaticProperty);
}
[Theory]
[InlineData(typeof(PrivateAttribute))]
[InlineData(typeof(NotAnAttribute))]
public static void ClassNotSupportedAsAttribute_DoesNotThrow_DoesNotSet(Type type)
{
ConstructorInfo con = type.GetConstructor(new Type[0]);
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0]);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
Assert.Empty(assembly.GetCustomAttributes());
}
[Fact]
public static void NullConstructor_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("con", () => new CustomAttributeBuilder(null, new object[0]));
AssertExtensions.Throws<ArgumentNullException>("con", () => new CustomAttributeBuilder(null, new object[0], new FieldInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentNullException>("con", () => new CustomAttributeBuilder(null, new object[0], new PropertyInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentNullException>("con", () => new CustomAttributeBuilder(null, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
public static void StaticConstructor_ThrowsArgumentException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).First();
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new FieldInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
public static void PrivateConstructor_ThrowsArgumentException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).First();
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new FieldInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Theory]
[InlineData(CallingConventions.Any)]
[InlineData(CallingConventions.VarArgs)]
public static void ConstructorHasNonStandardCallingConvention_ThrowsArgumentException(CallingConventions callingConvention)
{
TypeBuilder typeBuilder = Helpers.DynamicType(TypeAttributes.Public);
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, callingConvention, new Type[0]);
constructorBuilder.GetILGenerator().Emit(OpCodes.Ret);
ConstructorInfo con = typeBuilder.CreateTypeInfo().AsType().GetConstructor(new Type[0]);
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new FieldInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
public static void NullConstructorArgs_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[] { typeof(int) });
AssertExtensions.Throws<ArgumentNullException>("constructorArgs", () => new CustomAttributeBuilder(con, null));
AssertExtensions.Throws<ArgumentNullException>("constructorArgs", () => new CustomAttributeBuilder(con, null, new FieldInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentNullException>("constructorArgs", () => new CustomAttributeBuilder(con, null, new PropertyInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentNullException>("constructorArgs", () => new CustomAttributeBuilder(con, null, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
public static IEnumerable<object[]> NotSupportedObject_Constructor_TestData()
{
yield return new object[] { new int[0, 0] };
yield return new object[] { Enum.GetValues(CreateEnum(typeof(char), 'a')).GetValue(0) };
yield return new object[] { Enum.GetValues(CreateEnum(typeof(bool), true)).GetValue(0) };
}
public static IEnumerable<object[]> FloatEnum_DoubleEnum_TestData()
{
yield return new object[] { Enum.GetValues(CreateEnum(typeof(float), 0.0f)).GetValue(0) };
yield return new object[] { Enum.GetValues(CreateEnum(typeof(double), 0.0)).GetValue(0) };
}
public static IEnumerable<object[]> NotSupportedObject_Others_TestData()
{
yield return new object[] { new Guid() };
yield return new object[] { new int[5, 5] };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Netfx doesn't support Enum.GetEnumName for float or double enums.")]
[MemberData(nameof(FloatEnum_DoubleEnum_TestData))]
public void ConstructorArgsContainsFloatEnumOrDoubleEnum_ThrowsArgumentException(object value)
{
NotSupportedObjectInConstructorArgs_ThrowsArgumentException(value);
}
[Theory]
[MemberData(nameof(NotSupportedObject_Constructor_TestData))]
[MemberData(nameof(NotSupportedObject_Others_TestData))]
public static void NotSupportedObjectInConstructorArgs_ThrowsArgumentException(object value)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[] { typeof(object) });
object[] constructorArgs = new object[] { value };
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new FieldInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Theory]
[InlineData(new Type[] { typeof(int) }, new object[] { 123, false })]
[InlineData(new Type[] { typeof(int), typeof(bool) }, new object[] { false, 123 })]
[InlineData(new Type[] { typeof(string), typeof(int), typeof(string), typeof(int) }, new object[] { "TestString", 10 })]
public void ConstructorAndConstructorArgsDontMatch_ThrowsArgumentException(Type[] constructorTypes, object[] constructorArgs)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(constructorTypes);
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new FieldInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
public static IEnumerable<object[]> IntPtrAttributeTypes_TestData()
{
yield return new object[] { typeof(IntPtr), (IntPtr)1 };
yield return new object[] { typeof(UIntPtr), (UIntPtr)1 };
}
public static IEnumerable<object[]> InvalidAttributeTypes_TestData()
{
yield return new object[] { typeof(Guid), new Guid() };
yield return new object[] { typeof(int[,]), new int[5, 5] };
yield return new object[] { CreateEnum(typeof(char), 'a'), 'a' };
yield return new object[] { CreateEnum(typeof(bool), false), true };
yield return new object[] { CreateEnum(typeof(float), 1.0f), 1.0f };
yield return new object[] { CreateEnum(typeof(double), 1.0), 1.0 };
yield return new object[] { CreateEnum(typeof(IntPtr)), (IntPtr)1 };
yield return new object[] { CreateEnum(typeof(UIntPtr)), (UIntPtr)1 };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Coreclr fixed an issue where IntPtr/UIntPtr in constructorParameters causes a corrupt created binary.")]
[MemberData(nameof(IntPtrAttributeTypes_TestData))]
public void ConstructorParametersContainsIntPtrOrUIntPtrArgument_ThrowsArgumentException(Type type, object value)
{
ConstructorParametersNotSupportedInAttributes_ThrowsArgumentException(type, value);
}
[Theory]
[MemberData(nameof(InvalidAttributeTypes_TestData))]
public void ConstructorParametersNotSupportedInAttributes_ThrowsArgumentException(Type type, object value)
{
TypeBuilder typeBuilder = Helpers.DynamicType(TypeAttributes.Public);
ConstructorInfo con = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { type });
object[] constructorArgs = new object[] { value };
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new FieldInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Used to throw a NullReferenceException, see issue #11702.")]
public void NullValueForPrimitiveTypeInConstructorArgs_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[] { typeof(int) });
object[] constructorArgs = new object[] { null };
AssertExtensions.Throws<ArgumentNullException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs));
AssertExtensions.Throws<ArgumentNullException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new FieldInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentNullException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentNullException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
public static IEnumerable<object[]> NotSupportedPrimitives_TestData()
{
yield return new object[] { (IntPtr)1 };
yield return new object[] { (UIntPtr)1 };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Coreclr fixed an issue where IntPtr/UIntPtr in constructorArgs causes a corrupt created binary.")]
[MemberData(nameof(NotSupportedPrimitives_TestData))]
public static void NotSupportedPrimitiveInConstructorArgs_ThrowsArgumentException(object value)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[] { typeof(object) });
object[] constructorArgs = new object[] { value };
AssertExtensions.Throws<ArgumentException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs));
AssertExtensions.Throws<ArgumentException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new FieldInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
public static void DynamicTypeInConstructorArgs_ThrowsFileNotFoundExceptionOnCreation()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
TypeBuilder type = assembly.DefineDynamicModule("DynamicModule").DefineType("DynamicType");
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[] { typeof(object) });
object[] constructorArgs = new object[] { type };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, constructorArgs);
assembly.SetCustomAttribute(attribute);
Assert.Throws<FileNotFoundException>(() => assembly.GetCustomAttributes());
}
[Fact]
public static void NullNamedFields_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
AssertExtensions.Throws<ArgumentNullException>("namedFields", () => new CustomAttributeBuilder(con, new object[0], (FieldInfo[])null, new object[0]));
AssertExtensions.Throws<ArgumentNullException>("namedFields", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], null, new object[0]));
}
[Theory]
[MemberData(nameof(InvalidAttributeTypes_TestData))]
public void NamedFields_FieldTypeNotSupportedInAttributes_ThrowsArgumentException(Type type, object value)
{
TypeBuilder typeBuilder = Helpers.DynamicType(TypeAttributes.Public);
FieldInfo field = typeBuilder.DefineField("Field", type, FieldAttributes.Public);
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = new FieldInfo[] { field };
object[] fieldValues = new object[] { value };
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, fieldValues));
}
public static IEnumerable<object[]> FieldDoesntBelongToConstructorDeclaringType_TestData()
{
// Different declaring type
yield return new object[] { typeof(TestAttribute).GetConstructor(new Type[0]), typeof(OtherTestAttribute).GetField(nameof(OtherTestAttribute.Field)) };
// Base class and sub class declaring types
yield return new object[] { typeof(TestAttribute).GetConstructor(new Type[0]), typeof(SubAttribute).GetField(nameof(SubAttribute.SubField)) };
}
[Theory]
[MemberData(nameof(FieldDoesntBelongToConstructorDeclaringType_TestData))]
public void NamedFields_FieldDoesntBelongToConstructorDeclaringType_ThrowsArgumentException(ConstructorInfo con, FieldInfo field)
{
FieldInfo[] namedFields = new FieldInfo[] { field };
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedFields, new object[] { 5 }));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, new object[] { 5 }));
}
[Fact]
public void NamedFields_ContainsConstField_ThrowsArgumentException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = new FieldInfo[] { typeof(TestAttribute).GetField(nameof(TestAttribute.ConstField)) };
object[] propertyValues = new object[] { 5 };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedFields, propertyValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
// CustomAttributeFormatException is not exposed on .NET Core
Exception ex = Assert.ThrowsAny<Exception>(() => assembly.GetCustomAttributes());
Assert.Equal("System.Reflection.CustomAttributeFormatException", ex.GetType().ToString());
}
[Fact]
public static void NullFieldValues_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
AssertExtensions.Throws<ArgumentNullException>("fieldValues", () => new CustomAttributeBuilder(con, new object[0], new FieldInfo[0], null));
AssertExtensions.Throws<ArgumentNullException>("fieldValues", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], null));
}
[Fact]
public static void NullObjectInNamedFields_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = new FieldInfo[] { null };
AssertExtensions.Throws<ArgumentNullException>("namedFields[0]", () => new CustomAttributeBuilder(con, new object[0], namedFields, new object[1]));
AssertExtensions.Throws<ArgumentNullException>("namedFields[0]", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, new object[1]));
}
[Fact]
public static void NullObjectInFieldValues_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), nameof(TestAttribute.TestInt));
object[] fieldValues = new object[] { null };
AssertExtensions.Throws<ArgumentNullException>("fieldValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues));
AssertExtensions.Throws<ArgumentNullException>("fieldValues[0]", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, fieldValues));
}
[Theory]
[MemberData(nameof(NotSupportedObject_Others_TestData))]
public static void NotSupportedObjectInFieldValues_ThrowsArgumentException(object value)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), nameof(TestAttribute.ObjectField));
object[] fieldValues = new object[] { value };
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, fieldValues));
}
[Fact]
public static void ZeroCountMultidimensionalArrayInFieldValues_ChangesToZeroCountJaggedArray()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), nameof(TestAttribute.ObjectField));
object[] fieldValues = new object[] { new int[0, 0] };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
TestAttribute customAttribute = (TestAttribute)assembly.GetCustomAttributes().First();
Array objectField = (Array)customAttribute.ObjectField;
Assert.IsType<int[]>(objectField);
Assert.Equal(0, objectField.Length);
}
[Theory]
[MemberData(nameof(NotSupportedPrimitives_TestData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Coreclr fixed an issue where IntPtr/UIntPtr in fieldValues causes a corrupt created binary.")]
public static void NotSupportedPrimitiveInFieldValues_ThrowsArgumentException(object value)
{
// Used to assert in CustomAttributeBuilder.EmitType(), not writing any CustomAttributeEncoding.
// This created a blob that (probably) generates a CustomAttributeFormatException. In theory, this
// could have been something more uncontrolled, so was fixed. See issue #11703.
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), nameof(TestAttribute.ObjectField));
object[] fieldValues = new object[] { value };
AssertExtensions.Throws<ArgumentException>("fieldValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues));
AssertExtensions.Throws<ArgumentException>("fieldValues[0]", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new FieldInfo[0], namedFields, fieldValues));
}
[Fact]
public static void DynamicTypeInPropertyValues_ThrowsFileNotFoundExceptionOnCreation()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
TypeBuilder type = assembly.DefineDynamicModule("DynamicModule").DefineType("DynamicType");
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), nameof(TestAttribute.ObjectField));
object[] fieldValues = new object[] { type };
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues);
assembly.SetCustomAttribute(attribute);
Assert.Throws<FileNotFoundException>(() => assembly.GetCustomAttributes());
}
[Theory]
[InlineData(new string[] { nameof(TestAttribute.TestInt) }, new object[0], "namedFields, fieldValues")]
[InlineData(new string[] { nameof(TestAttribute.TestInt) }, new object[] { "TestString", 10 }, "namedFields, fieldValues")]
[InlineData(new string[] { nameof(TestAttribute.TestInt), nameof(TestAttribute.TestStringField) }, new object[] { "TestString", 10 }, null)]
[InlineData(new string[] { nameof(TestAttribute.TestStringField) }, new object[] { 10 }, null)]
public void NamedFieldAndFieldValuesDifferentLengths_ThrowsArgumentException(string[] fieldNames, object[] fieldValues, string paramName)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), fieldNames);
AssertExtensions.Throws<ArgumentException>(paramName, () => new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues));
AssertExtensions.Throws<ArgumentException>(paramName, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, fieldValues));
}
[Fact]
public static void NullNamedProperties_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
AssertExtensions.Throws<ArgumentNullException>("namedProperties", () => new CustomAttributeBuilder(con, new object[0], (PropertyInfo[])null, new object[0]));
AssertExtensions.Throws<ArgumentNullException>("namedProperties", () => new CustomAttributeBuilder(con, new object[0], null, new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
public static void NullPropertyValues_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
AssertExtensions.Throws<ArgumentNullException>("propertyValues", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], null));
AssertExtensions.Throws<ArgumentNullException>("propertyValues", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], null, new FieldInfo[0], new object[0]));
}
[Fact]
public static void NullObjectInNamedProperties_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = new PropertyInfo[] { null };
AssertExtensions.Throws<ArgumentNullException>("namedProperties[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, new object[1]));
AssertExtensions.Throws<ArgumentNullException>("namedProperties[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, new object[1], new FieldInfo[0], new object[0]));
}
[Fact]
public static void IndexerInNamedProperties_ThrowsCustomAttributeFormatExceptionOnCreation()
{
ConstructorInfo con = typeof(IndexerAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = new PropertyInfo[] { typeof(IndexerAttribute).GetProperty("Item") };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedProperties, new object[] { "abc" });
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
// CustomAttributeFormatException is not exposed on .NET Core
Exception ex = Assert.ThrowsAny<Exception>(() => assembly.GetCustomAttributes());
Assert.Equal("System.Reflection.CustomAttributeFormatException", ex.GetType().ToString());
}
[Theory]
[MemberData(nameof(InvalidAttributeTypes_TestData))]
[MemberData(nameof(IntPtrAttributeTypes_TestData))]
public void NamedProperties_TypeNotSupportedInAttributes_ThrowsArgumentException(Type type, object value)
{
TypeBuilder typeBuilder = Helpers.DynamicType(TypeAttributes.Public);
PropertyBuilder property = typeBuilder.DefineProperty("Property", PropertyAttributes.None, type, new Type[0]);
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = new PropertyInfo[] { property };
object[] propertyValues = new object[] { value };
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, new FieldInfo[0], new object[0]));
}
public static IEnumerable<object[]> PropertyDoesntBelongToConstructorDeclaringType_TestData()
{
// Different declaring type
yield return new object[] { typeof(TestAttribute).GetConstructor(new Type[0]), typeof(OtherTestAttribute).GetProperty(nameof(OtherTestAttribute.Property)) };
// Base class and sub class declaring types
yield return new object[] { typeof(TestAttribute).GetConstructor(new Type[0]), typeof(SubAttribute).GetProperty(nameof(SubAttribute.SubProperty)) };
}
[Theory]
[MemberData(nameof(PropertyDoesntBelongToConstructorDeclaringType_TestData))]
public void NamedProperties_PropertyDoesntBelongToConstructorDeclaringType_ThrowsArgumentException(ConstructorInfo con, PropertyInfo property)
{
PropertyInfo[] namedProperties = new PropertyInfo[] { property };
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, new object[] { 5 }));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, new object[] { 5 }, new FieldInfo[0], new object[0]));
}
[Fact]
public static void NullObjectInPropertyValues_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), nameof(TestAttribute.TestInt32));
object[] propertyValues = new object[] { null };
AssertExtensions.Throws<ArgumentNullException>("propertyValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues));
AssertExtensions.Throws<ArgumentNullException>("propertyValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, new FieldInfo[0], new object[0]));
}
[Theory]
[MemberData(nameof(NotSupportedObject_Others_TestData))]
public static void NotSupportedObjectInPropertyValues_ThrowsArgumentException(object value)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), nameof(TestAttribute.ObjectProperty));
object[] propertyValues = new object[] { value };
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues));
AssertExtensions.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, new FieldInfo[0], new object[0]));
}
[Fact]
public static void ZeroCountMultidimensionalArrayInPropertyValues_ChangesToZeroCountJaggedArray()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), nameof(TestAttribute.ObjectProperty));
object[] propertyValues = new object[] { new int[0, 0] };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
TestAttribute customAttribute = (TestAttribute)assembly.GetCustomAttributes().First();
Array objectProperty = (Array)customAttribute.ObjectProperty;
Assert.IsType<int[]>(objectProperty);
Assert.Equal(0, objectProperty.Length);
}
[Theory]
[MemberData(nameof(NotSupportedPrimitives_TestData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Coreclr fixed an issue where IntPtr/UIntPtr in propertValues causes a corrupt created binary.")]
public static void NotSupportedPrimitiveInPropertyValues_ThrowsArgumentException(object value)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), nameof(TestAttribute.ObjectProperty));
object[] propertyValues = new object[] { value };
AssertExtensions.Throws<ArgumentException>("propertyValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues));
AssertExtensions.Throws<ArgumentException>("propertyValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, new FieldInfo[0], new object[0]));
}
[Fact]
public static void DynamicTypeInFieldValues_ThrowsFileNotFoundExceptionOnCreation()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
TypeBuilder type = assembly.DefineDynamicModule("DynamicModule").DefineType("DynamicType");
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), nameof(TestAttribute.ObjectProperty));
object[] propertyValues = new object[] { type };
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues);
assembly.SetCustomAttribute(attribute);
Assert.Throws<FileNotFoundException>(() => assembly.GetCustomAttributes());
}
[Theory]
[InlineData(new string[] { nameof(TestAttribute.TestInt32) }, new object[0], "namedProperties, propertyValues")]
[InlineData(new string[0], new object[] { 10 }, "namedProperties, propertyValues")]
[InlineData(new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { "TestString", 10 }, null)]
[InlineData(new string[] { nameof(TestAttribute.GetOnlyInt32) }, new object[] { "TestString" }, null)]
[InlineData(new string[] { nameof(TestAttribute.GetOnlyString) }, new object[] { "TestString" }, null)]
[InlineData(new string[] { nameof(TestAttribute.TestInt32) }, new object[] { "TestString" }, null)]
public void NamedPropertyAndPropertyValuesDifferentLengths_ThrowsArgumentException(string[] propertyNames, object[] propertyValues, string paramName)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), propertyNames);
AssertExtensions.Throws<ArgumentException>(paramName, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues));
AssertExtensions.Throws<ArgumentException>(paramName, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, new FieldInfo[0], new object[0]));
}
private static Type CreateEnum(Type underlyingType, params object[] literalValues)
{
ModuleBuilder module = Helpers.DynamicModule();
EnumBuilder enumBuilder = module.DefineEnum("Name", TypeAttributes.Public, underlyingType);
for (int i = 0; i < (literalValues?.Length ?? 0); i++)
{
enumBuilder.DefineLiteral("Value" + i, literalValues[i]);
}
return enumBuilder.CreateTypeInfo().AsType();
}
}
public class OtherTestAttribute : Attribute
{
public int Property { get; set; }
public int Field;
}
class PrivateAttribute : Attribute { }
public class NotAnAttribute { }
public class Primitives : Attribute
{
public Primitives(sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul,
SByteEnum sbe, ByteEnum be, ShortEnum se, UShortEnum use, IntEnum ie, UIntEnum uie, LongEnum le, ULongEnum ule,
char c, bool bo, float f, double d,
string str, Type t, int[] arr, object obj)
{
SByteConstructor = sb;
ByteConstructor = b;
ShortConstructor = s;
UShortConstructor = us;
IntConstructor = i;
UIntConstructor = ui;
LongConstructor = l;
ULongConstructor = ul;
SByteEnumConstructor = sbe;
ByteEnumConstructor = be;
ShortEnumConstructor = se;
UShortEnumConstructor = use;
IntEnumConstructor = ie;
UIntEnumConstructor = uie;
LongEnumConstructor = le;
ULongEnumConstructor = ule;
CharConstructor = c;
BoolConstructor = bo;
FloatConstructor = f;
DoubleConstructor = d;
StringConstructor = str;
TypeConstructor = t;
ArrayConstructor = arr;
ObjectConstructor = obj;
}
public sbyte SByteConstructor;
public byte ByteConstructor;
public short ShortConstructor;
public ushort UShortConstructor;
public int IntConstructor;
public uint UIntConstructor;
public long LongConstructor;
public ulong ULongConstructor;
public SByteEnum SByteEnumConstructor;
public ByteEnum ByteEnumConstructor;
public ShortEnum ShortEnumConstructor;
public UShortEnum UShortEnumConstructor;
public IntEnum IntEnumConstructor;
public UIntEnum UIntEnumConstructor;
public LongEnum LongEnumConstructor;
public ULongEnum ULongEnumConstructor;
public char CharConstructor;
public bool BoolConstructor;
public float FloatConstructor;
public double DoubleConstructor;
public string StringConstructor;
public Type TypeConstructor;
public int[] ArrayConstructor;
public object ObjectConstructor;
public sbyte SByteProperty { get; set; }
public byte ByteProperty { get; set; }
public short ShortProperty { get; set; }
public ushort UShortProperty { get; set; }
public int IntProperty { get; set; }
public uint UIntProperty { get; set; }
public long LongProperty { get; set; }
public ulong ULongProperty { get; set; }
public SByteEnum SByteEnumProperty { get; set; }
public ByteEnum ByteEnumProperty { get; set; }
public ShortEnum ShortEnumProperty { get; set; }
public UShortEnum UShortEnumProperty { get; set; }
public IntEnum IntEnumProperty { get; set; }
public UIntEnum UIntEnumProperty { get; set; }
public LongEnum LongEnumProperty { get; set; }
public ULongEnum ULongEnumProperty { get; set; }
public char CharProperty { get; set; }
public bool BoolProperty { get; set; }
public float FloatProperty { get; set; }
public double DoubleProperty { get; set; }
public string StringProperty { get; set; }
public Type TypeProperty { get; set; }
public int[] ArrayProperty { get; set; }
public object ObjectProperty { get; set; }
public sbyte SByteField;
public byte ByteField;
public short ShortField;
public ushort UShortField;
public int IntField;
public uint UIntField;
public long LongField;
public ulong ULongField;
public SByteEnum SByteEnumField;
public ByteEnum ByteEnumField;
public ShortEnum ShortEnumField;
public UShortEnum UShortEnumField;
public IntEnum IntEnumField;
public UIntEnum UIntEnumField;
public LongEnum LongEnumField;
public ULongEnum ULongEnumField;
public char CharField;
public bool BoolField;
public float FloatField;
public double DoubleField;
public string StringField;
public Type TypeField;
public int[] ArrayField;
public object ObjectField;
}
public class IndexerAttribute : Attribute
{
public IndexerAttribute() { }
public string this[string s]
{
get { return s; }
set { }
}
}
public enum SByteEnum : sbyte { }
public enum ByteEnum : byte { }
public enum ShortEnum : short { }
public enum UShortEnum : ushort { }
public enum IntEnum : int { }
public enum UIntEnum : uint { }
public enum LongEnum : long { }
public enum ULongEnum : ulong { }
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Specialized;
using System.Configuration.Internal;
namespace System.Configuration
{
public static class ConfigurationManager
{
// The Configuration System
private static volatile IInternalConfigSystem s_configSystem;
// Initialization state
private static volatile InitState s_initState;
private static readonly object s_initLock;
private static volatile Exception s_initError;
static ConfigurationManager()
{
s_initState = InitState.NotStarted;
s_initLock = new object();
}
// to be used by System.Diagnostics to avoid false config results during config init
internal static bool SetConfigurationSystemInProgress
=> (InitState.NotStarted < s_initState) && (s_initState < InitState.Completed);
internal static bool SupportsUserConfig
{
get
{
PrepareConfigSystem();
return s_configSystem.SupportsUserConfig;
}
}
public static NameValueCollection AppSettings
{
get
{
object section = GetSection("appSettings");
if (!(section is NameValueCollection))
{
// If config is null or not the type we expect, the declaration was changed.
// Treat it as a configuration error.
throw new ConfigurationErrorsException(SR.Config_appsettings_declaration_invalid);
}
return (NameValueCollection)section;
}
}
public static ConnectionStringSettingsCollection ConnectionStrings
{
get
{
object section = GetSection("connectionStrings");
// Verify type, and return the collection
if ((section == null) || (section.GetType() != typeof(ConnectionStringsSection)))
{
// If config is null or not the type we expect, the declaration was changed.
// Treat it as a configuration error.
throw new ConfigurationErrorsException(SR.Config_connectionstrings_declaration_invalid);
}
ConnectionStringsSection connectionStringsSection = (ConnectionStringsSection)section;
return connectionStringsSection.ConnectionStrings;
}
}
// Called by ASP.NET to allow hierarchical configuration settings and ASP.NET specific extenstions.
internal static void SetConfigurationSystem(IInternalConfigSystem configSystem, bool initComplete)
{
lock (s_initLock)
{
// It is an error if the configuration system has already been set.
if (s_initState != InitState.NotStarted)
throw new InvalidOperationException(SR.Config_system_already_set);
s_configSystem = configSystem;
s_initState = initComplete ? InitState.Completed : InitState.Usable;
}
}
private static void EnsureConfigurationSystem()
{
// If a configuration system has not yet been set,
// create the DefaultConfigurationSystem for exe's.
lock (s_initLock)
{
if (s_initState >= InitState.Usable) return;
s_initState = InitState.Started;
try
{
try
{
// Create the system, but let it initialize itself when GetConfig is called,
// so that it can handle its own re-entrancy issues during initialization.
//
// When initialization is complete, the DefaultConfigurationSystem will call
// CompleteConfigInit to mark initialization as having completed.
//
// Note: the ClientConfigurationSystem has a 2-stage initialization,
// and that's why s_initState isn't set to InitState.Completed yet.
s_configSystem = new ClientConfigurationSystem();
s_initState = InitState.Usable;
}
catch (Exception e)
{
s_initError =
new ConfigurationErrorsException(SR.Config_client_config_init_error, e);
throw s_initError;
}
}
catch
{
s_initState = InitState.Completed;
throw;
}
}
}
// Set the initialization error.
internal static void SetInitError(Exception initError)
{
s_initError = initError;
}
// Mark intiailization as having completed.
internal static void CompleteConfigInit()
{
lock (s_initLock)
{
s_initState = InitState.Completed;
}
}
private static void PrepareConfigSystem()
{
// Ensure the configuration system is usable.
if (s_initState < InitState.Usable) EnsureConfigurationSystem();
// If there was an initialization error, throw it.
if (s_initError != null) throw s_initError;
}
public static object GetSection(string sectionName)
{
// Avoid unintended AV's by ensuring sectionName is not empty.
// For compatibility, we cannot throw an InvalidArgumentException.
if (string.IsNullOrEmpty(sectionName)) return null;
PrepareConfigSystem();
object section = s_configSystem.GetSection(sectionName);
return section;
}
public static void RefreshSection(string sectionName)
{
// Avoid unintended AV's by ensuring sectionName is not empty.
// For consistency with GetSection, we should not throw an InvalidArgumentException.
if (string.IsNullOrEmpty(sectionName)) return;
PrepareConfigSystem();
s_configSystem.RefreshConfig(sectionName);
}
public static Configuration OpenMachineConfiguration()
{
return OpenExeConfigurationImpl(null, true, ConfigurationUserLevel.None, null);
}
public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)
{
return OpenExeConfigurationImpl(fileMap, true, ConfigurationUserLevel.None, null);
}
public static Configuration OpenExeConfiguration(ConfigurationUserLevel userLevel)
{
return OpenExeConfigurationImpl(null, false, userLevel, null);
}
public static Configuration OpenExeConfiguration(string exePath)
{
return OpenExeConfigurationImpl(null, false, ConfigurationUserLevel.None, exePath);
}
public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap,
ConfigurationUserLevel userLevel)
{
return OpenExeConfigurationImpl(fileMap, false, userLevel, null);
}
public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap,
ConfigurationUserLevel userLevel, bool preLoad)
{
return OpenExeConfigurationImpl(fileMap, false, userLevel, null, preLoad);
}
private static Configuration OpenExeConfigurationImpl(ConfigurationFileMap fileMap, bool isMachine,
ConfigurationUserLevel userLevel, string exePath, bool preLoad = false)
{
// exePath must be specified if not running inside ClientConfigurationSystem
if (!isMachine &&
(((fileMap == null) && (exePath == null)) ||
((fileMap != null) && (((ExeConfigurationFileMap)fileMap).ExeConfigFilename == null))))
{
if ((s_configSystem != null) &&
(s_configSystem.GetType() != typeof(ClientConfigurationSystem)))
throw new ArgumentException(SR.Config_configmanager_open_noexe);
}
Configuration config = ClientConfigurationHost.OpenExeConfiguration(fileMap, isMachine, userLevel, exePath);
if (preLoad) PreloadConfiguration(config);
return config;
}
/// <summary>
/// Recursively loads configuration section groups and sections belonging to a configuration object.
/// </summary>
private static void PreloadConfiguration(Configuration configuration)
{
if (null == configuration) return;
// Preload root-level sections.
foreach (ConfigurationSection section in configuration.Sections) { }
// Recursively preload all section groups and sections.
foreach (ConfigurationSectionGroup sectionGroup in configuration.SectionGroups)
PreloadConfigurationSectionGroup(sectionGroup);
}
private static void PreloadConfigurationSectionGroup(ConfigurationSectionGroup sectionGroup)
{
if (null == sectionGroup) return;
// Preload sections just by iterating.
foreach (ConfigurationSection section in sectionGroup.Sections) { }
// Load child section groups.
foreach (ConfigurationSectionGroup childSectionGroup in sectionGroup.SectionGroups)
PreloadConfigurationSectionGroup(childSectionGroup);
}
private enum InitState
{
// Initialization has not yet started.
NotStarted = 0,
// Initialization has started.
Started,
// The config system can be used, but initialization is not yet complete.
Usable,
// The config system has been completely initialized.
Completed
};
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
using Object = UnityEngine.Object;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
[CustomEditorForRenderPipeline(typeof(PlanarReflectionProbe), typeof(HDRenderPipelineAsset))]
[CanEditMultipleObjects]
sealed class PlanarReflectionProbeEditor : HDProbeEditor<PlanarReflectionProbeUISettingsProvider, SerializedPlanarReflectionProbe>
{
const float k_PreviewHeight = 128;
static Mesh k_QuadMesh;
static Material k_PreviewMaterial;
static Material k_PreviewOutlineMaterial;
List<Texture> m_PreviewedTextures = new List<Texture>();
public override bool HasPreviewGUI()
{
foreach (var p in m_TypedTargets)
{
if (p.texture != null)
return true;
}
return false;
}
public override GUIContent GetPreviewTitle() => EditorGUIUtility.TrTextContent("Planar Reflection");
public override void OnPreviewGUI(Rect r, GUIStyle background)
{
m_PreviewedTextures.Clear();
foreach (var p in m_TypedTargets)
m_PreviewedTextures.Add(p.texture);
var space = Vector2.one;
var rowSize = Mathf.CeilToInt(Mathf.Sqrt(m_PreviewedTextures.Count));
var size = r.size / rowSize - space * (rowSize - 1);
for (var i = 0; i < m_PreviewedTextures.Count; i++)
{
var row = i / rowSize;
var col = i % rowSize;
var itemRect = new Rect(
r.x + size.x * row + ((row > 0) ? (row - 1) * space.x : 0),
r.y + size.y * col + ((col > 0) ? (col - 1) * space.y : 0),
size.x,
size.y);
if (m_PreviewedTextures[i] != null)
EditorGUI.DrawPreviewTexture(itemRect, m_PreviewedTextures[i], CameraEditorUtils.GUITextureBlit2SRGBMaterial, ScaleMode.ScaleToFit, 0, 1);
else
EditorGUI.LabelField(itemRect, EditorGUIUtility.TrTextContent("Not Available"));
}
}
protected override SerializedPlanarReflectionProbe NewSerializedObject(SerializedObject so)
=> new SerializedPlanarReflectionProbe(so);
internal override HDProbe GetTarget(Object editorTarget) => editorTarget as HDProbe;
protected override void DrawAdditionalCaptureSettings(
SerializedPlanarReflectionProbe serialized, Editor owner
)
{
var isReferencePositionRelevant = serialized.probeSettings.mode.intValue != (int)ProbeSettings.Mode.Realtime;
if (!isReferencePositionRelevant)
return;
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(serialized.localReferencePosition, EditorGUIUtility.TrTextContent("Reference Local Position"));
--EditorGUI.indentLevel;
}
protected override void DrawHandles(SerializedPlanarReflectionProbe serialized, Editor owner)
{
base.DrawHandles(serialized, owner);
SceneViewOverlay_Window(EditorGUIUtility.TrTextContent("Planar Probe"), OnOverlayGUI, -100, target);
if (serialized.probeSettings.mode.intValue != (int)ProbeSettings.Mode.Realtime)
{
using (new Handles.DrawingScope(Matrix4x4.TRS(serialized.target.transform.position, serialized.target.transform.rotation, Vector3.one)))
{
var referencePosition = serialized.localReferencePosition.vector3Value;
EditorGUI.BeginChangeCheck();
referencePosition = Handles.PositionHandle(referencePosition, Quaternion.identity);
if (EditorGUI.EndChangeCheck())
serialized.localReferencePosition.vector3Value = referencePosition;
}
}
}
void OnOverlayGUI(Object target, SceneView sceneView)
{
var previewSize = new Rect();
foreach(var p in m_TypedTargets)
{
if (p.texture == null)
continue;
var factor = k_PreviewHeight / p.texture.height;
previewSize.x += p.texture.width * factor;
previewSize.y = k_PreviewHeight;
}
// Get and reserve rect
var cameraRect = GUILayoutUtility.GetRect(previewSize.x, previewSize.y);
if (Event.current.type == EventType.Repaint)
{
var c = new Rect(cameraRect);
foreach(var p in m_TypedTargets)
{
if (p.texture == null)
continue;
var factor = k_PreviewHeight / p.texture.height;
c.width = p.texture.width * factor;
c.height = k_PreviewHeight;
Graphics.DrawTexture(c, p.texture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, GUI.color, CameraEditorUtils.GUITextureBlit2SRGBMaterial);
c.x += c.width;
}
}
}
static Type k_SceneViewOverlay_WindowFunction = Type.GetType("UnityEditor.SceneViewOverlay+WindowFunction,UnityEditor");
static Type k_SceneViewOverlay_WindowDisplayOption = Type.GetType("UnityEditor.SceneViewOverlay+WindowDisplayOption,UnityEditor");
static MethodInfo k_SceneViewOverlay_Window = Type.GetType("UnityEditor.SceneViewOverlay,UnityEditor")
.GetMethod(
"Window",
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public,
null,
CallingConventions.Any,
new[] { typeof(GUIContent), k_SceneViewOverlay_WindowFunction, typeof(int), typeof(Object), k_SceneViewOverlay_WindowDisplayOption, typeof(EditorWindow) },
null);
static void SceneViewOverlay_Window(GUIContent title, Action<Object, SceneView> sceneViewFunc, int order, Object target)
{
k_SceneViewOverlay_Window.Invoke(null, new[]
{
title, DelegateUtility.Cast(sceneViewFunc, k_SceneViewOverlay_WindowFunction),
order,
target,
Enum.ToObject(k_SceneViewOverlay_WindowDisplayOption, 1),
null
});
}
[DrawGizmo(GizmoType.Selected)]
static void DrawSelectedGizmo(PlanarReflectionProbe probe, GizmoType gizmoType)
{
var e = (PlanarReflectionProbeEditor)GetEditorFor(probe);
if (e == null)
return;
var mat = Matrix4x4.TRS(probe.transform.position, probe.transform.rotation, Vector3.one);
InfluenceVolumeUI.DrawGizmos(
probe.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.None,
InfluenceVolumeUI.HandleType.Base | InfluenceVolumeUI.HandleType.Influence
);
DrawCapturePositionGizmo(probe);
}
static void DrawCapturePositionGizmo(PlanarReflectionProbe probe)
{
if (Event.current.type != EventType.Repaint)
return;
// Capture gizmo
if (k_QuadMesh == null)
k_QuadMesh = Resources.GetBuiltinResource<Mesh>("Quad.fbx");
if (k_PreviewMaterial == null)
k_PreviewMaterial = new Material(Shader.Find("Debug/PlanarReflectionProbePreview"));
if (k_PreviewOutlineMaterial == null)
k_PreviewOutlineMaterial = new Material(Shader.Find("Hidden/UnlitTransparentColored"));
var proxyToWorld = probe.proxyToWorld;
var settings = probe.settings;
var mirrorPosition = proxyToWorld.MultiplyPoint(settings.proxySettings.mirrorPositionProxySpace);
var mirrorRotation = proxyToWorld.rotation * settings.proxySettings.mirrorRotationProxySpace * Quaternion.Euler(0, 180, 0);
var renderData = probe.renderData;
var gpuProj = GL.GetGPUProjectionMatrix(renderData.projectionMatrix, true);
var gpuView = renderData.worldToCameraRHS;
var vp = gpuProj * gpuView;
var cameraPositionWS = Vector3.zero;
var capturePositionWS = renderData.capturePosition;
if (SceneView.currentDrawingSceneView?.camera != null)
cameraPositionWS = SceneView.currentDrawingSceneView.camera.transform.position;
if (ShaderConfig.s_CameraRelativeRendering != 0)
{
cameraPositionWS = Vector3.zero;
// For Camera relative rendering, we need to translate with the position of the currently rendering camera
capturePositionWS -= cameraPositionWS;
}
// Draw outline
k_PreviewOutlineMaterial.SetColor("_Color", InfluenceVolumeUI.k_GizmoThemeColorBase);
k_PreviewOutlineMaterial.SetPass(0);
Graphics.DrawMeshNow(k_QuadMesh, Matrix4x4.TRS(mirrorPosition, mirrorRotation, Vector3.one * capturePointPreviewSize * 2.1f));
k_PreviewMaterial.SetTexture("_MainTex", probe.texture);
k_PreviewMaterial.SetMatrix("_CaptureVPMatrix", vp);
k_PreviewMaterial.SetVector("_CameraPositionWS", new Vector4(cameraPositionWS.x, cameraPositionWS.y, -cameraPositionWS.z, 0));
k_PreviewMaterial.SetVector("_CapturePositionWS", new Vector4(capturePositionWS.x, capturePositionWS.y, -capturePositionWS.z, 0));
k_PreviewMaterial.SetPass(0);
Graphics.DrawMeshNow(k_QuadMesh, Matrix4x4.TRS(mirrorPosition, mirrorRotation, Vector3.one * capturePointPreviewSize * 2));
}
}
struct PlanarReflectionProbeUISettingsProvider : HDProbeUI.IProbeUISettingsProvider, InfluenceVolumeUI.IInfluenceUISettingsProvider
{
bool InfluenceVolumeUI.IInfluenceUISettingsProvider.drawOffset => false;
bool InfluenceVolumeUI.IInfluenceUISettingsProvider.drawNormal => false;
bool InfluenceVolumeUI.IInfluenceUISettingsProvider.drawFace => false;
ProbeSettingsOverride HDProbeUI.IProbeUISettingsProvider.displayedCaptureSettings => new ProbeSettingsOverride
{
probe = ProbeSettingsFields.proxyMirrorPositionProxySpace
| ProbeSettingsFields.proxyMirrorRotationProxySpace,
camera = new CameraSettingsOverride
{
camera = (CameraSettingsFields)(-1) & ~(
CameraSettingsFields.flipYMode
| CameraSettingsFields.frustumAspect
| CameraSettingsFields.cullingInvertFaceCulling
| CameraSettingsFields.frustumMode
| CameraSettingsFields.frustumProjectionMatrix
)
}
};
ProbeSettingsOverride HDProbeUI.IProbeUISettingsProvider.overrideableCaptureSettings => new ProbeSettingsOverride
{
probe = ProbeSettingsFields.none,
camera = new CameraSettingsOverride
{
camera = CameraSettingsFields.frustumFieldOfView
}
};
ProbeSettingsOverride HDProbeUI.IProbeUISettingsProvider.displayedAdvancedSettings => new ProbeSettingsOverride
{
probe = ProbeSettingsFields.lightingLightLayer
| ProbeSettingsFields.lightingMultiplier
| ProbeSettingsFields.lightingWeight,
camera = new CameraSettingsOverride
{
camera = CameraSettingsFields.none
}
};
ProbeSettingsOverride HDProbeUI.IProbeUISettingsProvider.overrideableAdvancedSettings => new ProbeSettingsOverride();
Type HDProbeUI.IProbeUISettingsProvider.customTextureType => typeof(Texture2D);
static readonly HDProbeUI.ToolBar[] k_Toolbars =
{
HDProbeUI.ToolBar.InfluenceShape | HDProbeUI.ToolBar.Blend,
HDProbeUI.ToolBar.MirrorPosition | HDProbeUI.ToolBar.MirrorRotation
};
HDProbeUI.ToolBar[] HDProbeUI.IProbeUISettingsProvider.toolbars => k_Toolbars;
static Dictionary<KeyCode, HDProbeUI.ToolBar> k_ToolbarShortCutKey = new Dictionary<KeyCode, HDProbeUI.ToolBar>
{
{ KeyCode.Alpha1, HDProbeUI.ToolBar.InfluenceShape },
{ KeyCode.Alpha2, HDProbeUI.ToolBar.Blend },
{ KeyCode.Alpha3, HDProbeUI.ToolBar.MirrorPosition },
{ KeyCode.Alpha4, HDProbeUI.ToolBar.MirrorRotation }
};
Dictionary<KeyCode, HDProbeUI.ToolBar> HDProbeUI.IProbeUISettingsProvider.shortcuts => k_ToolbarShortCutKey;
}
}
| |
// 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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Completion
{
internal static class CommonCompletionUtilities
{
private const string NonBreakingSpaceString = "\x00A0";
public static TextSpan GetWordSpan(SourceText text, int position,
Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter)
{
int start = position;
while (start > 0 && isWordStartCharacter(text[start - 1]))
{
start--;
}
// If we're brought up in the middle of a word, extend to the end of the word as well.
// This means that if a user brings up the completion list at the start of the word they
// will "insert" the text before what's already there (useful for qualifying existing
// text). However, if they bring up completion in the "middle" of a word, then they will
// "overwrite" the text. Useful for correcting misspellings or just replacing unwanted
// code with new code.
int end = position;
if (start != position)
{
while (end < text.Length && isWordCharacter(text[end]))
{
end++;
}
}
return TextSpan.FromBounds(start, end);
}
public static bool IsStartingNewWord(SourceText text, int characterPosition, Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter)
{
var ch = text[characterPosition];
if (!isWordStartCharacter(ch))
{
return false;
}
// Only want to trigger if we're the first character in an identifier. If there's a
// character before or after us, then we don't want to trigger.
if (characterPosition > 0 &&
isWordCharacter(text[characterPosition - 1]))
{
return false;
}
if (characterPosition < text.Length - 1 &&
isWordCharacter(text[characterPosition + 1]))
{
return false;
}
return true;
}
public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory(
Workspace workspace,
SemanticModel semanticModel,
int position,
ISymbol symbol)
{
return CreateDescriptionFactory(workspace, semanticModel, position, new[] { symbol });
}
public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory(
Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols)
{
return c => CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms: null, cancellationToken: c);
}
public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory(
Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols, SupportedPlatformData supportedPlatforms)
{
return c => CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms: supportedPlatforms, cancellationToken: c);
}
public static async Task<CompletionDescription> CreateDescriptionAsync(
Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols, SupportedPlatformData supportedPlatforms, CancellationToken cancellationToken)
{
var symbolDisplayService = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<ISymbolDisplayService>();
var formatter = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<IDocumentationCommentFormattingService>();
// TODO(cyrusn): Figure out a way to cancel this.
var symbol = symbols[0];
var sections = await symbolDisplayService.ToDescriptionGroupsAsync(workspace, semanticModel, position, ImmutableArray.Create(symbol), cancellationToken).ConfigureAwait(false);
if (!sections.ContainsKey(SymbolDescriptionGroups.MainDescription))
{
return CompletionDescription.Empty;
}
var textContentBuilder = new List<SymbolDisplayPart>();
textContentBuilder.AddRange(sections[SymbolDescriptionGroups.MainDescription]);
switch (symbol.Kind)
{
case SymbolKind.Method:
case SymbolKind.NamedType:
if (symbols.Count > 1)
{
var overloadCount = symbols.Count - 1;
var isGeneric = symbol.GetArity() > 0;
textContentBuilder.AddSpace();
textContentBuilder.AddPunctuation("(");
textContentBuilder.AddPunctuation("+");
textContentBuilder.AddText(NonBreakingSpaceString + overloadCount.ToString());
AddOverloadPart(textContentBuilder, overloadCount, isGeneric);
textContentBuilder.AddPunctuation(")");
}
break;
}
AddDocumentationPart(textContentBuilder, symbol, semanticModel, position, formatter, cancellationToken);
if (sections.ContainsKey(SymbolDescriptionGroups.AwaitableUsageText))
{
textContentBuilder.AddRange(sections[SymbolDescriptionGroups.AwaitableUsageText]);
}
if (sections.ContainsKey(SymbolDescriptionGroups.AnonymousTypes))
{
var parts = sections[SymbolDescriptionGroups.AnonymousTypes];
if (!parts.IsDefaultOrEmpty)
{
textContentBuilder.AddLineBreak();
textContentBuilder.AddLineBreak();
textContentBuilder.AddRange(parts);
}
}
if (supportedPlatforms != null)
{
textContentBuilder.AddLineBreak();
textContentBuilder.AddRange(supportedPlatforms.ToDisplayParts());
}
return CompletionDescription.Create(textContentBuilder.ToTaggedText());
}
private static void AddOverloadPart(List<SymbolDisplayPart> textContentBuilder, int overloadCount, bool isGeneric)
{
var text = isGeneric
? overloadCount == 1
? FeaturesResources.generic_overload
: FeaturesResources.generic_overloads
: overloadCount == 1
? FeaturesResources.overload
: FeaturesResources.overloads_;
textContentBuilder.AddText(NonBreakingSpaceString + text);
}
private static void AddDocumentationPart(List<SymbolDisplayPart> textContentBuilder, ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken)
{
var documentation = symbol.GetDocumentationParts(semanticModel, position, formatter, cancellationToken);
if (documentation.Any())
{
textContentBuilder.AddLineBreak();
textContentBuilder.AddRange(documentation);
}
}
internal static bool IsTextualTriggerString(SourceText text, int characterPosition, string value)
{
// The character position starts at the last character of 'value'. So if 'value' has
// length 1, then we don't want to move, if it has length 2 we want to move back one,
// etc.
characterPosition = characterPosition - value.Length + 1;
for (int i = 0; i < value.Length; i++, characterPosition++)
{
if (characterPosition < 0 || characterPosition >= text.Length)
{
return false;
}
if (text[characterPosition] != value[i])
{
return false;
}
}
return true;
}
public static bool TryRemoveAttributeSuffix(ISymbol symbol, SyntaxContext context, out string name)
{
var isAttributeNameContext = context.IsAttributeNameContext;
var syntaxFacts = context.GetLanguageService<ISyntaxFactsService>();
if (!isAttributeNameContext)
{
name = null;
return false;
}
// Do the symbol textual check first. Then the more expensive symbolic check.
if (!symbol.Name.TryGetWithoutAttributeSuffix(syntaxFacts.IsCaseSensitive, out name) ||
!symbol.IsAttribute())
{
return false;
}
return true;
}
}
}
| |
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = Lucene.Net.Util.BytesRef;
using Codec = Lucene.Net.Codecs.Codec;
using Constants = Lucene.Net.Util.Constants;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using InfoStream = Lucene.Net.Util.InfoStream;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestSegmentMerger : LuceneTestCase
{
//The variables for the new merged segment
private Directory mergedDir;
private string mergedSegment = "test";
//First segment to be merged
private Directory merge1Dir;
private Document doc1;
private SegmentReader reader1;
//Second Segment to be merged
private Directory merge2Dir;
private Document doc2;
private SegmentReader reader2;
[SetUp]
public override void SetUp()
{
base.SetUp();
this.doc1 = new Document();
this.doc2 = new Document();
mergedDir = NewDirectory();
merge1Dir = NewDirectory();
merge2Dir = NewDirectory();
DocHelper.SetupDoc(doc1);
SegmentCommitInfo info1 = DocHelper.WriteDoc(Random, merge1Dir, doc1);
DocHelper.SetupDoc(doc2);
SegmentCommitInfo info2 = DocHelper.WriteDoc(Random, merge2Dir, doc2);
reader1 = new SegmentReader(info1, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, NewIOContext(Random));
reader2 = new SegmentReader(info2, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, NewIOContext(Random));
}
[TearDown]
public override void TearDown()
{
reader1.Dispose();
reader2.Dispose();
mergedDir.Dispose();
merge1Dir.Dispose();
merge2Dir.Dispose();
base.TearDown();
}
[Test]
public virtual void Test()
{
Assert.IsTrue(mergedDir != null);
Assert.IsTrue(merge1Dir != null);
Assert.IsTrue(merge2Dir != null);
Assert.IsTrue(reader1 != null);
Assert.IsTrue(reader2 != null);
}
[Test]
public virtual void TestMerge()
{
Codec codec = Codec.Default;
SegmentInfo si = new SegmentInfo(mergedDir, Constants.LUCENE_MAIN_VERSION, mergedSegment, -1, false, codec, null);
SegmentMerger merger = new SegmentMerger(new List<AtomicReader> { reader1, reader2 }, si, (InfoStream)InfoStream.Default, mergedDir, IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL, CheckAbort.NONE, new FieldInfos.FieldNumbers(), NewIOContext(Random), true);
MergeState mergeState = merger.Merge();
int docsMerged = mergeState.SegmentInfo.DocCount;
Assert.IsTrue(docsMerged == 2);
//Should be able to open a new SegmentReader against the new directory
SegmentReader mergedReader = new SegmentReader(new SegmentCommitInfo(new SegmentInfo(mergedDir, Constants.LUCENE_MAIN_VERSION, mergedSegment, docsMerged, false, codec, null), 0, -1L, -1L), DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, NewIOContext(Random));
Assert.IsTrue(mergedReader != null);
Assert.IsTrue(mergedReader.NumDocs == 2);
Document newDoc1 = mergedReader.Document(0);
Assert.IsTrue(newDoc1 != null);
//There are 2 unstored fields on the document
Assert.IsTrue(DocHelper.NumFields(newDoc1) == DocHelper.NumFields(doc1) - DocHelper.Unstored.Count);
Document newDoc2 = mergedReader.Document(1);
Assert.IsTrue(newDoc2 != null);
Assert.IsTrue(DocHelper.NumFields(newDoc2) == DocHelper.NumFields(doc2) - DocHelper.Unstored.Count);
DocsEnum termDocs = TestUtil.Docs(Random, mergedReader, DocHelper.TEXT_FIELD_2_KEY, new BytesRef("field"), MultiFields.GetLiveDocs(mergedReader), null, 0);
Assert.IsTrue(termDocs != null);
Assert.IsTrue(termDocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
int tvCount = 0;
foreach (FieldInfo fieldInfo in mergedReader.FieldInfos)
{
if (fieldInfo.HasVectors)
{
tvCount++;
}
}
//System.out.println("stored size: " + stored.Size());
Assert.AreEqual(3, tvCount, "We do not have 3 fields that were indexed with term vector");
Terms vector = mergedReader.GetTermVectors(0).GetTerms(DocHelper.TEXT_FIELD_2_KEY);
Assert.IsNotNull(vector);
Assert.AreEqual(3, vector.Count);
TermsEnum termsEnum = vector.GetEnumerator();
int i = 0;
while (termsEnum.MoveNext())
{
string term = termsEnum.Term.Utf8ToString();
int freq = (int)termsEnum.TotalTermFreq;
//System.out.println("Term: " + term + " Freq: " + freq);
Assert.IsTrue(DocHelper.FIELD_2_TEXT.IndexOf(term, StringComparison.Ordinal) != -1);
Assert.IsTrue(DocHelper.FIELD_2_FREQS[i] == freq);
i++;
}
TestSegmentReader.CheckNorms(mergedReader);
mergedReader.Dispose();
}
private static bool Equals(MergeState.DocMap map1, MergeState.DocMap map2)
{
if (map1.MaxDoc != map2.MaxDoc)
{
return false;
}
for (int i = 0; i < map1.MaxDoc; ++i)
{
if (map1.Get(i) != map2.Get(i))
{
return false;
}
}
return true;
}
[Test]
public virtual void TestBuildDocMap()
{
int maxDoc = TestUtil.NextInt32(Random, 1, 128);
int numDocs = TestUtil.NextInt32(Random, 0, maxDoc);
int numDeletedDocs = maxDoc - numDocs;
FixedBitSet liveDocs = new FixedBitSet(maxDoc);
for (int i = 0; i < numDocs; ++i)
{
while (true)
{
int docID = Random.Next(maxDoc);
if (!liveDocs.Get(docID))
{
liveDocs.Set(docID);
break;
}
}
}
MergeState.DocMap docMap = MergeState.DocMap.Build(maxDoc, liveDocs);
Assert.AreEqual(maxDoc, docMap.MaxDoc);
Assert.AreEqual(numDocs, docMap.NumDocs);
Assert.AreEqual(numDeletedDocs, docMap.NumDeletedDocs);
// assert the mapping is compact
for (int i = 0, del = 0; i < maxDoc; ++i)
{
if (!liveDocs.Get(i))
{
Assert.AreEqual(-1, docMap.Get(i));
++del;
}
else
{
Assert.AreEqual(i - del, docMap.Get(i));
}
}
}
}
}
| |
using Northwind.Common.DataModel;
using NUnit.Framework;
using System;
namespace NServiceKit.Text.Tests
{
/// <summary>A CSV stream tests.</summary>
[TestFixture]
public class CsvStreamTests
{
/// <summary>Logs.</summary>
/// <param name="fmt"> Describes the format to use.</param>
/// <param name="args">A variable-length parameters list containing arguments.</param>
protected void Log(string fmt, params object[] args)
{
// Console.WriteLine("{0}", String.Format(fmt, args).Trim());
}
/// <summary>Tear down.</summary>
[TearDown]
public void TearDown()
{
CsvConfig.Reset();
}
/// <summary>Can create CSV from customers.</summary>
[Test]
public void Can_create_csv_from_Customers()
{
NorthwindData.LoadData(false);
var csv = CsvSerializer.SerializeToCsv(NorthwindData.Customers);
Log(csv);
Assert.That(csv, Is.Not.Null);
}
/// <summary>Can create CSV from customers pipe separator.</summary>
[Test]
public void Can_create_csv_from_Customers_pipe_separator()
{
CsvConfig.ItemSeperatorString = "|";
NorthwindData.LoadData(false);
var csv = CsvSerializer.SerializeToCsv(NorthwindData.Customers);
Log(csv);
Assert.That(csv, Is.Not.Null);
}
/// <summary>Can create CSV from customers pipe delimiter.</summary>
[Test]
public void Can_create_csv_from_Customers_pipe_delimiter()
{
CsvConfig.ItemDelimiterString = "|";
NorthwindData.LoadData(false);
var csv = CsvSerializer.SerializeToCsv(NorthwindData.Customers);
Log(csv);
Assert.That(csv, Is.Not.Null);
}
/// <summary>Can create CSV from customers pipe row separator.</summary>
[Test]
public void Can_create_csv_from_Customers_pipe_row_separator()
{
CsvConfig.RowSeparatorString = "|";
NorthwindData.LoadData(false);
var csv = CsvSerializer.SerializeToCsv(NorthwindData.Customers);
Log(csv);
Assert.That(csv, Is.Not.Null);
}
/// <summary>Can create CSV from categories.</summary>
[Test]
public void Can_create_csv_from_Categories()
{
NorthwindData.LoadData(false);
var category = NorthwindFactory.Category(1, "between \"quotes\" here", "with, comma", null);
var categories = new[] { category, category };
var csv = CsvSerializer.SerializeToCsv(categories);
Log(csv);
Assert.That(csv, Is.EqualTo(
"Id,CategoryName,Description,Picture"
+ Environment.NewLine
+ "1,\"between \"\"quotes\"\" here\",\"with, comma\","
+ Environment.NewLine
+ "1,\"between \"\"quotes\"\" here\",\"with, comma\","
+ Environment.NewLine
));
}
/// <summary>Can create CSV from categories pipe separator.</summary>
[Test]
public void Can_create_csv_from_Categories_pipe_separator()
{
CsvConfig.ItemSeperatorString = "|";
NorthwindData.LoadData(false);
var category = NorthwindFactory.Category(1, "between \"quotes\" here", "with, comma", null);
var categories = new[] { category, category };
var csv = CsvSerializer.SerializeToCsv(categories);
Log(csv);
Assert.That(csv, Is.EqualTo(
"Id|CategoryName|Description|Picture"
+ Environment.NewLine
+ "1|\"between \"\"quotes\"\" here\"|with, comma|"
+ Environment.NewLine
+ "1|\"between \"\"quotes\"\" here\"|with, comma|"
+ Environment.NewLine
));
}
/// <summary>Can create CSV from categories pipe delimiter.</summary>
[Test]
public void Can_create_csv_from_Categories_pipe_delimiter()
{
CsvConfig.ItemDelimiterString = "|";
NorthwindData.LoadData(false);
var category = NorthwindFactory.Category(1, "between \"quotes\" here", "with, comma", null);
var categories = new[] { category, category };
var csv = CsvSerializer.SerializeToCsv(categories);
Log(csv);
Assert.That(csv, Is.EqualTo(
"Id,CategoryName,Description,Picture"
+ Environment.NewLine
+ "1,between \"quotes\" here,|with, comma|,"
+ Environment.NewLine
+ "1,between \"quotes\" here,|with, comma|,"
+ Environment.NewLine
));
}
/// <summary>Can create CSV from categories long delimiter.</summary>
[Test]
public void Can_create_csv_from_Categories_long_delimiter()
{
CsvConfig.ItemDelimiterString = "~^~";
NorthwindData.LoadData(false);
var category = NorthwindFactory.Category(1, "between \"quotes\" here", "with, comma", null);
var categories = new[] { category, category };
var csv = CsvSerializer.SerializeToCsv(categories);
Log(csv);
Assert.That(csv, Is.EqualTo(
"Id,CategoryName,Description,Picture"
+ Environment.NewLine
+ "1,between \"quotes\" here,~^~with, comma~^~,"
+ Environment.NewLine
+ "1,between \"quotes\" here,~^~with, comma~^~,"
+ Environment.NewLine
));
}
/// <summary>Can generate CSV with invalid characters.</summary>
[Test]
public void Can_generate_csv_with_invalid_chars()
{
var fields = new[] { "1", "2", "3\"", "4", "5\"five,six\"", "7,7.1", "\"7,7.1\"", "8" };
var csv = CsvSerializer.SerializeToCsv(fields);
Log(csv);
Assert.That(csv, Is.EqualTo(
"1,2,\"3\"\"\",4,\"5\"\"five,six\"\"\",\"7,7.1\",\"\"\"7,7.1\"\"\",8"
+ Environment.NewLine
));
}
/// <summary>Can generate CSV with invalid characters pipe delimiter.</summary>
[Test]
public void Can_generate_csv_with_invalid_chars_pipe_delimiter()
{
CsvConfig.ItemDelimiterString = "|";
var fields = new[] { "1", "2", "3\"", "4", "5\"five,six\"", "7,7.1", "\"7,7.1\"", "8" };
var csv = CsvSerializer.SerializeToCsv(fields);
Log(csv);
Assert.That(csv, Is.EqualTo(
"1,2,3\",4,|5\"five,six\"|,|7,7.1|,|\"7,7.1\"|,8"
+ Environment.NewLine
));
}
/// <summary>Can generate CSV with invalid characters pipe separator.</summary>
[Test]
public void Can_generate_csv_with_invalid_chars_pipe_separator()
{
CsvConfig.ItemSeperatorString = "|";
var fields = new[] { "1", "2", "3\"", "4", "5\"five,six\"", "7,7.1", "\"7,7.1\"", "8" };
var csv = CsvSerializer.SerializeToCsv(fields);
Log(csv);
Assert.That(csv, Is.EqualTo(
"1|2|\"3\"\"\"|4|\"5\"\"five,six\"\"\"|7,7.1|\"\"\"7,7.1\"\"\"|8"
+ Environment.NewLine
));
}
/// <summary>Can convert to CSV field.</summary>
[Test]
public void Can_convert_to_csv_field()
{
Assert.That("1".ToCsvField(), Is.EqualTo("1"));
Assert.That("3\"".ToCsvField(), Is.EqualTo("\"3\"\"\""));
Assert.That("5\"five,six\"".ToCsvField(), Is.EqualTo("\"5\"\"five,six\"\"\""));
Assert.That("7,7.1".ToCsvField(), Is.EqualTo("\"7,7.1\""));
Assert.That("\"7,7.1\"".ToCsvField(), Is.EqualTo("\"\"\"7,7.1\"\"\""));
}
/// <summary>Can convert to CSV field pipe separator.</summary>
[Test]
public void Can_convert_to_csv_field_pipe_separator()
{
CsvConfig.ItemSeperatorString = "|";
Assert.That("1".ToCsvField(), Is.EqualTo("1"));
Assert.That("3\"".ToCsvField(), Is.EqualTo("\"3\"\"\""));
Assert.That("5\"five,six\"".ToCsvField(), Is.EqualTo("\"5\"\"five,six\"\"\""));
Assert.That("7,7.1".ToCsvField(), Is.EqualTo("7,7.1"));
Assert.That("\"7,7.1\"".ToCsvField(), Is.EqualTo("\"\"\"7,7.1\"\"\""));
}
/// <summary>Can convert to CSV field pipe delimiter.</summary>
[Test]
public void Can_convert_to_csv_field_pipe_delimiter()
{
CsvConfig.ItemDelimiterString = "|";
Assert.That("1".ToCsvField(), Is.EqualTo("1"));
Assert.That("3\"".ToCsvField(), Is.EqualTo("3\""));
Assert.That("5\"five,six\"".ToCsvField(), Is.EqualTo("|5\"five,six\"|"));
Assert.That("7,7.1".ToCsvField(), Is.EqualTo("|7,7.1|"));
Assert.That("\"7,7.1\"".ToCsvField(), Is.EqualTo("|\"7,7.1\"|"));
}
/// <summary>Can convert from CSV field.</summary>
[Test]
public void Can_convert_from_csv_field()
{
Assert.That("1".FromCsvField(), Is.EqualTo("1"));
Assert.That("\"3\"\"\"".FromCsvField(), Is.EqualTo("3\""));
Assert.That("\"5\"\"five,six\"\"\"".FromCsvField(), Is.EqualTo("5\"five,six\""));
Assert.That("\"7,7.1\"".FromCsvField(), Is.EqualTo("7,7.1"));
Assert.That("\"\"\"7,7.1\"\"\"".FromCsvField(), Is.EqualTo("\"7,7.1\""));
}
/// <summary>Can convert from CSV field pipe separator.</summary>
[Test]
public void Can_convert_from_csv_field_pipe_separator()
{
CsvConfig.ItemSeperatorString = "|";
Assert.That("1".FromCsvField(), Is.EqualTo("1"));
Assert.That("\"3\"\"\"".FromCsvField(), Is.EqualTo("3\""));
Assert.That("\"5\"\"five,six\"\"\"".FromCsvField(), Is.EqualTo("5\"five,six\""));
Assert.That("\"7,7.1\"".FromCsvField(), Is.EqualTo("7,7.1"));
Assert.That("7,7.1".FromCsvField(), Is.EqualTo("7,7.1"));
Assert.That("\"\"\"7,7.1\"\"\"".FromCsvField(), Is.EqualTo("\"7,7.1\""));
}
/// <summary>Can convert from CSV field pipe delimiter.</summary>
[Test]
public void Can_convert_from_csv_field_pipe_delimiter()
{
CsvConfig.ItemDelimiterString = "|";
Assert.That("1".FromCsvField(), Is.EqualTo("1"));
Assert.That("3\"".FromCsvField(), Is.EqualTo("3\""));
Assert.That("|5\"five,six\"|".FromCsvField(), Is.EqualTo("5\"five,six\""));
Assert.That("|7,7.1|".FromCsvField(), Is.EqualTo("7,7.1"));
Assert.That("|\"7,7.1\"|".FromCsvField(), Is.EqualTo("\"7,7.1\""));
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using AllReady.Models;
namespace AllReady.Migrations
{
[DbContext(typeof(AllReadyContext))]
[Migration("20151123015003_TaskDateTimeOffset")]
partial class TaskDateTimeOffset
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("AllReady.Models.Activity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CampaignId");
b.Property<string>("Description");
b.Property<DateTimeOffset>("EndDateTime");
b.Property<string>("ImageUrl");
b.Property<int?>("LocationId");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("NumberOfVolunteersRequired");
b.Property<string>("OrganizerId");
b.Property<DateTimeOffset>("StartDateTime");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ActivitySignup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("ActivityId");
b.Property<string>("AdditionalInfo");
b.Property<DateTime?>("CheckinDateTime");
b.Property<string>("PreferredEmail");
b.Property<string>("PreferredPhoneNumber");
b.Property<DateTime>("SignupDateTime");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ActivitySkill", b =>
{
b.Property<int>("ActivityId");
b.Property<int>("SkillId");
b.HasKey("ActivityId", "SkillId");
});
modelBuilder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("ActivityId");
b.Property<string>("Description");
b.Property<DateTimeOffset?>("EndDateTime");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("NumberOfVolunteersRequired");
b.Property<DateTimeOffset?>("StartDateTime");
b.Property<int?>("TenantId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("Name");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<int?>("TenantId");
b.Property<string>("TimeZoneId")
.IsRequired();
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("AllReady.Models.Campaign", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CampaignImpactId");
b.Property<string>("Description");
b.Property<DateTimeOffset>("EndDateTime");
b.Property<string>("FullDescription");
b.Property<string>("ImageUrl");
b.Property<int?>("LocationId");
b.Property<int>("ManagingTenantId");
b.Property<string>("Name")
.IsRequired();
b.Property<string>("OrganizerId");
b.Property<DateTimeOffset>("StartDateTime");
b.Property<string>("TimeZoneId")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
{
b.Property<int>("CampaignId");
b.Property<int>("ContactId");
b.Property<int>("ContactType");
b.HasKey("CampaignId", "ContactId", "ContactType");
});
modelBuilder.Entity("AllReady.Models.CampaignImpact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CurrentImpactLevel");
b.Property<bool>("Display");
b.Property<int>("ImpactType");
b.Property<int>("NumericImpactGoal");
b.Property<string>("TextualImpactGoal");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CampaignId");
b.Property<int?>("TenantId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Contact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Email");
b.Property<string>("FirstName");
b.Property<string>("LastName");
b.Property<string>("PhoneNumber");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Location", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Address1");
b.Property<string>("Address2");
b.Property<string>("City");
b.Property<string>("Country");
b.Property<string>("Name");
b.Property<string>("PhoneNumber");
b.Property<string>("PostalCodePostalCode");
b.Property<string>("State");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b =>
{
b.Property<string>("PostalCode");
b.Property<string>("City");
b.Property<string>("State");
b.HasKey("PostalCode");
});
modelBuilder.Entity("AllReady.Models.Resource", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("CategoryTag");
b.Property<string>("Description");
b.Property<string>("MediaUrl");
b.Property<string>("Name");
b.Property<DateTime>("PublishDateBegin");
b.Property<DateTime>("PublishDateEnd");
b.Property<string>("ResourceUrl");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Skill", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<string>("Name")
.IsRequired();
b.Property<int?>("ParentSkillId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TaskSignup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Status");
b.Property<DateTime>("StatusDateTimeUtc");
b.Property<string>("StatusDescription");
b.Property<int?>("TaskId");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TaskSkill", b =>
{
b.Property<int>("TaskId");
b.Property<int>("SkillId");
b.HasKey("TaskId", "SkillId");
});
modelBuilder.Entity("AllReady.Models.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("LocationId");
b.Property<string>("LogoUrl");
b.Property<string>("Name")
.IsRequired();
b.Property<string>("WebUrl");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TenantContact", b =>
{
b.Property<int>("TenantId");
b.Property<int>("ContactId");
b.Property<int>("ContactType");
b.HasKey("TenantId", "ContactId", "ContactType");
});
modelBuilder.Entity("AllReady.Models.UserSkill", b =>
{
b.Property<string>("UserId");
b.Property<int>("SkillId");
b.HasKey("UserId", "SkillId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("AllReady.Models.Activity", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OrganizerId");
});
modelBuilder.Entity("AllReady.Models.ActivitySignup", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("AllReady.Models.ActivitySkill", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
});
modelBuilder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.Tenant")
.WithMany()
.HasForeignKey("TenantId");
});
modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.HasOne("AllReady.Models.Tenant")
.WithMany()
.HasForeignKey("TenantId");
});
modelBuilder.Entity("AllReady.Models.Campaign", b =>
{
b.HasOne("AllReady.Models.CampaignImpact")
.WithMany()
.HasForeignKey("CampaignImpactId");
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("AllReady.Models.Tenant")
.WithMany()
.HasForeignKey("ManagingTenantId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OrganizerId");
});
modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Contact")
.WithMany()
.HasForeignKey("ContactId");
});
modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Tenant")
.WithMany()
.HasForeignKey("TenantId");
});
modelBuilder.Entity("AllReady.Models.Location", b =>
{
b.HasOne("AllReady.Models.PostalCodeGeo")
.WithMany()
.HasForeignKey("PostalCodePostalCode");
});
modelBuilder.Entity("AllReady.Models.Skill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("ParentSkillId");
});
modelBuilder.Entity("AllReady.Models.TaskSignup", b =>
{
b.HasOne("AllReady.Models.AllReadyTask")
.WithMany()
.HasForeignKey("TaskId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("AllReady.Models.TaskSkill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
b.HasOne("AllReady.Models.AllReadyTask")
.WithMany()
.HasForeignKey("TaskId");
});
modelBuilder.Entity("AllReady.Models.Tenant", b =>
{
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
});
modelBuilder.Entity("AllReady.Models.TenantContact", b =>
{
b.HasOne("AllReady.Models.Contact")
.WithMany()
.HasForeignKey("ContactId");
b.HasOne("AllReady.Models.Tenant")
.WithMany()
.HasForeignKey("TenantId");
});
modelBuilder.Entity("AllReady.Models.UserSkill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
using System;
using UnityEngine;
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
public class PostEffectsBase : MonoBehaviour {
protected bool supportHDRTextures = true;
protected bool supportDX11 = false;
protected bool isSupported = true;
protected Material CheckShaderAndCreateMaterial ( Shader s, Material m2Create) {
if (!s) {
Debug.Log("Missing shader in " + ToString ());
enabled = false;
return null;
}
if (s.isSupported && m2Create && m2Create.shader == s)
return m2Create;
if (!s.isSupported) {
NotSupported ();
Debug.Log("The shader " + s.ToString() + " on effect "+ToString()+" is not supported on this platform!");
return null;
}
else {
m2Create = new Material (s);
m2Create.hideFlags = HideFlags.DontSave;
if (m2Create)
return m2Create;
else return null;
}
}
protected Material CreateMaterial ( Shader s, Material m2Create) {
if (!s) {
Debug.Log ("Missing shader in " + ToString ());
return null;
}
if (m2Create && (m2Create.shader == s) && (s.isSupported))
return m2Create;
if (!s.isSupported) {
return null;
}
else {
m2Create = new Material (s);
m2Create.hideFlags = HideFlags.DontSave;
if (m2Create)
return m2Create;
else return null;
}
}
void OnEnable () {
isSupported = true;
}
protected bool CheckSupport () {
return CheckSupport (false);
}
public virtual bool CheckResources () {
Debug.LogWarning ("CheckResources () for " + ToString() + " should be overwritten.");
return isSupported;
}
protected void Start () {
CheckResources ();
}
protected bool CheckSupport ( bool needDepth) {
isSupported = true;
supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf);
supportDX11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders;
if (!SystemInfo.supportsImageEffects || !SystemInfo.supportsRenderTextures) {
NotSupported ();
return false;
}
if (needDepth && !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth)) {
NotSupported ();
return false;
}
if (needDepth)
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
return true;
}
protected bool CheckSupport ( bool needDepth, bool needHdr) {
if (!CheckSupport(needDepth))
return false;
if (needHdr && !supportHDRTextures) {
NotSupported ();
return false;
}
return true;
}
public bool Dx11Support () {
return supportDX11;
}
protected void ReportAutoDisable () {
Debug.LogWarning ("The image effect " + ToString() + " has been disabled as it's not supported on the current platform.");
}
// deprecated but needed for old effects to survive upgrading
bool CheckShader ( Shader s) {
Debug.Log("The shader " + s.ToString () + " on effect "+ ToString () + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package.");
if (!s.isSupported) {
NotSupported ();
return false;
}
else {
return false;
}
}
protected void NotSupported () {
enabled = false;
isSupported = false;
return;
}
protected void DrawBorder ( RenderTexture dest, Material material ) {
float x1;
float x2;
float y1;
float y2;
RenderTexture.active = dest;
bool invertY = true; // source.texelSize.y < 0.0ff;
// Set up the simple Matrix
GL.PushMatrix();
GL.LoadOrtho();
for (int i = 0; i < material.passCount; i++)
{
material.SetPass(i);
float y1_; float y2_;
if (invertY)
{
y1_ = 1.0f; y2_ = 0.0f;
}
else
{
y1_ = 0.0f; y2_ = 1.0f;
}
// left
x1 = 0.0f;
x2 = 0.0f + 1.0f/(dest.width*1.0f);
y1 = 0.0f;
y2 = 1.0f;
GL.Begin(GL.QUADS);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// right
x1 = 1.0f - 1.0f/(dest.width*1.0f);
x2 = 1.0f;
y1 = 0.0f;
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// top
x1 = 0.0f;
x2 = 1.0f;
y1 = 0.0f;
y2 = 0.0f + 1.0f/(dest.height*1.0f);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// bottom
x1 = 0.0f;
x2 = 1.0f;
y1 = 1.0f - 1.0f/(dest.height*1.0f);
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
GL.End();
}
GL.PopMatrix();
}
}
| |
// Prexonite
//
// Copyright (c) 2014, Christian Klauser
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// The names of the contributors may be used to endorse or
// promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Prexonite.Commands.List;
using Prexonite.Compiler.Cil;
using Prexonite.Concurrency;
using Prexonite.Types;
namespace Prexonite.Commands.Concurrency
{
public class AsyncSeq : CoroutineCommand, ICilCompilerAware
{
#region Singleton pattern
private AsyncSeq()
{
}
private static readonly AsyncSeq _instance = new AsyncSeq();
public static AsyncSeq Instance
{
get { return _instance; }
}
#endregion
#region Overrides of PCommand
[Obsolete]
public override bool IsPure
{
get { return false; }
}
#endregion
#region Overrides of CoroutineCommand
protected override IEnumerable<PValue> CoroutineRun(ContextCarrier sctxCarrier,
PValue[] args)
{
return CoroutineRunStatically(sctxCarrier, args);
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly",
MessageId = "Coroutine")]
protected static IEnumerable<PValue> CoroutineRunStatically(ContextCarrier sctxCarrier,
PValue[] args)
{
if (sctxCarrier == null)
throw new ArgumentNullException("sctxCarrier");
if (args == null)
throw new ArgumentNullException("args");
if (args.Length < 1)
throw new PrexoniteException(
"async_seq requires one parameter: The sequence to be computed.");
return new ChannelEnumerable(sctxCarrier, args[0]);
}
//Contains all the logic for spawing the background worker
private class ChannelEnumerable : IEnumerable<PValue>
{
private readonly ContextCarrier _sctxCarrier;
private readonly PValue _arg;
public ChannelEnumerable(ContextCarrier sctxCarrier, PValue arg)
{
_sctxCarrier = sctxCarrier;
_arg = arg;
}
#region Implementation of IEnumerable
public IEnumerator<PValue> GetEnumerator()
{
var peek = new Channel();
var data = new Channel();
var rset = new Channel();
var disp = new Channel();
#region Producer
Func<PValue> producer =
() =>
{
using (
var e =
Map._ToEnumerable(_sctxCarrier.StackContext, _arg).GetEnumerator
())
{
var doCont = true;
var doDisp = false;
cont:
if (e.MoveNext())
{
peek.Send(true);
data.Send(e.Current);
}
else
{
peek.Send(false);
//doCont = false;
goto shutDown;
}
wait:
Select.RunStatically(
_sctxCarrier.StackContext, new[]
{
new KeyValuePair<Channel, PValue>
(
rset, pfunc(
(s, a) =>
{
doCont = true;
try
{
e.Reset();
}
catch (Exception exc)
{
rset.Send(
PType.Object.CreatePValue(exc));
}
rset.Send(PType.Null);
return PType.Null;
})),
new KeyValuePair<Channel, PValue>
(
disp, pfunc(
(s, a) =>
{
doCont = false;
doDisp = true;
return PType.Null;
})),
new KeyValuePair<Channel, PValue>
(null, PType.Null),
}, false);
//We loop until the dispose command is explicitly given.
// -> This way, a reset command can be issued after
// the complete enumeration has been computed
// without the enumerator being disposed of prematurely
if (doCont)
goto cont;
else if (! doDisp)
goto wait;
} //end using (disposes enumerator)
//Ignored (part of CallAsync interface)
shutDown:
return PType.Null;
};
#endregion
return new ChannelEnumerator(peek, data, rset, disp, producer, _sctxCarrier);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
//The channel enumerator is a proxy that translates method calls into messages
// to our producer
private class ChannelEnumerator : IEnumerator<PValue>
{
public ChannelEnumerator(Channel peek,
Channel data,
Channel rset,
Channel disp,
Func<PValue> produce,
ContextCarrier sctxCarrier)
{
_peek = peek;
_sctxCarrier = sctxCarrier;
_produce = produce;
_data = data;
_rset = rset;
_disp = disp;
//The producer runs on a separate thread and communicates
// with this thread via 4 channels, one for each method
}
private readonly Channel _peek;
private readonly Channel _data;
private readonly Channel _rset;
private readonly Channel _disp;
private readonly Func<PValue> _produce;
private readonly ContextCarrier _sctxCarrier;
private PValue _current;
#region Implementation of IDisposable
public void Dispose()
{
_disp.Send(PType.Null);
}
#endregion
#region Implementation of IEnumerator
public bool MoveNext()
{
if (_current == null)
{
//The producer runs on a separate thread and communicates
// with this thread via 4 channels, one for each method
CallAsync.RunAsync(_sctxCarrier.StackContext, _produce);
_current = PType.Null;
}
if ((bool) _peek.Receive().Value)
{
_current = _data.Receive();
return true;
}
else
{
return false;
}
}
public void Reset()
{
_rset.Send(PType.Null);
var p = _rset.Receive();
if (!p.IsNull)
{
var exc = p.Value as Exception;
if (exc != null)
throw exc;
else
throw new PrexoniteException("Cannot reset async enumerator: " + p.Value);
}
}
public PValue Current
{
get { return _current; }
}
object IEnumerator.Current
{
get { return Current; }
}
#endregion
}
//Makes working with select from managed code easier
private class PFunc : IIndirectCall
{
private readonly Func<StackContext, PValue[], PValue> _f;
public PFunc(Func<StackContext, PValue[], PValue> f)
{
_f = f;
}
#region Implementation of IIndirectCall
public PValue IndirectCall(StackContext sctx, PValue[] args)
{
return _f(sctx, args);
}
#endregion
public static implicit operator PValue(PFunc f)
{
return PType.Object.CreatePValue(f);
}
}
private static PValue pfunc(Func<StackContext, PValue[], PValue> f)
{
return new PFunc(f);
}
public static PValue RunStatically(StackContext sctx, PValue[] args)
{
var carrier = new ContextCarrier();
var corctx = new CoroutineContext(sctx, CoroutineRunStatically(carrier, args));
carrier.StackContext = corctx;
return sctx.CreateNativePValue(new Coroutine(corctx));
}
#endregion
#region Implementation of ICilCompilerAware
CompilationFlags ICilCompilerAware.CheckQualification(Instruction ins)
{
return CompilationFlags.PrefersRunStatically;
}
void ICilCompilerAware.ImplementInCil(CompilerState state, Instruction ins)
{
throw new NotSupportedException();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using Microsoft.PowerShell.CrossCompatibility.Query;
using System.Linq;
using Data = Microsoft.PowerShell.CrossCompatibility.Data;
namespace Microsoft.PowerShell.CrossCompatibility.Collection
{
/// <summary>
/// Object that takes a PowerShell compatibility profile and validates it.
/// </summary>
public abstract class ProfileValidator
{
/// <summary>
/// Check if a PowerShell compatibility profile is valid.
/// </summary>
/// <param name="profileData">The compatibility profile to check.</param>
/// <param name="validationErrors">All errors encountered with the validation. May be null when true is returned.</param>
/// <returns>True if the profile is valid, false otherwise.</returns>
public abstract bool IsProfileValid(Data.CompatibilityProfileData profileData, out IEnumerable<Exception> validationErrors);
/// <summary>
/// Resets the state of the validator so it is ready for another validation.
/// May be implemented as a no-op with stateless validators.
/// </summary>
public abstract void Reset();
}
/// <summary>
/// A simple profile validator that just checks that common keys and values are present.
/// </summary>
internal class QuickCheckValidator : ProfileValidator
{
private static IReadOnlyCollection<string> s_commonParameters = new []
{
"ErrorVariable",
"WarningAction",
"Verbose"
};
private static IReadOnlyCollection<string> s_commonParameterAliases = new []
{
"ev",
"wa",
"vb"
};
private static IReadOnlyDictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> s_modules = new Dictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>>()
{
{
"Microsoft.PowerShell.Core", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "Get-Module", new [] { "Name", "ListAvailable" } },
{ "Start-Job", new [] { "ScriptBlock", "FilePath" } },
{ "Where-Object", new [] { "FilterScript", "Property" } },
}
},
{
"Microsoft.PowerShell.Management", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "Get-Process", new [] { "Name", "Id", "InputObject" } },
{ "Test-Path", new [] { "Path", "LiteralPath" } },
{ "Get-ChildItem", new [] { "Path", "LiteralPath" } },
{ "New-Item", new [] { "Path", "Name", "Value" }},
}
},
{
"Microsoft.PowerShell.Utility", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "New-Object", new [] { "TypeName", "ArgumentList" }},
{ "Write-Host", new [] { "Object", "NoNewline" }},
{ "Out-File", new [] { "FilePath", "Encoding", "Append", "Force" }},
{ "Invoke-Expression", new [] { "Command" }}
}
}
};
private static IReadOnlyDictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> s_ps4Modules = new Dictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>>()
{
{
"PowerShellGet", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "Install-Module", new [] { "Name", "Scope" } }
}
}
};
private static IReadOnlyDictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> s_ps5Modules = new Dictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>>()
{
{
"PSReadLine", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "Set-PSReadLineKeyHandler", new [] { "Chord", "ScriptBlock" } },
{ "Set-PSReadLineOption", new [] { "EditMode", "ContinuationPrompt" }}
}
}
};
private static IReadOnlyDictionary<string, IReadOnlyCollection<string>> s_aliases = new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "Microsoft.PowerShell.Core", new [] { "?", "%", "select", "fl" , "iwr" } },
{ "Microsoft.PowerShell.Management", new [] { "stz", "gtz" } },
};
private static IReadOnlyDictionary<string, IReadOnlyCollection<string>> s_ps5Aliases = new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "Microsoft.PowerShell.Utility", new [] { "fhx" } },
};
private static IReadOnlyDictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> s_types = new Dictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>>()
{
{
"System.Management.Automation", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "System.Management.Automation", new [] { "AliasInfo", "PSCmdlet", "PSModuleInfo", "SwitchParameter", "ProgressRecord" } },
{ "System.Management.Automation.Language", new [] { "Parser", "AstVisitor", "ITypeName", "Token", "Ast" } },
{ "Microsoft.PowerShell", new [] { "ExecutionPolicy" }},
{ "Microsoft.PowerShell.Commands", new [] { "OutHostCommand", "GetCommandCommand", "GetModuleCommand", "InvokeCommandCommand", "ModuleCmdletBase" } }
}
},
{
"Microsoft.PowerShell.Commands.Utility", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "Microsoft.PowerShell.Commands", new [] { "GetDateCommand", "NewObjectCommand", "SelectObjectCommand", "WriteOutputCommand", "GroupInfo", "GetRandomCommand" } }
}
},
{
"Microsoft.PowerShell.Commands.Management", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "Microsoft.PowerShell.Commands", new [] { "GetContentCommand", "CopyItemCommand", "TestPathCommand", "GetProcessCommand", "SetLocationCommand", "WriteContentLocationCommandBase" } }
}
}
};
private static IReadOnlyDictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> s_coreTypes = new Dictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>>()
{
{
"System.Private.CoreLib", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "System", new [] { "Object", "String", "Array", "Type" } },
{ "System.Reflection", new [] { "Assembly", "BindingFlags", "FieldAttributes" } },
{ "System.Collections.Generic", new [] { "Dictionary`2", "IComparer`1", "List`1", "IReadOnlyList`1" } }
}
},
{
"System.Collections", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "System.Collections", new [] { "BitArray" } },
{ "System.Collections.Generic", new [] { "Queue`1", "Stack`1", "HashSet`1" } }
}
}
};
private static IReadOnlyDictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> s_fxTypes = new Dictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>>()
{
{
"mscorlib", new Dictionary<string, IReadOnlyCollection<string>>()
{
{ "System", new [] { "Object", "String", "Array", "Type" } },
{ "System.Reflection", new [] { "Assembly", "BindingFlags", "FieldAttributes" } },
{ "System.Collections.Generic", new [] { "Dictionary`2", "IComparer`1", "List`1", "IReadOnlyList`1" } },
{ "System.Collections", new [] { "BitArray" } }
}
}
};
private static IReadOnlyDictionary<string, string> s_typeAccelerators = new Dictionary<string, string>()
{
{ "type", "System.Type" },
{ "psobject", "System.Management.Automation.PSObject" },
{ "pscustomobject", "System.Management.Automation.PSObject" },
{ "regex", "System.Text.RegularExpressions.Regex" },
{ "xml", "System.Xml.XmlDocument" },
{ "hashtable", "System.Collections.Hashtable" },
};
private ValidationErrorAccumulator _errAcc;
private int _psVersionMajor;
private Data.DotnetRuntime _dotNetEdition;
/// <summary>
/// Create a new quick check validator.
/// </summary>
public QuickCheckValidator()
{
_errAcc = new ValidationErrorAccumulator();
_psVersionMajor = -1;
_dotNetEdition = Data.DotnetRuntime.Other;
}
/// <inheritdoc/>
public override bool IsProfileValid(Data.CompatibilityProfileData profileData, out IEnumerable<Exception> errors)
{
CompatibilityProfileData queryableProfile;
try
{
queryableProfile = new CompatibilityProfileData(profileData);
}
catch (Exception e)
{
errors = new [] { e };
return false;
}
try
{
_psVersionMajor = queryableProfile.Platform.PowerShell.Version.Major;
ValidatePlatformData(queryableProfile.Id, queryableProfile.Platform);
}
catch (Exception e)
{
_errAcc.AddError(e);
}
try
{
ValidateRuntimeData(queryableProfile.Runtime);
}
catch (Exception e)
{
_errAcc.AddError(e);
}
if (_errAcc.HasErrors())
{
errors = _errAcc.GetErrors();
return false;
}
errors = null;
return true;
}
/// <inheritdoc/>
public override void Reset()
{
_errAcc.Clear();
_psVersionMajor = -1;
_dotNetEdition = Data.DotnetRuntime.Other;
}
private void ValidatePlatformData(string platformId, PlatformData platformData)
{
if (string.IsNullOrEmpty(platformId))
{
_errAcc.AddError("Platform ID is null or empty");
}
if (platformData.PowerShell.Version == null)
{
_errAcc.AddError("PowerShell version is null");
}
else if (platformData.PowerShell.Version.Major >= 5
&& string.IsNullOrEmpty(platformData.PowerShell.Edition))
{
_errAcc.AddError("PowerShell edition is null or empty on version 5.1 or above");
}
if (platformData.Dotnet.ClrVersion == null)
{
_errAcc.AddError(".NET CLR version is null");
}
if (string.IsNullOrEmpty(platformData.OperatingSystem.Name))
{
_errAcc.AddError("OS name is null or empty");
}
if (string.IsNullOrEmpty(platformData.OperatingSystem.Version))
{
_errAcc.AddError("OS version is null or empty");
}
}
private void ValidateRuntimeData(RuntimeData runtimeData)
{
try
{
ValidateCommonData(runtimeData.Common);
}
catch (Exception e)
{
_errAcc.AddError(e);
}
try
{
ValidateModules(runtimeData.Modules);
}
catch (Exception e)
{
_errAcc.AddError(e);
}
try
{
ValidateAvailableTypes(runtimeData.Types);
}
catch (Exception e)
{
_errAcc.AddError(e);
}
}
private void ValidateCommonData(CommonPowerShellData commonData)
{
if (commonData == null)
{
_errAcc.AddError("CommonData is null");
return;
}
if (commonData.Parameters == null)
{
_errAcc.AddError("CommonData.Parameters is null");
}
else
{
foreach (string commonParameter in s_commonParameters)
{
if (!commonData.Parameters.TryGetValue(commonParameter, out ParameterData parameter))
{
_errAcc.AddError($"Common parameter {commonParameter} is not present");
}
else if (parameter == null)
{
_errAcc.AddError($"Common parameter {commonParameter} present but null");
}
}
}
if (commonData.ParameterAliases == null)
{
_errAcc.AddError("CommonData.ParameterAliases is null");
}
else
{
foreach (string commonParameterAlias in s_commonParameterAliases)
{
if (!commonData.ParameterAliases.TryGetValue(commonParameterAlias, out ParameterData parameter))
{
_errAcc.AddError($"Common parameter alias {commonParameterAlias} not present");
}
else if (parameter == null)
{
_errAcc.AddError($"Common parameter alias {commonParameterAlias} present but null");
}
}
}
}
private void ValidateModules(IReadOnlyDictionary<string, IReadOnlyDictionary<Version, ModuleData>> modules)
{
if (modules == null)
{
_errAcc.AddError("RuntimeData.Modules is null");
return;
}
foreach (KeyValuePair<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> expectedModule in s_modules)
{
ValidateSingleModule(expectedModule, modules);
}
foreach (KeyValuePair<string, IReadOnlyCollection<string>> expectedModuleAliases in s_aliases)
{
ValidateSingleModuleAliases(expectedModuleAliases, modules);
}
if (_psVersionMajor > 4)
{
foreach (KeyValuePair<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> expectedModule in s_ps4Modules)
{
ValidateSingleModule(expectedModule, modules);
}
}
if (_psVersionMajor > 5)
{
foreach (KeyValuePair<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> expectedModule in s_ps5Modules)
{
ValidateSingleModule(expectedModule, modules);
}
foreach (KeyValuePair<string, IReadOnlyCollection<string>> expectedModuleAliases in s_ps5Aliases)
{
ValidateSingleModuleAliases(expectedModuleAliases, modules);
}
}
}
private void ValidateSingleModule(
KeyValuePair<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> expectedModule,
IReadOnlyDictionary<string, IReadOnlyDictionary<Version, ModuleData>> modules)
{
if (!modules.TryGetValue(expectedModule.Key, out IReadOnlyDictionary<Version, ModuleData> moduleVersions))
{
_errAcc.AddError($"Module {expectedModule.Key} is not present");
return;
}
else if (moduleVersions.Count == 0)
{
_errAcc.AddError($"Module {expectedModule.Key} is present by name but has no data entries");
return;
}
ModuleData module = moduleVersions.OrderByDescending(moduleVersion => moduleVersion.Key).First().Value;
foreach (KeyValuePair<string, IReadOnlyCollection<string>> expectedCmdlet in expectedModule.Value)
{
if (!module.Cmdlets.TryGetValue(expectedCmdlet.Key, out CmdletData cmdlet))
{
_errAcc.AddError($"Expected cmdlet {expectedCmdlet.Key} not found in module {expectedModule.Key}");
continue;
}
foreach (string expectedParameter in expectedCmdlet.Value)
{
if (!cmdlet.Parameters.ContainsKey(expectedParameter))
{
_errAcc.AddError($"Expected parameter {expectedParameter} on cmdlet {expectedCmdlet.Key} in module {expectedModule.Key} was not found");
}
}
}
}
private void ValidateSingleModuleAliases(
KeyValuePair<string, IReadOnlyCollection<string>> expectedAliases,
IReadOnlyDictionary<string, IReadOnlyDictionary<Version, ModuleData>> modules)
{
ModuleData module;
try
{
module = modules[expectedAliases.Key].OrderByDescending(moduleVersion => moduleVersion.Key).First().Value;
}
catch (InvalidOperationException)
{
_errAcc.AddError($"Module {expectedAliases.Key} not found while checking aliases");
return;
}
foreach (string expectedAlias in expectedAliases.Value)
{
if (!module.Aliases.ContainsKey(expectedAlias))
{
_errAcc.AddError($"Expected alias {expectedAlias} was not found in module {expectedAliases.Key}");
}
}
}
private void ValidateAvailableTypes(AvailableTypeData types)
{
try
{
ValidateTypeAccelerators(types.TypeAccelerators);
}
catch (Exception e)
{
_errAcc.AddError(e);
}
try
{
ValidateAssemblies(types.Assemblies, s_types);
switch (_dotNetEdition)
{
case Data.DotnetRuntime.Core:
ValidateAssemblies(types.Assemblies, s_coreTypes);
break;
case Data.DotnetRuntime.Framework:
ValidateAssemblies(types.Assemblies, s_fxTypes);
break;
default:
_errAcc.AddError($"Dotnet edition did not resolve properly");
break;
}
}
catch (Exception e)
{
_errAcc.AddError(e);
}
}
private void ValidateTypeAccelerators(IReadOnlyDictionary<string, TypeAcceleratorData> typeAccelerators)
{
foreach (KeyValuePair<string, string> expectedTypeAccelerator in s_typeAccelerators)
{
if (!typeAccelerators.TryGetValue(expectedTypeAccelerator.Key, out TypeAcceleratorData typeAccelerator))
{
_errAcc.AddError($"Expected type accelerator {expectedTypeAccelerator.Key} not found");
continue;
}
if (typeAccelerator == null)
{
_errAcc.AddError($"Expected type accelerator {expectedTypeAccelerator.Key} found but null");
continue;
}
if (!typeAccelerator.Type.Equals(expectedTypeAccelerator.Value))
{
_errAcc.AddError($"Type accelerator {expectedTypeAccelerator.Key} was expected to point to type {expectedTypeAccelerator.Value}, but instead points to {typeAccelerator.Type}");
}
}
}
private void ValidateAssemblies(
IReadOnlyDictionary<string, AssemblyData> assemblies,
IReadOnlyDictionary<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> expectedAssemblies)
{
foreach (KeyValuePair<string, IReadOnlyDictionary<string, IReadOnlyCollection<string>>> expectedAssembly in expectedAssemblies)
{
if (!assemblies.TryGetValue(expectedAssembly.Key, out AssemblyData assembly))
{
_errAcc.AddError($"Expected assembly {expectedAssembly.Key} not found");
continue;
}
if (assembly == null)
{
_errAcc.AddError($"Expected assembly {expectedAssembly.Key} was found but null");
continue;
}
foreach (KeyValuePair<string, IReadOnlyCollection<string>> expectedNamespace in expectedAssembly.Value)
{
if (!assembly.Types.TryGetValue(expectedNamespace.Key, out IReadOnlyDictionary<string, TypeData> namespaceTypes))
{
_errAcc.AddError($"Assembly {expectedAssembly.Key} does not contain expected namespace {expectedNamespace.Key}");
continue;
}
if (namespaceTypes == null)
{
_errAcc.AddError($"Assembly {expectedAssembly.Key} contains namespace {expectedNamespace.Key} but it is null");
continue;
}
foreach (string expectedType in expectedNamespace.Value)
{
if (!namespaceTypes.TryGetValue(expectedType, out TypeData typeData))
{
_errAcc.AddError($"Expected type {expectedType} was not found in namespace {expectedNamespace.Key} in assembly {expectedAssembly.Key}");
continue;
}
if (typeData == null)
{
_errAcc.AddError($"Expected type {expectedType} was found but null in namespace {expectedNamespace.Key} in assemblye {expectedAssembly.Key}");
}
}
}
}
}
/// <summary>
/// Class to accumuate validator errors.
/// </summary>
private class ValidationErrorAccumulator
{
private List<Exception> _errors;
public ValidationErrorAccumulator()
{
_errors = new List<Exception>();
}
public void AddError(string message)
{
_errors.Add(new Exception(message));
}
public void AddError(Exception exception)
{
_errors.Add(exception);
}
public IEnumerable<Exception> GetErrors()
{
return _errors;
}
public bool HasErrors()
{
return _errors.Count > 0;
}
public void Clear()
{
_errors.Clear();
}
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace MLifter.AudioTools
{
public delegate void EmtyDelegate();
public delegate void EventDelegate(EventArgs e);
public delegate void ColorDelegate(Color color);
/// <summary>
/// The possible functions of the control / class.
/// </summary>
public enum Function
{
/// <summary>
/// If the control has no function or isn't doing anything.
/// </summary>
Nothing,
/// <summary>
/// If the control is recording or the button is to start the recording.
/// </summary>
Record,
/// <summary>
/// If the control is playing or the button is to start playing.
/// </summary>
Play,
/// <summary>
/// If the button is to stop recording.
/// </summary>
StopRecording,
/// <summary>
/// If the button is to stop playing.
/// </summary>
StopPlaying,
/// <summary>
/// If the button is to go to the next card.
/// </summary>
Forward,
/// <summary>
/// If the button is to go to the previous card.
/// </summary>
Backward
}
/// <summary>
/// The different available font sizes.
/// </summary>
public enum FontSizes
{
Small,
Medium,
Large,
Automatic
}
/// <summary>
/// The different types of media items.
/// </summary>
public enum MediaItemType
{
Question,
QuestionExample,
Answer,
AnswerExample
}
/// <summary>
/// The last excecuted command.
/// </summary>
public enum LastCommand
{
Next,
Back
}
/// <summary>
/// Class which provides some heling methods.
/// </summary>
/// <remarks>Documented by Dev05, 2007-08-08</remarks>
public static class Tools
{
/// <summary>
/// Gets the valid filepath.
/// </summary>
/// <param name="OldFilepath">The old filepath.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2007-08-08</remarks>
public static string GetValidFilename(string OldFilename)
{
string newFilename = System.Text.RegularExpressions.Regex.Replace(Path.GetFileNameWithoutExtension(OldFilename), @"[^\w-\\ ]", "") + Path.GetExtension(OldFilename);
return newFilename;
}
}
/// <summary>
/// General constants.
/// </summary>
/// <remarks>Documented by Dev05, 2007-08-03</remarks>
public class CONSTANTS
{
public static readonly string SETTINGS_FILENAME = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
MLifter.Recorder.Properties.Settings.Default.SettingsPath, "settings.xml");
public const int START_RECORDING_DELAY = 250;
public const int STOP_RECORDING_DELAY = 200;
public const bool DELAYS_ACTIVE = true;
public const bool ALLOW_MULTIPLE_ASSIGNMENT = false;
public const bool PRESENTER_ACTIVATED = true;
}
/// <summary>
/// The standard appearance of the programm.
/// </summary>
public class STANDARD_APPEARANCE
{
public const bool ADVANCEDVIEW = true;
public const bool KEYBOARDLAYOUT = false;
public const bool LOCK_FUNCTIONS_IN_SIMPLE_VIEW = true;
public const int FONT_SIZE_SMALL = 24;
public const int FONT_SIZE_MEDIUM = 36;
public const int FONT_SIZE_LARGE = 56;
public const int FONT_SIZE_AUTOMATIC_LOWER_LIMIT = 16;
public const int FONT_SIZE_AUTOMATIC_UPPER_LIMIT = 72;
public static readonly Color COLOR_RECORD = Color.Red;
public static readonly Color COLOR_PLAY = Color.Green;
public static readonly Color COLOR_STOP = Color.Blue;
public static readonly Color COLOR_MOVE = Color.Yellow;
public const int COLOR_MOVE_TIME = 50;
public static readonly Color COLOR_CARD_COMPLETE = Color.LightGreen;
public static readonly Color COLOR_CARD_NOTHING = Color.Gainsboro;
public static readonly Color COLOR_CARD_PARTS = Color.BurlyWood;
public static readonly Color COLOR_CARD_NOTSELECTED = Color.DimGray;
public static readonly Color COLOR_CARD_SEPARATOR = Color.Gray;
}
/// <summary>
/// The standard Key-Assignment.
/// </summary>
public class STANDART_KEYS
{
public const Keys SWITCH1 = Keys.NumLock;
public const Keys SWITCH2 = Keys.Back;
public const Keys SWITCH3 = Keys.Tab;
public const Keys PLAY = Keys.Enter;
public const Keys RECORD1 = Keys.NumPad0;
public const Keys RECORD2 = Keys.Space;
public const Keys NEXT = Keys.NumPad3;
public const Keys BACK = Keys.Decimal;
public const Keys PRESENTER_RECORD1 = Keys.F5;
public const Keys PRESENTER_RECORD2 = Keys.Escape;
public const Keys PRESENTER_NEXT = Keys.PageDown;
public const Keys PRESENTER_BACK = Keys.PageUp;
}
/// <summary>
/// The standard functions of the NumPad-Keys.
/// </summary>
public class STANDART_FUNCTIONS
{
public const bool AUTOPLAY = false;
public const Function KEY_0 = Function.Record;
public const Function KEY_1 = Function.Nothing;
public const Function KEY_2 = Function.Nothing;
public const Function KEY_3 = Function.Forward;
public const Function KEY_4 = Function.Nothing;
public const Function KEY_5 = Function.Nothing;
public const Function KEY_6 = Function.Nothing;
public const Function KEY_7 = Function.Nothing;
public const Function KEY_8 = Function.Nothing;
public const Function KEY_9 = Function.Nothing;
public const Function KEY_COMMA = Function.Backward;
public const Function KEY_ENTER = Function.Play;
public const Function KEY_PLUS = Function.Nothing;
public const Function KEY_MINUS = Function.Nothing;
public const Function KEY_MULTIPLY = Function.Nothing;
public const Function KEY_DIVIDE = Function.Nothing;
public const Function KEY_SPACE = Function.Record;
public const Function KEY_C = Function.Nothing;
public const Function KEY_V = Function.Backward;
public const Function KEY_B = Function.Play;
public const Function KEY_N = Function.Forward;
public const Function KEY_M = Function.Nothing;
}
[Serializable]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
/// <summary>
/// This property is reserved, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"></see> to the class instead.
/// </summary>
/// <returns>
/// An <see cref="T:System.Xml.Schema.XmlSchema"></see> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"></see> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"></see> method.
/// </returns>
/// <remarks>Documented by Dev05, 2007-08-08</remarks>
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"></see> stream from which the object is deserialized.</param>
/// <remarks>Documented by Dev05, 2007-08-08</remarks>
public void ReadXml(XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
{
return;
}
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
//Shorter version, but only for simple types (int, string, enum,...)
//TKey key = (TKey)GetValue(typeof(TKey), reader.ReadElementString("key"));
//TValue value = (TValue)GetValue(typeof(TValue), reader.ReadElementString("value"));
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
/// <summary>
/// Parses the specified string read form the XML and returns the value
/// it represents as the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2007-08-08</remarks>
private object GetValue(Type type, string value)
{
if (type == typeof(string))
{
return value;
}
else if (type == typeof(bool))
{
return Convert.ToBoolean(value);
}
else if (type.IsEnum)
{
return Enum.Parse(type, value, true);
}
else if (type == typeof(DateTime))
{
if (value.Length == 0)
{
return DateTime.MinValue;
}
else
{
return DateTime.Parse(value);
//return Convert.ToDateTime(value);
}
}
else if (type == typeof(TimeSpan))
{
return TimeSpan.Parse(value); //Convert.Tot(value);
}
else if (type == typeof(Int16))
{
return Convert.ToInt16(value);
}
else if (type == typeof(Int32))
{
return Convert.ToInt32(value);
}
else if (type == typeof(Int64))
{
return Convert.ToInt64(value);
}
else if (type == typeof(float))
{
return Convert.ToSingle(value);
}
else if (type == typeof(double))
{
return Convert.ToDouble(value);
}
else if (type == typeof(decimal))
{
return Convert.ToDecimal(value);
}
else if (type == typeof(char))
{
return Convert.ToChar(value);
}
else if (type == typeof(byte))
{
return Convert.ToByte(value);
}
else if (type == typeof(UInt16))
{
return Convert.ToUInt16(value);
}
else if (type == typeof(UInt32))
{
return Convert.ToUInt32(value);
}
else if (type == typeof(UInt64))
{
return Convert.ToUInt64(value);
}
else if (type == typeof(Guid))
{
return new Guid(value);
}
else
{
return null;
}
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"></see> stream to which the object is serialized.</param>
/// <remarks>Documented by Dev05, 2007-08-08</remarks>
public void WriteXml(XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
//Shorter version, but only for simple types (int, string, enum,...)
//writer.WriteElementString("key", key.ToString());
//writer.WriteElementString("value", this[key].ToString());
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.IO;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a JSON object.
/// </summary>
public class JObject : JContainer, IDictionary<string, JToken>, INotifyPropertyChanged
#if !(UNITY_WP8 || UNITY_WP_8_1) && !(UNITY_WINRT && !UNITY_EDITOR)
, ICustomTypeDescriptor
#endif
{
public class JPropertKeyedCollection : KeyedCollection<string, JToken>
{
public JPropertKeyedCollection(IEqualityComparer<string> comparer)
#if !(UNITY_WEBPLAYER || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE))
: base(comparer)
#else
: base(comparer, 0)
#endif
{
}
protected override string GetKeyForItem(JToken item)
{
return ((JProperty)item).Name;
}
protected override void InsertItem(int index, JToken item)
{
if (Dictionary == null)
{
base.InsertItem(index, item);
}
else
{
// need to override so that the dictionary key is always set rather than added
string keyForItem = GetKeyForItem(item);
Dictionary[keyForItem] = item;
#if !UNITY_WEBPLAYER
Items.Insert(index, item);
#else
base.InsertItem(index, item);
#endif
}
}
#if UNITY_WEBPLAYER
public void RemoveItemAt(int index)
{
base.RemoveAt (index);
}
#endif
#if !(UNITY_WEBPLAYER)
public new IDictionary<string, JToken> Dictionary
{
get { return base.Dictionary; }
}
#else
public IDictionary<string, JToken> Dictionary
{
get { return _dictionary; }
}
private readonly Dictionary<string, JToken> _dictionary = new Dictionary<string, JToken>();
#endif
}
private JPropertKeyedCollection _properties = new JPropertKeyedCollection(StringComparer.Ordinal);
/// <summary>
/// Gets the container's children tokens.
/// </summary>
/// <value>The container's children tokens.</value>
protected override IList<JToken> ChildrenTokens
{
get { return _properties; }
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Initializes a new instance of the <see cref="JObject"/> class.
/// </summary>
public JObject()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JObject"/> class from another <see cref="JObject"/> object.
/// </summary>
/// <param name="other">A <see cref="JObject"/> object to copy from.</param>
public JObject(JObject other)
: base(other)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JObject"/> class with the specified content.
/// </summary>
/// <param name="content">The contents of the object.</param>
public JObject(params object[] content)
: this((object)content)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JObject"/> class with the specified content.
/// </summary>
/// <param name="content">The contents of the object.</param>
public JObject(object content)
{
Add(content);
}
internal override bool DeepEquals(JToken node)
{
JObject t = node as JObject;
return (t != null && ContentsEqual(t));
}
internal override void InsertItem(int index, JToken item)
{
// don't add comments to JObject, no name to reference comment by
if (item != null && item.Type == JTokenType.Comment)
return;
base.InsertItem(index, item);
}
internal override void ValidateToken(JToken o, JToken existing)
{
ValidationUtils.ArgumentNotNull(o, "o");
if (o.Type != JTokenType.Property)
throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType()));
JProperty newProperty = (JProperty)o;
if (existing != null)
{
JProperty existingProperty = (JProperty)existing;
if (newProperty.Name == existingProperty.Name)
return;
}
if (_properties.Dictionary != null && _properties.Dictionary.TryGetValue(newProperty.Name, out existing))
throw new ArgumentException("Can not add property {0} to {1}. Property with the same name already exists on object.".FormatWith(CultureInfo.InvariantCulture, newProperty.Name, GetType()));
}
internal void InternalPropertyChanged(JProperty childProperty)
{
OnPropertyChanged(childProperty.Name);
}
internal void InternalPropertyChanging(JProperty childProperty)
{
}
internal override JToken CloneToken()
{
return new JObject(this);
}
/// <summary>
/// Gets the node type for this <see cref="JToken"/>.
/// </summary>
/// <value>The type.</value>
public override JTokenType Type
{
get { return JTokenType.Object; }
}
/// <summary>
/// Gets an <see cref="IEnumerable{JProperty}"/> of this object's properties.
/// </summary>
/// <returns>An <see cref="IEnumerable{JProperty}"/> of this object's properties.</returns>
public IEnumerable<JProperty> Properties()
{
return ChildrenTokens.Cast<JProperty>();
}
/// <summary>
/// Gets a <see cref="JProperty"/> the specified name.
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>A <see cref="JProperty"/> with the specified name or null.</returns>
public JProperty Property(string name)
{
if (_properties.Dictionary == null)
return null;
if (name == null)
return null;
JToken property;
_properties.Dictionary.TryGetValue(name, out property);
return (JProperty)property;
}
/// <summary>
/// Gets an <see cref="JEnumerable{JToken}"/> of this object's property values.
/// </summary>
/// <returns>An <see cref="JEnumerable{JToken}"/> of this object's property values.</returns>
public JEnumerable<JToken> PropertyValues()
{
return new JEnumerable<JToken>(Properties().Select(p => p.Value));
}
/// <summary>
/// Gets the <see cref="JToken"/> with the specified key.
/// </summary>
/// <value>The <see cref="JToken"/> with the specified key.</value>
public override JToken this[object key]
{
get
{
ValidationUtils.ArgumentNotNull(key, "o");
string propertyName = key as string;
if (propertyName == null)
throw new ArgumentException("Accessed JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
return this[propertyName];
}
set
{
ValidationUtils.ArgumentNotNull(key, "o");
string propertyName = key as string;
if (propertyName == null)
throw new ArgumentException("Set JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
this[propertyName] = value;
}
}
/// <summary>
/// Gets or sets the <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name.
/// </summary>
/// <value></value>
public JToken this[string propertyName]
{
get
{
ValidationUtils.ArgumentNotNull(propertyName, "propertyName");
JProperty property = Property(propertyName);
return (property != null) ? property.Value : null;
}
set
{
JProperty property = Property(propertyName);
if (property != null)
{
property.Value = value;
}
else
{
Add(new JProperty(propertyName, value));
OnPropertyChanged(propertyName);
}
}
}
/// <summary>
/// Loads an <see cref="JObject"/> from a <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JObject"/>.</param>
/// <returns>A <see cref="JObject"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public static new JObject Load(JsonReader reader)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
if (reader.TokenType == JsonToken.None)
{
if (!reader.Read())
throw new Exception("Error reading JObject from JsonReader.");
}
if (reader.TokenType != JsonToken.StartObject)
{
throw new Exception(
"Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(
CultureInfo.InvariantCulture, reader.TokenType));
}
JObject o = new JObject();
o.SetLineInfo(reader as IJsonLineInfo);
o.ReadTokenFrom(reader);
return o;
}
/// <summary>
/// Load a <see cref="JObject"/> from a string that contains JSON.
/// </summary>
/// <param name="json">A <see cref="String"/> that contains JSON.</param>
/// <returns>A <see cref="JObject"/> populated from the string that contains JSON.</returns>
public static new JObject Parse(string json)
{
JsonReader jsonReader = new JsonTextReader(new StringReader(json));
return Load(jsonReader);
}
/// <summary>
/// Creates a <see cref="JObject"/> from an object.
/// </summary>
/// <param name="o">The object that will be used to create <see cref="JObject"/>.</param>
/// <returns>A <see cref="JObject"/> with the values of the specified object</returns>
public static new JObject FromObject(object o)
{
return FromObject(o, new JsonSerializer());
}
/// <summary>
/// Creates a <see cref="JArray"/> from an object.
/// </summary>
/// <param name="o">The object that will be used to create <see cref="JArray"/>.</param>
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param>
/// <returns>A <see cref="JArray"/> with the values of the specified object</returns>
public static new JObject FromObject(object o, JsonSerializer jsonSerializer)
{
JToken token = FromObjectInternal(o, jsonSerializer);
if (token != null && token.Type != JTokenType.Object)
throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type));
return (JObject)token;
}
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{
writer.WriteStartObject();
foreach (JProperty property in ChildrenTokens)
{
property.WriteTo(writer, converters);
}
writer.WriteEndObject();
}
#region IDictionary<string,JToken> Members
/// <summary>
/// Adds the specified property name.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="value">The value.</param>
public void Add(string propertyName, JToken value)
{
Add(new JProperty(propertyName, value));
}
bool IDictionary<string, JToken>.ContainsKey(string key)
{
if (_properties.Dictionary == null)
return false;
return _properties.Dictionary.ContainsKey(key);
}
ICollection<string> IDictionary<string, JToken>.Keys
{
get { return _properties.Dictionary.Keys; }
}
/// <summary>
/// Removes the property with the specified name.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns>true if item was successfully removed; otherwise, false.</returns>
public bool Remove(string propertyName)
{
JProperty property = Property(propertyName);
if (property == null)
return false;
property.Remove();
#if UNITY_WEBPLAYER
_properties.Dictionary.Remove (propertyName);
#endif
return true;
}
/// <summary>
/// Tries the get value.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="value">The value.</param>
/// <returns>true if a value was successfully retrieved; otherwise, false.</returns>
public bool TryGetValue(string propertyName, out JToken value)
{
JProperty property = Property(propertyName);
if (property == null)
{
value = null;
return false;
}
value = property.Value;
return true;
}
ICollection<JToken> IDictionary<string, JToken>.Values
{
get { return _properties.Dictionary.Values; }
}
#endregion
#region ICollection<KeyValuePair<string,JToken>> Members
void ICollection<KeyValuePair<string, JToken>>.Add(KeyValuePair<string, JToken> item)
{
Add(new JProperty(item.Key, item.Value));
}
void ICollection<KeyValuePair<string, JToken>>.Clear()
{
RemoveAll();
}
bool ICollection<KeyValuePair<string, JToken>>.Contains(KeyValuePair<string, JToken> item)
{
JProperty property = Property(item.Key);
if (property == null)
return false;
return (property.Value == item.Value);
}
void ICollection<KeyValuePair<string, JToken>>.CopyTo(KeyValuePair<string, JToken>[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
if (arrayIndex >= array.Length)
throw new ArgumentException("arrayIndex is equal to or greater than the length of array.");
if (Count > array.Length - arrayIndex)
throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.");
int index = 0;
foreach (JProperty property in ChildrenTokens)
{
array[arrayIndex + index] = new KeyValuePair<string, JToken>(property.Name, property.Value);
index++;
}
}
bool ICollection<KeyValuePair<string, JToken>>.IsReadOnly
{
get { return false; }
}
bool ICollection<KeyValuePair<string, JToken>>.Remove(KeyValuePair<string, JToken> item)
{
if (!((ICollection<KeyValuePair<string, JToken>>)this).Contains(item))
return false;
((IDictionary<string, JToken>)this).Remove(item.Key);
return true;
}
#endregion
internal override int GetDeepHashCode()
{
return ContentsHashCode();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<KeyValuePair<string, JToken>> GetEnumerator()
{
foreach (JProperty property in ChildrenTokens)
{
yield return new KeyValuePair<string, JToken>(property.Name, property.Value);
}
}
/// <summary>
/// Raises the <see cref="PropertyChanged"/> event with the provided arguments.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
// include custom type descriptor on JObject rather than use a provider because the properties are specific to a type
#region ICustomTypeDescriptor
/// <summary>
/// Returns the properties for this instance of a component.
/// </summary>
/// <returns>
/// A <see cref="T:System.ComponentModel.PropertyDescriptorCollection"/> that represents the properties for this component instance.
/// </returns>
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor)this).GetProperties(null);
}
private static Type GetTokenPropertyType(JToken token)
{
if (token is JValue)
{
JValue v = (JValue)token;
return (v.Value != null) ? v.Value.GetType() : typeof(object);
}
return token.GetType();
}
/// <summary>
/// Returns the properties for this instance of a component using the attribute array as a filter.
/// </summary>
/// <param name="attributes">An array of type <see cref="T:System.Attribute"/> that is used as a filter.</param>
/// <returns>
/// A <see cref="T:System.ComponentModel.PropertyDescriptorCollection"/> that represents the filtered properties for this component instance.
/// </returns>
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(System.Attribute[] attributes)
{
PropertyDescriptorCollection descriptors = new PropertyDescriptorCollection(null);
foreach (KeyValuePair<string, JToken> propertyValue in this)
{
descriptors.Add(new JPropertyDescriptor(propertyValue.Key, GetTokenPropertyType(propertyValue.Value)));
}
return descriptors;
}
/// <summary>
/// Returns a collection of custom attributes for this instance of a component.
/// </summary>
/// <returns>
/// An <see cref="T:System.ComponentModel.AttributeCollection"/> containing the attributes for this object.
/// </returns>
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return AttributeCollection.Empty;
}
/// <summary>
/// Returns the class name of this instance of a component.
/// </summary>
/// <returns>
/// The class name of the object, or null if the class does not have a name.
/// </returns>
string ICustomTypeDescriptor.GetClassName()
{
return null;
}
/// <summary>
/// Returns the name of this instance of a component.
/// </summary>
/// <returns>
/// The name of the object, or null if the object does not have a name.
/// </returns>
string ICustomTypeDescriptor.GetComponentName()
{
return null;
}
/// <summary>
/// Returns a type converter for this instance of a component.
/// </summary>
/// <returns>
/// A <see cref="T:System.ComponentModel.TypeConverter"/> that is the converter for this object, or null if there is no <see cref="T:System.ComponentModel.TypeConverter"/> for this object.
/// </returns>
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return new TypeConverter();
}
/// <summary>
/// Returns the default event for this instance of a component.
/// </summary>
/// <returns>
/// An <see cref="T:System.ComponentModel.EventDescriptor"/> that represents the default event for this object, or null if this object does not have events.
/// </returns>
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return null;
}
/// <summary>
/// Returns the default property for this instance of a component.
/// </summary>
/// <returns>
/// A <see cref="T:System.ComponentModel.PropertyDescriptor"/> that represents the default property for this object, or null if this object does not have properties.
/// </returns>
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return null;
}
/// <summary>
/// Returns an editor of the specified type for this instance of a component.
/// </summary>
/// <param name="editorBaseType">A <see cref="T:System.Type"/> that represents the editor for this object.</param>
/// <returns>
/// An <see cref="T:System.Object"/> of the specified type that is the editor for this object, or null if the editor cannot be found.
/// </returns>
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return null;
}
/// <summary>
/// Returns the events for this instance of a component using the specified attribute array as a filter.
/// </summary>
/// <param name="attributes">An array of type <see cref="T:System.Attribute"/> that is used as a filter.</param>
/// <returns>
/// An <see cref="T:System.ComponentModel.EventDescriptorCollection"/> that represents the filtered events for this component instance.
/// </returns>
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(System.Attribute[] attributes)
{
return EventDescriptorCollection.Empty;
}
/// <summary>
/// Returns the events for this instance of a component.
/// </summary>
/// <returns>
/// An <see cref="T:System.ComponentModel.EventDescriptorCollection"/> that represents the events for this component instance.
/// </returns>
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return EventDescriptorCollection.Empty;
}
/// <summary>
/// Returns an object that contains the property described by the specified property descriptor.
/// </summary>
/// <param name="pd">A <see cref="T:System.ComponentModel.PropertyDescriptor"/> that represents the property whose owner is to be found.</param>
/// <returns>
/// An <see cref="T:System.Object"/> that represents the owner of the specified property.
/// </returns>
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return null;
}
#endregion
#endif
}
}
#endif
| |
#define TRACE_ADJUSTMENTS
using System.Diagnostics;
using TickedPriorityQueue;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace UnitySteer.Behaviors
{
/// <summary>
/// Vehicle subclass oriented towards autonomous bipeds and vehicles, which
/// will be ticked automatically to calculate their direction.
/// </summary>
public abstract class TickedVehicle : Vehicle
{
#region Internal state values
private TickedObject _tickedObject;
private UnityTickedQueue _steeringQueue;
/// <summary>
/// The name of the steering queue for this ticked vehicle.
/// </summary>
[SerializeField] private string _queueName = "Steering";
/// <summary>
/// How often will this Vehicle's steering calculations be ticked.
/// </summary>
[SerializeField] private float _tickLength = 0.1f;
/// <summary>
/// The maximum number of radar update calls processed on the queue per update
/// </summary>
/// <remarks>
/// Notice that this is a limit shared across queue items of the same name, at
/// least until we have some queue settings, so whatever value is set last for
/// the queue will win. Make sure your settings are consistent for objects of
/// the same queue.
/// </remarks>
[SerializeField] private int _maxQueueProcessedPerUpdate = 20;
[SerializeField] private bool _traceAdjustments = false;
#endregion
public CharacterController CharacterController { get; private set; }
/// <summary>
/// Last time the vehicle's tick was completed.
/// </summary>
/// <value>The last tick time.</value>
public float PreviousTickTime { get; private set; }
/// <summary>
/// Current time that the tick was called.
/// </summary>
/// <value>The current tick time.</value>
public float CurrentTickTime { get; private set; }
/// <summary>
/// The time delta between now and when the vehicle's previous tick time and the current one.
/// </summary>
/// <value>The delta time.</value>
public override float DeltaTime
{
get { return CurrentTickTime - PreviousTickTime; }
}
/// <summary>
/// Velocity vector used to orient the agent.
/// </summary>
/// <remarks>
/// This is expected to be set by the subclasses.
/// </remarks>
public Vector3 OrientationVelocity { get; protected set; }
public string QueueName
{
get { return _queueName; }
set { _queueName = value; }
}
/// <summary>
/// Priority queue for this vehicle's updates
/// </summary>
public UnityTickedQueue SteeringQueue
{
get { return _steeringQueue; }
}
/// <summary>
/// Ticked object for the vehicle, so that its owner can configure
/// the priority as desired.
/// </summary>
public TickedObject TickedObject { get; private set; }
#region Unity events
private void Start()
{
CharacterController = GetComponent<CharacterController>();
PreviousTickTime = Time.time;
}
protected override void OnEnable()
{
base.OnEnable();
TickedObject = new TickedObject(OnUpdateSteering);
TickedObject.TickLength = _tickLength;
_steeringQueue = UnityTickedQueue.GetInstance(QueueName);
_steeringQueue.Add(TickedObject);
_steeringQueue.MaxProcessedPerUpdate = _maxQueueProcessedPerUpdate;
}
protected override void OnDisable()
{
DeQueue();
base.OnDisable();
}
#endregion
#region Velocity / Speed methods
private void DeQueue()
{
if (_steeringQueue != null)
{
_steeringQueue.Remove(TickedObject);
}
}
protected void OnUpdateSteering(object obj)
{
if (enabled)
{
// We just calculate the forces, and expect the radar updates itself.
CalculateForces();
}
else
{
/*
* This is an interesting edge case.
*
* Because of the way TickedQueue iterates through its items, we may have
* a case where:
* - The vehicle's OnUpdateSteering is enqueued into the work queue
* - An event previous to it being called causes it to be disabled, and de-queued
* - When the ticked queue gets to it, it executes and re-enqueues it
*
* Therefore we double check that we're not trying to tick it while disabled, and
* if so we de-queue it. Must review TickedQueue to see if there's a way we can
* easily handle these sort of issues without a performance hit.
*/
DeQueue();
// Debug.LogError(string.Format("{0} HOLD YOUR HORSES. Disabled {1} being ticked", Time.time, this));
}
}
protected void CalculateForces()
{
PreviousTickTime = CurrentTickTime;
CurrentTickTime = Time.time;
if (!CanMove || Mathf.Approximately(MaxForce, 0) || Mathf.Approximately(MaxSpeed, 0))
{
return;
}
Profiler.BeginSample("Calculating vehicle forces");
var force = Vector3.zero;
Profiler.BeginSample("Adding up basic steerings");
for (var i = 0; i < Steerings.Length; i++)
{
var s = Steerings[i];
if (s.enabled)
{
force += s.WeighedForce;
}
}
Profiler.EndSample();
LastRawForce = force;
// Enforce speed limit. Steering behaviors are expected to return a
// final desired velocity, not a acceleration, so we apply them directly.
var newVelocity = Vector3.ClampMagnitude(force / Mass, MaxForce);
if (newVelocity.sqrMagnitude == 0)
{
ZeroVelocity();
DesiredVelocity = Vector3.zero;
}
else
{
DesiredVelocity = newVelocity;
}
// Adjusts the velocity by applying the post-processing behaviors.
//
// This currently is not also considering the maximum force, nor
// blending the new velocity into an accumulator. We *could* do that,
// but things are working just fine for now, and it seems like
// overkill.
var adjustedVelocity = Vector3.zero;
Profiler.BeginSample("Adding up post-processing steerings");
for (var i = 0; i < SteeringPostprocessors.Length; i++)
{
var s = SteeringPostprocessors[i];
if (s.enabled)
{
adjustedVelocity += s.WeighedForce;
}
}
Profiler.EndSample();
if (adjustedVelocity != Vector3.zero)
{
adjustedVelocity = Vector3.ClampMagnitude(adjustedVelocity, MaxSpeed);
TraceDisplacement(adjustedVelocity, Color.cyan);
TraceDisplacement(newVelocity, Color.white);
newVelocity = adjustedVelocity;
}
// Update vehicle velocity
SetCalculatedVelocity(newVelocity);
Profiler.EndSample();
}
/// <summary>
/// Applies a steering force to this vehicle
/// </summary>
/// <param name="elapsedTime">
/// How long has elapsed since the last update<see cref="System.Single"/>
/// </param>
private void ApplySteeringForce(float elapsedTime)
{
// Euler integrate (per frame) velocity into position
var acceleration = CalculatePositionDelta(elapsedTime);
acceleration = Vector3.Scale(acceleration, AllowedMovementAxes);
if (CharacterController != null)
{
CharacterController.Move(acceleration);
}
else if (Rigidbody == null || Rigidbody.isKinematic)
{
Transform.position += acceleration;
}
else
{
Rigidbody.MovePosition(Rigidbody.position + acceleration);
}
}
/// <summary>
/// Turns the vehicle towards his velocity vector. Previously called
/// LookTowardsVelocity.
/// </summary>
/// <param name="deltaTime">Time delta to use for turn calculations</param>
protected void AdjustOrientation(float deltaTime)
{
/*
* Avoid adjusting if we aren't applying any velocity. We also
* disregard very small velocities, to avoid jittery movement on
* rounding errors.
*/
if (TargetSpeed > MinSpeedForTurning && Velocity != Vector3.zero)
{
var newForward = Vector3.Scale(OrientationVelocity, AllowedMovementAxes).normalized;
if (TurnTime > 0)
{
newForward = Vector3.Slerp(Transform.forward, newForward, deltaTime / TurnTime);
}
Transform.forward = newForward;
}
}
/// <summary>
/// Records the velocity that was just calculated by CalculateForces in a
/// manner that is specific to each subclass.
/// </summary>
/// <param name="velocity">Newly calculated velocity</param>
protected abstract void SetCalculatedVelocity(Vector3 velocity);
/// <summary>
/// Calculates how much the agent's position should change in a manner that
/// is specific to the vehicle's implementation.
/// </summary>
/// <param name="deltaTime">Time delta to use in position calculations</param>
protected abstract Vector3 CalculatePositionDelta(float deltaTime);
/// <summary>
/// Zeros this vehicle's velocity.
/// </summary>
/// <remarks>
/// Implementation details are left up to the subclasses.
/// </remarks>
protected abstract void ZeroVelocity();
#endregion
private void Update()
{
if (CanMove)
{
ApplySteeringForce(Time.deltaTime);
AdjustOrientation(Time.deltaTime);
}
}
[Conditional("TRACE_ADJUSTMENTS")]
private void TraceDisplacement(Vector3 delta, Color color)
{
if (_traceAdjustments)
{
Debug.DrawLine(Transform.position, Transform.position + delta, color);
}
}
public void Stop()
{
CanMove = false;
ZeroVelocity();
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira 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.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class ExceptionHandler : Node
{
protected Declaration _declaration;
protected Expression _filterCondition;
protected ExceptionHandlerFlags _flags;
protected Block _block;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ExceptionHandler CloneNode()
{
return (ExceptionHandler)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ExceptionHandler CleanClone()
{
return (ExceptionHandler)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.ExceptionHandler; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnExceptionHandler(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( ExceptionHandler)node;
if (!Node.Matches(_declaration, other._declaration)) return NoMatch("ExceptionHandler._declaration");
if (!Node.Matches(_filterCondition, other._filterCondition)) return NoMatch("ExceptionHandler._filterCondition");
if (_flags != other._flags) return NoMatch("ExceptionHandler._flags");
if (!Node.Matches(_block, other._block)) return NoMatch("ExceptionHandler._block");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_declaration == existing)
{
this.Declaration = (Declaration)newNode;
return true;
}
if (_filterCondition == existing)
{
this.FilterCondition = (Expression)newNode;
return true;
}
if (_block == existing)
{
this.Block = (Block)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
ExceptionHandler clone = new ExceptionHandler();
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
if (null != _declaration)
{
clone._declaration = _declaration.Clone() as Declaration;
clone._declaration.InitializeParent(clone);
}
if (null != _filterCondition)
{
clone._filterCondition = _filterCondition.Clone() as Expression;
clone._filterCondition.InitializeParent(clone);
}
clone._flags = _flags;
if (null != _block)
{
clone._block = _block.Clone() as Block;
clone._block.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _declaration)
{
_declaration.ClearTypeSystemBindings();
}
if (null != _filterCondition)
{
_filterCondition.ClearTypeSystemBindings();
}
if (null != _block)
{
_block.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Declaration Declaration
{
get { return _declaration; }
set
{
if (_declaration != value)
{
_declaration = value;
if (null != _declaration)
{
_declaration.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression FilterCondition
{
get { return _filterCondition; }
set
{
if (_filterCondition != value)
{
_filterCondition = value;
if (null != _filterCondition)
{
_filterCondition.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ExceptionHandlerFlags Flags
{
get { return _flags; }
set { _flags = value; }
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Block Block
{
get
{
if (_block == null)
{
_block = new Block();
_block.InitializeParent(this);
}
return _block;
}
set
{
if (_block != value)
{
_block = value;
if (null != _block)
{
_block.InitializeParent(this);
}
}
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
namespace Igor
{
public class InputOutputBox<EntityType> : EntityBox<EntityType> where EntityType : LinkedEntity<EntityType>, new()
{
public bool bIsInputBox;
public InputOutputBox(GraphWindow<EntityType> Owner, EntityType EntityToWatch, string InBoxTitle, bool InbIsInputBox) : base(Owner, EntityToWatch)
{
bIsInputBox = InbIsInputBox;
BoxTitle = InBoxTitle;
bReadOnlyTitle = true;
bReadOnlyInputList = bIsInputBox;
bReadOnlyOutputList = !bIsInputBox;
UpdateAnchors();
}
public override string GetTypeName()
{
return "InputOutput";
}
public override string GetBoxKey()
{
return "InputOutputBox" + (bIsInputBox ? "Input" : "Output");
}
public override bool HandleContextMenu(GenericMenu GenericContextMenu)
{
return true;
}
public virtual LinkedEntityManager<EntityType> GetManager()
{
return null;
}
public override void GainedFocus()
{
InspectorPicker.AddHandler(GetTypeName(), EntityDrawInspectorWidgets);
InspectorPicker.SelectInstance(GetTypeName(), this);
}
public override void OnInspectorGUIClickedSaveButton()
{
/* if(WrappedInstance.GetFilename().Length == 0 && WrappedInstance.Title.Length > 0)
{
string UniqueName = GetUniqueFilename(WrappedInstance.Title);
WrappedInstance.EditorSetFilename(UniqueName);
}
SaveEntities();
Owner.SerializeBoxMetadata(true);*/
}
public override void EntityDrawInspectorWidgets(object Instance)
{
InputOutputBox<EntityType> EntityInst = (InputOutputBox<EntityType>)Instance;
OnInspectorGUIDrawSaveButton(GetClassTypeSaveString());
string TempBoxTitle = EntityInst.GetBoxTitle();
InspectorGUIString("Title", ref TempBoxTitle, bReadOnlyTitle);
if(bIsInputBox)
{
InspectorDrawStartWidgets();
}
else
{
InspectorDrawEndWidgets();
}
}
public virtual void InspectorDrawStartWidgets()
{
}
public virtual void InspectorDrawEndWidgets()
{
}
public virtual List<EntityLink<EntityType>> GetStartEntities()
{
return null;
}
public virtual List<EntityLink<EntityType>> GetEndEntities()
{
return null;
}
public override void BuildConnectionsFromSourceData()
{
if(bIsInputBox)
{
List<EntityLink<EntityType>> OutputEvents = GetStartEntities();
foreach(EntityLink<EntityType> CurrentLink in OutputEvents)
{
Anchor<EntityType> LocalAnchor = GetAnchor("Output" + CurrentLink.Name);
if(LocalAnchor != null)
{
foreach(EntityLink<EntityType> CurrentRemoteLink in CurrentLink.LinkedEntities)
{
if(CurrentRemoteLink.GetOwner() != null)
{
if(CurrentRemoteLink.GetOwner().InputEvents.Contains(CurrentRemoteLink))
{
EntityBox<EntityType> RemoteBox = Owner.GetEntityBoxForEntity(CurrentRemoteLink.GetOwner());
if(RemoteBox != null)
{
Anchor<EntityType> RemoteAnchor = RemoteBox.GetAnchor("Input" + CurrentRemoteLink.Name);
if(RemoteAnchor != null)
{
Owner.ConnectInputToOutput(LocalAnchor, RemoteAnchor);
}
}
}
}
else
{
EntityBox<EntityType> EndBox = Owner.GetOutputBox();
if(EndBox != null)
{
Anchor<EntityType> RemoteAnchor = EndBox.GetAnchor("Input" + CurrentRemoteLink.Name);
if(RemoteAnchor != null)
{
Owner.ConnectInputToOutput(LocalAnchor, RemoteAnchor);
}
}
}
}
}
}
}
else
{
List<EntityLink<EntityType>> InputEvents = GetEndEntities();
foreach(EntityLink<EntityType> CurrentLink in InputEvents)
{
Anchor<EntityType> LocalAnchor = GetAnchor("Input" + CurrentLink.Name);
if(LocalAnchor != null)
{
foreach(EntityLink<EntityType> CurrentRemoteLink in CurrentLink.LinkedEntities)
{
if(CurrentRemoteLink.GetOwner() != null)
{
if(CurrentRemoteLink.GetOwner().OutputEvents.Contains(CurrentRemoteLink))
{
EntityBox<EntityType> RemoteBox = Owner.GetEntityBoxForEntity(CurrentRemoteLink.GetOwner());
if(RemoteBox != null)
{
Anchor<EntityType> RemoteAnchor = RemoteBox.GetAnchor("Output" + CurrentRemoteLink.Name);
if(RemoteAnchor != null)
{
Owner.ConnectInputToOutput(LocalAnchor, RemoteAnchor);
}
}
}
}
else
{
EntityBox<EntityType> StartBox = Owner.GetInputBox();
if(StartBox != null)
{
Anchor<EntityType> RemoteAnchor = StartBox.GetAnchor("Input" + CurrentRemoteLink.Name);
if(RemoteAnchor != null)
{
Owner.ConnectInputToOutput(LocalAnchor, RemoteAnchor);
}
}
}
}
}
}
}
}
public override void FixOneWayLinks()
{
List<EntityLink<EntityType>> Events = null;
if(bIsInputBox)
{
Events = GetStartEntities();
}
else
{
Events = GetEndEntities();
}
if(Events != null)
{
foreach(EntityLink<EntityType> CurrentConnector in Events)
{
foreach(EntityLink<EntityType> RemoteConnector in CurrentConnector.LinkedEntities)
{
bool bFound = false;
foreach(EntityLink<EntityType> RemoteRemoteConnector in RemoteConnector.LinkedEntities)
{
if(RemoteRemoteConnector.GetOwner() == CurrentConnector.GetOwner() && RemoteRemoteConnector.Name == CurrentConnector.Name)
{
bFound = true;
break;
}
}
if(!bFound)
{
bErrorInNode = true;
}
}
}
}
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Core.ConnectedAngularAppsV2Web
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#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.Diagnostics;
using Internal.Runtime.Augments;
namespace System.Threading
{
internal static partial class WaitSubsystem
{
/// <summary>
/// Contains thread-specific information for the wait subsystem. There is one instance per thread that is registered
/// using <see cref="WaitedListNode"/>s with each <see cref="WaitableObject"/> that the thread is waiting upon.
///
/// Used by the wait subsystem on Unix, so this class cannot have any dependencies on the wait subsystem.
/// </summary>
public sealed class ThreadWaitInfo
{
private readonly RuntimeThread _thread;
/// <summary>
/// The monitor the thread would wait upon when the wait needs to be interruptible
/// </summary>
private readonly LowLevelMonitor _waitMonitor;
////////////////////////////////////////////////////////////////
/// Thread wait state. The following members indicate the waiting state of the thread, and convery information from
/// a signaler to the waiter. They are synchronized with <see cref="_waitMonitor"/>.
private WaitSignalState _waitSignalState;
/// <summary>
/// Index of the waitable object in <see cref="_waitedObjects"/>, which got signaled and satisfied the wait. -1 if
/// the wait has not yet been satisfied.
/// </summary>
private int _waitedObjectIndexThatSatisfiedWait;
////////////////////////////////////////////////////////////////
/// Information about the current wait, including the type of wait, the <see cref="WaitableObject"/>s involved in
/// the wait, etc. They are synchronized with <see cref="s_lock"/>.
private bool _isWaitForAll;
/// <summary>
/// Number of <see cref="WaitableObject"/>s the thread is waiting upon
/// </summary>
private int _waitedCount;
/// <summary>
/// - <see cref="WaitableObject"/>s that are waited upon by the thread. This array is also used for temporarily
/// storing <see cref="WaitableObject"/>s corresponding to <see cref="WaitHandle"/>s when the thread is not
/// waiting.
/// - The count of this array is a power of 2, the filled count is <see cref="_waitedCount"/>
/// - Indexes in all arrays that use <see cref="_waitedCount"/> correspond
/// </summary>
private WaitHandleArray<WaitableObject> _waitedObjects;
/// <summary>
/// - Nodes used for registering a thread's wait on each <see cref="WaitableObject"/>, in the
/// <see cref="WaitableObject.WaitersHead"/> linked list
/// - The count of this array is a power of 2, the filled count is <see cref="_waitedCount"/>
/// - Indexes in all arrays that use <see cref="_waitedCount"/> correspond
/// </summary>
private WaitHandleArray<WaitedListNode> _waitedListNodes;
/// <summary>
/// Indicates whether the next wait should be interrupted.
///
/// Synchronization:
/// - In most cases, reads and writes are synchronized with <see cref="s_lock"/>
/// - Sleep(nonzero) intentionally does not acquire <see cref="s_lock"/>, but it must acquire
/// <see cref="_waitMonitor"/> to do the wait. To support this case, a pending interrupt is recorded while
/// <see cref="s_lock"/> and <see cref="_waitMonitor"/> are locked, and the read and reset for Sleep(nonzero) are
/// done while <see cref="_waitMonitor"/> is locked.
/// - Sleep(0) intentionally does not acquire any lock, so it uses an interlocked compare-exchange for the read and
/// reset, see <see cref="CheckAndResetPendingInterrupt_NotLocked"/>
/// </summary>
private int _isPendingInterrupt;
////////////////////////////////////////////////////////////////
/// <summary>
/// Linked list of mutex <see cref="WaitableObject"/>s that are owned by the thread and need to be abandoned before
/// the thread exits. The linked list has only a head and no tail, which means acquired mutexes are prepended and
/// mutexes are abandoned in reverse order.
/// </summary>
private WaitableObject _lockedMutexesHead;
public ThreadWaitInfo(RuntimeThread thread)
{
Debug.Assert(thread != null);
_thread = thread;
_waitMonitor = new LowLevelMonitor();
_waitSignalState = WaitSignalState.NotWaiting;
_waitedObjectIndexThatSatisfiedWait = -1;
_waitedObjects = new WaitHandleArray<WaitableObject>(elementInitializer: null);
_waitedListNodes = new WaitHandleArray<WaitedListNode>(i => new WaitedListNode(this, i));
}
public RuntimeThread Thread => _thread;
private bool IsWaiting
{
get
{
_waitMonitor.VerifyIsLocked();
return _waitSignalState < WaitSignalState.NotWaiting;
}
}
/// <summary>
/// Callers must ensure to clear the array after use. Once <see cref="RegisterWait(int, bool)"/> is called (followed
/// by a call to <see cref="Wait(int, bool, out int)"/>, the array will be cleared automatically.
/// </summary>
public WaitableObject[] GetWaitedObjectArray(int requiredCapacity)
{
Debug.Assert(_thread == RuntimeThread.CurrentThread);
Debug.Assert(_waitedCount == 0);
_waitedObjects.VerifyElementsAreDefault();
_waitedObjects.EnsureCapacity(requiredCapacity);
return _waitedObjects.Items;
}
private WaitedListNode[] GetWaitedListNodeArray(int requiredCapacity)
{
Debug.Assert(_thread == RuntimeThread.CurrentThread);
Debug.Assert(_waitedCount == 0);
_waitedListNodes.EnsureCapacity(requiredCapacity, i => new WaitedListNode(this, i));
return _waitedListNodes.Items;
}
/// <summary>
/// The caller is expected to populate <see cref="WaitedObjects"/> and pass in the number of objects filled
/// </summary>
public void RegisterWait(int waitedCount, bool prioritize, bool isWaitForAll)
{
s_lock.VerifyIsLocked();
Debug.Assert(_thread == RuntimeThread.CurrentThread);
Debug.Assert(waitedCount > (isWaitForAll ? 1 : 0));
Debug.Assert(waitedCount <= _waitedObjects.Items.Length);
Debug.Assert(_waitedCount == 0);
WaitableObject[] waitedObjects = _waitedObjects.Items;
#if DEBUG
for (int i = 0; i < waitedCount; ++i)
{
Debug.Assert(waitedObjects[i] != null);
}
for (int i = waitedCount; i < waitedObjects.Length; ++i)
{
Debug.Assert(waitedObjects[i] == null);
}
#endif
bool success = false;
WaitedListNode[] waitedListNodes;
try
{
waitedListNodes = GetWaitedListNodeArray(waitedCount);
success = true;
}
finally
{
if (!success)
{
// Once this function is called, the caller is effectively transferring ownership of the waited objects
// to this and the wait functions. On exception, clear the array.
for (int i = 0; i < waitedCount; ++i)
{
waitedObjects[i] = null;
}
}
}
_isWaitForAll = isWaitForAll;
_waitedCount = waitedCount;
if (prioritize)
{
for (int i = 0; i < waitedCount; ++i)
{
waitedListNodes[i].RegisterPrioritizedWait(waitedObjects[i]);
}
}
else
{
for (int i = 0; i < waitedCount; ++i)
{
waitedListNodes[i].RegisterWait(waitedObjects[i]);
}
}
}
public void UnregisterWait()
{
s_lock.VerifyIsLocked();
Debug.Assert(_waitedCount > (_isWaitForAll ? 1 : 0));
for (int i = 0; i < _waitedCount; ++i)
{
_waitedListNodes.Items[i].UnregisterWait(_waitedObjects.Items[i]);
_waitedObjects.Items[i] = null;
}
_waitedCount = 0;
}
private int ProcessSignaledWaitState(WaitHandle[] waitHandlesForAbandon)
{
s_lock.VerifyIsNotLocked();
_waitMonitor.VerifyIsLocked();
Debug.Assert(_thread == RuntimeThread.CurrentThread);
switch (_waitSignalState)
{
case WaitSignalState.Waiting:
case WaitSignalState.Waiting_Interruptible:
return WaitHandle.WaitTimeout;
case WaitSignalState.NotWaiting_SignaledToSatisfyWait:
{
Debug.Assert(_waitedObjectIndexThatSatisfiedWait >= 0);
int waitedObjectIndexThatSatisfiedWait = _waitedObjectIndexThatSatisfiedWait;
_waitedObjectIndexThatSatisfiedWait = -1;
return waitedObjectIndexThatSatisfiedWait;
}
case WaitSignalState.NotWaiting_SignaledToSatisfyWaitWithAbandonedMutex:
Debug.Assert(_waitedObjectIndexThatSatisfiedWait >= 0);
if (waitHandlesForAbandon == null)
{
_waitedObjectIndexThatSatisfiedWait = -1;
throw new AbandonedMutexException();
}
else
{
int waitedObjectIndexThatSatisfiedWait = _waitedObjectIndexThatSatisfiedWait;
_waitedObjectIndexThatSatisfiedWait = -1;
throw
new AbandonedMutexException(
waitedObjectIndexThatSatisfiedWait,
waitHandlesForAbandon[waitedObjectIndexThatSatisfiedWait]);
}
case WaitSignalState.NotWaiting_SignaledToAbortWaitDueToMaximumMutexReacquireCount:
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
throw new OverflowException(SR.Overflow_MutexReacquireCount);
default:
Debug.Assert(_waitSignalState == WaitSignalState.NotWaiting_SignaledToInterruptWait);
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
throw new ThreadInterruptedException();
}
}
public int Wait(int timeoutMilliseconds, bool interruptible, WaitHandle[] waitHandlesForAbandon, bool isSleep)
{
if (isSleep)
{
s_lock.VerifyIsNotLocked();
Debug.Assert(waitHandlesForAbandon == null);
}
else
{
s_lock.VerifyIsLocked();
}
Debug.Assert(_thread == RuntimeThread.CurrentThread);
Debug.Assert(timeoutMilliseconds >= -1);
Debug.Assert(timeoutMilliseconds != 0); // caller should have taken care of it
_thread.SetWaitSleepJoinState();
/// <see cref="_waitMonitor"/> must be acquired before <see cref="s_lock"/> is released, to ensure that there is
/// no gap during which a waited object may be signaled to satisfy the wait but the thread may not yet be in a
/// wait state to accept the signal
_waitMonitor.Acquire();
if (!isSleep)
{
s_lock.Release();
}
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
Debug.Assert(_waitSignalState == WaitSignalState.NotWaiting);
// A signaled state may be set only when the thread is in one of the following states
_waitSignalState = interruptible ? WaitSignalState.Waiting_Interruptible : WaitSignalState.Waiting;
try
{
if (isSleep && interruptible && CheckAndResetPendingInterrupt)
{
throw new ThreadInterruptedException();
}
if (timeoutMilliseconds < 0)
{
do
{
_waitMonitor.Wait();
} while (IsWaiting);
int waitResult = ProcessSignaledWaitState(waitHandlesForAbandon);
Debug.Assert(waitResult != WaitHandle.WaitTimeout);
return waitResult;
}
int elapsedMilliseconds = 0;
int startTimeMilliseconds = Environment.TickCount;
while (true)
{
bool monitorWaitResult = _waitMonitor.Wait(timeoutMilliseconds - elapsedMilliseconds);
// It's possible for the wait to have timed out, but before the monitor could reacquire the lock, a
// signaler could have acquired it and signaled to satisfy the wait or interrupt the thread. Accept the
// signal and ignore the wait timeout.
int waitResult = ProcessSignaledWaitState(waitHandlesForAbandon);
if (waitResult != WaitHandle.WaitTimeout)
{
return waitResult;
}
if (monitorWaitResult)
{
elapsedMilliseconds = Environment.TickCount - startTimeMilliseconds;
if (elapsedMilliseconds < timeoutMilliseconds)
{
continue;
}
}
// Timeout
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
break;
}
}
finally
{
_waitSignalState = WaitSignalState.NotWaiting;
_waitMonitor.Release();
_thread.ClearWaitSleepJoinState();
}
/// Timeout. It's ok to read <see cref="_waitedCount"/> without acquiring <see cref="s_lock"/> here, because it
/// is initially set by this thread, and another thread cannot unregister this thread's wait without first
/// signaling this thread, in which case this thread wouldn't be timing out.
Debug.Assert(isSleep == (_waitedCount == 0));
if (!isSleep)
{
s_lock.Acquire();
UnregisterWait();
s_lock.Release();
}
return WaitHandle.WaitTimeout;
}
public static void UninterruptibleSleep0()
{
s_lock.VerifyIsNotLocked();
// On Unix, a thread waits on a condition variable. The timeout time will have already elapsed at the time
// of the call. The documentation does not state whether the thread yields or does nothing before returning
// an error, and in some cases, suggests that doing nothing is acceptable. The behavior could also be
// different between distributions. Yield directly here.
RuntimeThread.Yield();
}
public static void Sleep(int timeoutMilliseconds, bool interruptible)
{
s_lock.VerifyIsNotLocked();
Debug.Assert(timeoutMilliseconds >= -1);
if (timeoutMilliseconds == 0)
{
if (interruptible && RuntimeThread.CurrentThread.WaitInfo.CheckAndResetPendingInterrupt_NotLocked)
{
throw new ThreadInterruptedException();
}
UninterruptibleSleep0();
return;
}
int waitResult =
RuntimeThread
.CurrentThread
.WaitInfo
.Wait(timeoutMilliseconds, interruptible, waitHandlesForAbandon: null, isSleep: true);
Debug.Assert(waitResult == WaitHandle.WaitTimeout);
}
public bool TrySignalToSatisfyWait(WaitedListNode registeredListNode, bool isAbandonedMutex)
{
s_lock.VerifyIsLocked();
Debug.Assert(_thread != RuntimeThread.CurrentThread);
Debug.Assert(registeredListNode != null);
Debug.Assert(registeredListNode.WaitInfo == this);
Debug.Assert(registeredListNode.WaitedObjectIndex >= 0);
Debug.Assert(registeredListNode.WaitedObjectIndex < _waitedCount);
Debug.Assert(_waitedCount > (_isWaitForAll ? 1 : 0));
int signaledWaitedObjectIndex = registeredListNode.WaitedObjectIndex;
bool isWaitForAll = _isWaitForAll;
int waitedCount = 0;
WaitableObject[] waitedObjects = null;
bool wouldAnyMutexReacquireCountOverflow = false;
if (isWaitForAll)
{
// Determine if all waits would be satisfied
waitedCount = _waitedCount;
waitedObjects = _waitedObjects.Items;
if (!WaitableObject.WouldWaitForAllBeSatisfiedOrAborted(
_thread,
waitedObjects,
waitedCount,
signaledWaitedObjectIndex,
ref wouldAnyMutexReacquireCountOverflow,
ref isAbandonedMutex))
{
return false;
}
}
// The wait would be satisfied. Before making changes to satisfy the wait, acquire the monitor and verify that
// the thread can accept a signal.
_waitMonitor.Acquire();
if (!IsWaiting)
{
_waitMonitor.Release();
return false;
}
if (isWaitForAll && !wouldAnyMutexReacquireCountOverflow)
{
// All waits would be satisfied, accept the signals
WaitableObject.SatisfyWaitForAll(this, waitedObjects, waitedCount, signaledWaitedObjectIndex);
}
UnregisterWait();
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
if (wouldAnyMutexReacquireCountOverflow)
{
_waitSignalState = WaitSignalState.NotWaiting_SignaledToAbortWaitDueToMaximumMutexReacquireCount;
}
else
{
_waitedObjectIndexThatSatisfiedWait = signaledWaitedObjectIndex;
_waitSignalState =
isAbandonedMutex
? WaitSignalState.NotWaiting_SignaledToSatisfyWaitWithAbandonedMutex
: WaitSignalState.NotWaiting_SignaledToSatisfyWait;
}
_waitMonitor.Signal_Release();
return !wouldAnyMutexReacquireCountOverflow;
}
public void TrySignalToInterruptWaitOrRecordPendingInterrupt()
{
s_lock.VerifyIsLocked();
_waitMonitor.Acquire();
if (_waitSignalState != WaitSignalState.Waiting_Interruptible)
{
RecordPendingInterrupt();
_waitMonitor.Release();
return;
}
if (_waitedCount != 0)
{
UnregisterWait();
}
Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0);
_waitSignalState = WaitSignalState.NotWaiting_SignaledToInterruptWait;
_waitMonitor.Signal_Release();
}
private void RecordPendingInterrupt()
{
s_lock.VerifyIsLocked();
_waitMonitor.VerifyIsLocked();
_isPendingInterrupt = 1;
}
public bool CheckAndResetPendingInterrupt
{
get
{
#if DEBUG
Debug.Assert(s_lock.IsLocked || _waitMonitor.IsLocked);
#endif
if (_isPendingInterrupt == 0)
{
return false;
}
_isPendingInterrupt = 0;
return true;
}
}
private bool CheckAndResetPendingInterrupt_NotLocked
{
get
{
s_lock.VerifyIsNotLocked();
_waitMonitor.VerifyIsNotLocked();
return Interlocked.CompareExchange(ref _isPendingInterrupt, 0, 1) != 0;
}
}
public WaitableObject LockedMutexesHead
{
get
{
s_lock.VerifyIsLocked();
return _lockedMutexesHead;
}
set
{
s_lock.VerifyIsLocked();
_lockedMutexesHead = value;
}
}
public void OnThreadExiting()
{
// Abandon locked mutexes. Acquired mutexes are prepended to the linked list, so the mutexes are abandoned in
// last-acquired-first-abandoned order.
s_lock.Acquire();
try
{
while (true)
{
WaitableObject waitableObject = LockedMutexesHead;
if (waitableObject == null)
{
break;
}
waitableObject.AbandonMutex();
Debug.Assert(LockedMutexesHead != waitableObject);
}
}
finally
{
s_lock.Release();
}
}
public sealed class WaitedListNode
{
/// <summary>
/// For <see cref="WaitedListNode"/>s registered with <see cref="WaitableObject"/>s, this provides information
/// about the thread that is waiting and the <see cref="WaitableObject"/>s it is waiting upon
/// </summary>
private readonly ThreadWaitInfo _waitInfo;
/// <summary>
/// Index of the waited object corresponding to this node
/// </summary>
private readonly int _waitedObjectIndex;
/// <summary>
/// Link in the <see cref="WaitableObject.WaitersHead"/> linked list
/// </summary>
private WaitedListNode _previous, _next;
public WaitedListNode(ThreadWaitInfo waitInfo, int waitedObjectIndex)
{
Debug.Assert(waitInfo != null);
Debug.Assert(waitedObjectIndex >= 0);
Debug.Assert(waitedObjectIndex < WaitHandle.MaxWaitHandles);
_waitInfo = waitInfo;
_waitedObjectIndex = waitedObjectIndex;
}
public ThreadWaitInfo WaitInfo
{
get
{
s_lock.VerifyIsLocked();
return _waitInfo;
}
}
public int WaitedObjectIndex
{
get
{
s_lock.VerifyIsLocked();
return _waitedObjectIndex;
}
}
public WaitedListNode Previous
{
get
{
s_lock.VerifyIsLocked();
return _previous;
}
}
public WaitedListNode Next
{
get
{
s_lock.VerifyIsLocked();
return _next;
}
}
public void RegisterWait(WaitableObject waitableObject)
{
s_lock.VerifyIsLocked();
Debug.Assert(_waitInfo.Thread == RuntimeThread.CurrentThread);
Debug.Assert(waitableObject != null);
Debug.Assert(_previous == null);
Debug.Assert(_next == null);
WaitedListNode tail = waitableObject.WaitersTail;
if (tail != null)
{
_previous = tail;
tail._next = this;
}
else
{
waitableObject.WaitersHead = this;
}
waitableObject.WaitersTail = this;
}
public void RegisterPrioritizedWait(WaitableObject waitableObject)
{
s_lock.VerifyIsLocked();
Debug.Assert(_waitInfo.Thread == RuntimeThread.CurrentThread);
Debug.Assert(waitableObject != null);
Debug.Assert(_previous == null);
Debug.Assert(_next == null);
WaitedListNode head = waitableObject.WaitersHead;
if (head != null)
{
_next = head;
head._previous = this;
}
else
{
waitableObject.WaitersTail = this;
}
waitableObject.WaitersHead = this;
}
public void UnregisterWait(WaitableObject waitableObject)
{
s_lock.VerifyIsLocked();
Debug.Assert(waitableObject != null);
WaitedListNode previous = _previous;
WaitedListNode next = _next;
if (previous != null)
{
previous._next = next;
_previous = null;
}
else
{
Debug.Assert(waitableObject.WaitersHead == this);
waitableObject.WaitersHead = next;
}
if (next != null)
{
next._previous = previous;
_next = null;
}
else
{
Debug.Assert(waitableObject.WaitersTail == this);
waitableObject.WaitersTail = previous;
}
}
}
private enum WaitSignalState : byte
{
Waiting,
Waiting_Interruptible,
NotWaiting,
NotWaiting_SignaledToSatisfyWait,
NotWaiting_SignaledToSatisfyWaitWithAbandonedMutex,
NotWaiting_SignaledToAbortWaitDueToMaximumMutexReacquireCount,
NotWaiting_SignaledToInterruptWait
}
}
}
}
| |
// Copyright (c) 2002-2003, Sony Computer Entertainment America
// Copyright (c) 2002-2003, Craig Reynolds <[email protected]>
// Copyright (C) 2007 Bjoern Graf <[email protected]>
// Copyright (C) 2007 Michael Coles <[email protected]>
// All rights reserved.
//
// This software is licensed as described in the file license.txt, which
// you should have received as part of this distribution. The terms
// are also available at http://www.codeplex.com/SharpSteer/Project/License.aspx.
using System;
using System.Numerics;
namespace SharpSteer2.Helpers
{
public static class Vector3Helpers
{
/// <summary>
/// return component of vector parallel to a unit basis vector
/// </summary>
/// <param name="vector"></param>
/// <param name="unitBasis">A unit length basis vector</param>
/// <returns></returns>
public static Vector3 ParallelComponent(Vector3 vector, Vector3 unitBasis)
{
float projection = Vector3.Dot(vector, unitBasis);
return unitBasis * projection;
}
/// <summary>
/// return component of vector perpendicular to a unit basis vector
/// </summary>
/// <param name="vector"></param>
/// <param name="unitBasis">A unit length basis vector</param>
/// <returns></returns>
public static Vector3 PerpendicularComponent(Vector3 vector, Vector3 unitBasis)
{
return (vector - ParallelComponent(vector, unitBasis));
}
/// <summary>
/// clamps the length of a given vector to maxLength. If the vector is
/// shorter its value is returned unaltered, if the vector is longer
/// the value returned has length of maxLength and is parallel to the
/// original input.
/// </summary>
/// <param name="vector"></param>
/// <param name="maxLength"></param>
/// <returns></returns>
public static Vector3 TruncateLength(this Vector3 vector, float maxLength)
{
float maxLengthSquared = maxLength * maxLength;
float vecLengthSquared = vector.LengthSquared();
if (vecLengthSquared <= maxLengthSquared)
return vector;
return (vector * (maxLength / (float)Math.Sqrt(vecLengthSquared)));
}
/// <summary>
/// rotate this vector about the global Y (up) axis by the given angle
/// </summary>
/// <param name="vector"></param>
/// <param name="radians"></param>
/// <returns></returns>
public static Vector3 RotateAboutGlobalY(this Vector3 vector, float radians)
{
float s = 0;
float c = 0;
return RotateAboutGlobalY(vector, radians, ref s, ref c);
}
/// <summary>
/// Rotate this vector about the global Y (up) axis by the given angle
/// </summary>
/// <param name="vector"></param>
/// <param name="radians"></param>
/// <param name="sin">Either Sin(radians) or default(float), if default(float) this value will be initialized with Sin(radians)</param>
/// <param name="cos">Either Cos(radians) or default(float), if default(float) this value will be initialized with Cos(radians)</param>
/// <returns></returns>
public static Vector3 RotateAboutGlobalY(this Vector3 vector, float radians, ref float sin, ref float cos)
{
// if both are default, they have not been initialized yet
// ReSharper disable CompareOfFloatsByEqualityOperator
if (sin == default(float) && cos == default(float))
// ReSharper restore CompareOfFloatsByEqualityOperator
{
sin = (float)Math.Sin(radians);
cos = (float)Math.Cos(radians);
}
return new Vector3((vector.X * cos) + (vector.Z * sin), vector.Y, (vector.Z * cos) - (vector.X * sin));
}
/// <summary>
/// Wrap a position around so it is always within 1 radius of the sphere (keeps repeating wrapping until position is within sphere)
/// </summary>
/// <param name="vector"></param>
/// <param name="center"></param>
/// <param name="radius"></param>
/// <returns></returns>
public static Vector3 SphericalWrapAround(this Vector3 vector, Vector3 center, float radius)
{
float r;
do
{
Vector3 offset = vector - center;
r = offset.Length();
if (r > radius)
vector = vector + ((offset / r) * radius * -2);
} while (r > radius);
return vector;
}
/// <summary>
/// Returns a position randomly distributed on a disk of unit radius
/// on the XZ (Y=0) plane, centered at the origin. Orientation will be
/// random and length will range between 0 and 1
/// </summary>
/// <returns></returns>
public static Vector3 RandomVectorOnUnitRadiusXZDisk()
{
Vector3 v;
do
{
v.X = (RandomHelpers.Random() * 2) - 1;
v.Y = 0;
v.Z = (RandomHelpers.Random() * 2) - 1;
}
while (v.Length() >= 1);
return v;
}
/// <summary>
/// Returns a position randomly distributed inside a sphere of unit radius
/// centered at the origin. Orientation will be random and length will range
/// between 0 and 1
/// </summary>
/// <returns></returns>
public static Vector3 RandomVectorInUnitRadiusSphere()
{
Vector3 v = new Vector3();
do
{
v.X = (RandomHelpers.Random() * 2) - 1;
v.Y = (RandomHelpers.Random() * 2) - 1;
v.Z = (RandomHelpers.Random() * 2) - 1;
}
while (v.Length() >= 1);
return v;
}
/// <summary>
/// Returns a position randomly distributed on the surface of a sphere
/// of unit radius centered at the origin. Orientation will be random
/// and length will be 1
/// </summary>
/// <returns></returns>
public static Vector3 RandomUnitVector()
{
return Vector3.Normalize(RandomVectorInUnitRadiusSphere());
}
/// <summary>
/// Returns a position randomly distributed on a circle of unit radius
/// on the XZ (Y=0) plane, centered at the origin. Orientation will be
/// random and length will be 1
/// </summary>
/// <returns></returns>
public static Vector3 RandomUnitVectorOnXZPlane()
{
Vector3 temp = RandomVectorInUnitRadiusSphere();
temp.Y = 0;
temp = Vector3.Normalize(temp);
return temp;
}
/// <summary>
/// Clip a vector to be within the given cone
/// </summary>
/// <param name="source">A vector to clip</param>
/// <param name="cosineOfConeAngle">The cosine of the cone angle</param>
/// <param name="basis">The vector along the middle of the cone</param>
/// <returns></returns>
public static Vector3 LimitMaxDeviationAngle(this Vector3 source, float cosineOfConeAngle, Vector3 basis)
{
return LimitDeviationAngleUtility(true, // force source INSIDE cone
source, cosineOfConeAngle, basis);
}
/// <summary>
/// Clip a vector to be outside the given cone
/// </summary>
/// <param name="source">A vector to clip</param>
/// <param name="cosineOfConeAngle">The cosine of the cone angle</param>
/// <param name="basis">The vector along the middle of the cone</param>
/// <returns></returns>
public static Vector3 LimitMinDeviationAngle(this Vector3 source, float cosineOfConeAngle, Vector3 basis)
{
return LimitDeviationAngleUtility(false, // force source OUTSIDE cone
source, cosineOfConeAngle, basis);
}
/// <summary>
/// used by limitMaxDeviationAngle / limitMinDeviationAngle
/// </summary>
/// <param name="insideOrOutside"></param>
/// <param name="source"></param>
/// <param name="cosineOfConeAngle"></param>
/// <param name="basis"></param>
/// <returns></returns>
private static Vector3 LimitDeviationAngleUtility(bool insideOrOutside, Vector3 source, float cosineOfConeAngle, Vector3 basis)
{
// immediately return zero length input vectors
float sourceLength = source.Length();
if (sourceLength < float.Epsilon)
return source;
// measure the angular diviation of "source" from "basis"
Vector3 direction = source / sourceLength;
float cosineOfSourceAngle = Vector3.Dot(direction, basis);
// Simply return "source" if it already meets the angle criteria.
// (note: we hope this top "if" gets compiled out since the flag
// is a constant when the function is inlined into its caller)
if (insideOrOutside)
{
// source vector is already inside the cone, just return it
if (cosineOfSourceAngle >= cosineOfConeAngle)
return source;
}
else if (cosineOfSourceAngle <= cosineOfConeAngle)
return source;
// find the portion of "source" that is perpendicular to "basis"
Vector3 perp = PerpendicularComponent(source, basis);
if (perp == Vector3.Zero)
return Vector3.Zero;
// normalize that perpendicular
Vector3 unitPerp = Vector3.Normalize(perp);
// construct a new vector whose length equals the source vector,
// and lies on the intersection of a plane (formed the source and
// basis vectors) and a cone (whose axis is "basis" and whose
// angle corresponds to cosineOfConeAngle)
float perpDist = (float)Math.Sqrt(1 - (cosineOfConeAngle * cosineOfConeAngle));
Vector3 c0 = basis * cosineOfConeAngle;
Vector3 c1 = unitPerp * perpDist;
return (c0 + c1) * sourceLength;
}
/// <summary>
/// Returns the distance between a point and a line.
/// </summary>
/// <param name="point">The point to measure distance to</param>
/// <param name="lineOrigin">A point on the line</param>
/// <param name="lineUnitTangent">A UNIT vector parallel to the line</param>
/// <returns></returns>
public static float DistanceFromLine(this Vector3 point, Vector3 lineOrigin, Vector3 lineUnitTangent)
{
Vector3 offset = point - lineOrigin;
Vector3 perp = PerpendicularComponent(offset, lineUnitTangent);
return perp.Length();
}
/// <summary>
/// Find any arbitrary vector which is perpendicular to the given vector
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public static Vector3 FindPerpendicularIn3d(this Vector3 direction)
{
// to be filled in:
Vector3 quasiPerp; // a direction which is "almost perpendicular"
Vector3 result; // the computed perpendicular to be returned
// three mutually perpendicular basis vectors
Vector3 i = Vector3.UnitX;
Vector3 j = Vector3.UnitY;
Vector3 k = Vector3.UnitZ;
// measure the projection of "direction" onto each of the axes
float id = Vector3.Dot(i, direction);
float jd = Vector3.Dot(j, direction);
float kd = Vector3.Dot(k, direction);
// set quasiPerp to the basis which is least parallel to "direction"
if ((id <= jd) && (id <= kd))
quasiPerp = i; // projection onto i was the smallest
else if ((jd <= id) && (jd <= kd))
quasiPerp = j; // projection onto j was the smallest
else
quasiPerp = k; // projection onto k was the smallest
// return the cross product (direction x quasiPerp)
// which is guaranteed to be perpendicular to both of them
result = Vector3.Cross(direction, quasiPerp);
return result;
}
}
}
| |
namespace AngleSharp.Dom
{
using AngleSharp.Attributes;
using AngleSharp.Css;
using AngleSharp.Css.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// A set of useful extension methods for the Element class.
/// </summary>
[DomExposed("Element")]
public static class ElementExtensions
{
/// <summary>
/// Creates a pseudo element for the current element.
/// </summary>
/// <param name="element">The element to extend.</param>
/// <param name="pseudoElement">
/// The element to create (e.g. ::after).
/// </param>
/// <returns>The created element or null, if not possible.</returns>
[DomName("pseudo")]
public static IPseudoElement Pseudo(this IElement element, String pseudoElement)
{
var factory = element.Owner?.Context.GetService<IPseudoElementFactory>();
return factory?.Create(element, pseudoElement);
}
/// <summary>
/// Gets the innerText of an element.
/// </summary>
/// <param name="element">The element to extend.</param>
/// <returns>The computed inner text.</returns>
[DomName("innerText")]
[DomAccessor(Accessors.Getter)]
public static String GetInnerText(this IElement element)
{
var hidden = new Nullable<Boolean>();
if (element.Owner == null)
{
hidden = true;
}
if (!hidden.HasValue)
{
var css = element.ComputeCurrentStyle();
if (!String.IsNullOrEmpty(css?.GetDisplay()))
{
hidden = css.GetDisplay() == CssKeywords.None;
}
}
if (!hidden.HasValue)
{
hidden = (element as IHtmlElement)?.IsHidden;
}
if (!hidden.Value)
{
var offset = 0;
var sb = StringBuilderPool.Obtain();
var requiredLineBreakCounts = new Dictionary<Int32, Int32>();
InnerTextCollection(element, sb, requiredLineBreakCounts, element.ParentElement?.ComputeCurrentStyle());
// Remove any runs of consecutive required line break count items at the start or end of results.
requiredLineBreakCounts.Remove(0);
requiredLineBreakCounts.Remove(sb.Length);
// SortedDictionary would be nicer
foreach (var keyval in requiredLineBreakCounts.OrderBy(kv => kv.Key))
{
var index = keyval.Key + offset;
sb.Insert(index, new String(Symbols.LineFeed, keyval.Value));
offset += keyval.Value;
}
return sb.ToPool();
}
return element.TextContent;
}
/// <summary>
/// Sets the innerText of an element.
/// </summary>
/// <param name="element">The element to extend.</param>
/// <param name="value">The inner text to set.</param>
[DomName("innerText")]
[DomAccessor(Accessors.Setter)]
public static void SetInnerText(this IElement element, String value)
{
if (String.IsNullOrEmpty(value))
{
element.TextContent = String.Empty;
}
else
{
var document = element.Owner;
var fragment = document.CreateDocumentFragment();
var sb = StringBuilderPool.Obtain();
for (var i = 0; i < value.Length; i++)
{
var c = value[i];
if (c == Symbols.LineFeed || c == Symbols.CarriageReturn)
{
if (c == Symbols.CarriageReturn && i + 1 < value.Length && value[i + 1] == Symbols.LineFeed)
{
// ignore carriage return if the next char is a line feed
continue;
}
if (sb.Length > 0)
{
fragment.AppendChild(document.CreateTextNode(sb.ToString()));
sb.Clear();
}
fragment.AppendChild(document.CreateElement(TagNames.Br));
}
else
{
sb.Append(c);
}
}
var remaining = sb.ToPool();
if (remaining.Length > 0)
{
fragment.AppendChild(document.CreateTextNode(remaining));
}
while (element.HasChildNodes)
{
element.RemoveChild(element.FirstChild);
}
element.AppendChild(fragment);
}
}
private static void InnerTextCollection(INode node, StringBuilder sb, Dictionary<Int32, Int32> requiredLineBreakCounts, ICssStyleDeclaration parentStyle)
{
if (HasCssBox(node))
{
var element = node as IElement;
var elementCss = element?.ComputeCurrentStyle();
ItcInCssBox(elementCss, parentStyle, node, sb, requiredLineBreakCounts);
}
}
private static void ItcInCssBox(ICssStyleDeclaration elementStyle, ICssStyleDeclaration parentStyle, INode node, StringBuilder sb, Dictionary<Int32, Int32> requiredLineBreakCounts)
{
var elementHidden = new Nullable<Boolean>();
if (elementStyle != null)
{
if (!String.IsNullOrEmpty(elementStyle.GetDisplay()))
{
elementHidden = elementStyle.GetDisplay() == CssKeywords.None;
}
if (!String.IsNullOrEmpty(elementStyle.GetVisibility()) && elementHidden != true)
{
elementHidden = elementStyle.GetVisibility() != CssKeywords.Visible;
}
}
if (!elementHidden.HasValue)
{
elementHidden = (node as IHtmlElement)?.IsHidden ?? false;
}
if (!elementHidden.Value)
{
var isBlockLevel = new Nullable<Boolean>();
var startIndex = sb.Length;
foreach (var child in node.ChildNodes)
{
InnerTextCollection(child, sb, requiredLineBreakCounts, elementStyle);
}
if (node is IText textElement)
{
var lastLine = node.NextSibling is null ||
String.IsNullOrEmpty(node.NextSibling.TextContent) ||
node.NextSibling is IHtmlBreakRowElement;
ProcessText(textElement.Data, sb, parentStyle, lastLine);
}
else if (node is IHtmlBreakRowElement)
{
sb.Append(Symbols.LineFeed);
}
else if (elementStyle != null && ((node is IHtmlTableCellElement && String.IsNullOrEmpty(elementStyle.GetDisplay())) || elementStyle.GetDisplay() == CssKeywords.TableCell))
{
if (node.NextSibling is IElement nextSibling)
{
var nextSiblingCss = nextSibling.ComputeCurrentStyle();
if (nextSibling is IHtmlTableCellElement && String.IsNullOrEmpty(nextSiblingCss.GetDisplay()) || nextSiblingCss.GetDisplay() == CssKeywords.TableCell)
{
sb.Append(Symbols.Tab);
}
}
}
else if (elementStyle != null && ((node is IHtmlTableRowElement && String.IsNullOrEmpty(elementStyle.GetDisplay())) || elementStyle.GetDisplay() == CssKeywords.TableRow))
{
if (node.NextSibling is IElement nextSibling)
{
var nextSiblingCss = nextSibling.ComputeCurrentStyle();
if (nextSibling is IHtmlTableRowElement && String.IsNullOrEmpty(nextSiblingCss.GetDisplay()) || nextSiblingCss.GetDisplay() == CssKeywords.TableRow)
{
sb.Append(Symbols.LineFeed);
}
}
}
else if (node is IHtmlParagraphElement)
{
requiredLineBreakCounts.TryGetValue(startIndex, out var startIndexCount);
if (startIndexCount < 2)
{
requiredLineBreakCounts[startIndex] = 2;
}
requiredLineBreakCounts.TryGetValue(sb.Length, out var endIndexCount);
if (endIndexCount < 2)
{
requiredLineBreakCounts[sb.Length] = 2;
}
}
if (elementStyle != null)
{
if (IsBlockLevelDisplay(elementStyle.GetDisplay()))
{
isBlockLevel = true;
}
}
if (!isBlockLevel.HasValue)
{
isBlockLevel = IsBlockLevel(node);
}
if (isBlockLevel.Value)
{
requiredLineBreakCounts.TryGetValue(startIndex, out var startIndexCount);
if (startIndexCount < 1)
{
requiredLineBreakCounts[startIndex] = 1;
}
requiredLineBreakCounts.TryGetValue(sb.Length, out var endIndexCount);
if (endIndexCount < 1)
{
requiredLineBreakCounts[sb.Length] = 1;
}
}
}
}
/// <summary>
/// Sets the style on all elements of the collection.
/// </summary>
/// <typeparam name="TElement">The type of elements.</typeparam>
/// <param name="elements">The collection to go over.</param>
/// <param name="change">The action to trigger for each element style.</param>
/// <returns>The collection for chaining.</returns>
public static IEnumerable<TElement> SetStyle<TElement>(this IEnumerable<TElement> elements, Action<ICssStyleDeclaration> change)
where TElement : IElement
{
change = change ?? throw new ArgumentNullException(nameof(change));
foreach (var element in elements)
{
change.Invoke(element.GetStyle());
}
return elements;
}
private static Boolean HasCssBox(INode node)
{
switch (node.NodeName)
{
case "CANVAS":
case "COL":
case "COLGROUP":
case "DETAILS":
case "FRAME":
case "FRAMESET":
case "IFRAME":
case "IMG":
case "INPUT":
case "LINK":
case "METER":
case "PROGRESS":
case "TEMPLATE":
case "TEXTAREA":
case "VIDEO":
case "WBR":
case "SCRIPT":
case "STYLE":
case "NOSCRIPT":
return false;
default:
return true;
}
}
private static Boolean IsBlockLevelDisplay(String display)
{
// https://www.w3.org/TR/css-display-3/#display-value-summary
// https://hg.mozilla.org/mozilla-central/file/0acceb224b7d/servo/components/layout/query.rs#l1016
switch (display)
{
case "block":
case "flow-root":
case "flex":
case "grid":
case "table":
case "table-caption":
return true;
default:
return false;
}
}
private static Boolean IsBlockLevel(INode node)
{
// https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
switch (node.NodeName)
{
case "ADDRESS":
case "ARTICLE":
case "ASIDE":
case "BLOCKQUOTE":
case "CANVAS":
case "DD":
case "DIV":
case "DL":
case "DT":
case "FIELDSET":
case "FIGCAPTION":
case "FIGURE":
case "FOOTER":
case "FORM":
case "H1":
case "H2":
case "H3":
case "H4":
case "H5":
case "H6":
case "HEADER":
case "GROUP":
case "HR":
case "LI":
case "MAIN":
case "NAV":
case "NOSCRIPT":
case "OL":
case "OPTION":
case "OUTPUT":
case "P":
case "PRE":
case "SECTION":
case "TABLE":
case "TFOOT":
case "UL":
case "VIDEO":
return true;
default:
return false;
}
}
private static void ProcessText(String text, StringBuilder sb, ICssStyleDeclaration style, Boolean lastLine)
{
var startIndex = sb.Length;
var whiteSpace = style?.GetWhiteSpace();
var textTransform = style?.GetTextTransform();
var isWhiteSpace = startIndex > 0 ? Char.IsWhiteSpace(sb[startIndex - 1]) && sb[startIndex - 1] != Symbols.NoBreakSpace : true;
for (var i = 0; i < text.Length; i++)
{
var c = text[i];
if (Char.IsWhiteSpace(c) && c != Symbols.NoBreakSpace)
{
// https://drafts.csswg.org/css-text/#white-space-property
switch (whiteSpace)
{
case "pre":
case "pre-wrap":
break;
case "pre-line":
if (c == Symbols.Space || c == Symbols.Tab)
{
if (isWhiteSpace)
{
continue;
}
c = Symbols.Space;
}
break;
case "nowrap":
case "normal":
default:
if (isWhiteSpace)
{
continue;
}
c = Symbols.Space;
break;
}
isWhiteSpace = true;
}
else
{
// https://drafts.csswg.org/css-text/#propdef-text-transform
switch (textTransform)
{
case "uppercase":
c = Char.ToUpperInvariant(c);
break;
case "lowercase":
c = Char.ToLowerInvariant(c);
break;
case "capitalize":
if (isWhiteSpace)
{
c = Char.ToUpperInvariant(c);
}
break;
case "none":
default:
break;
}
isWhiteSpace = false;
}
sb.Append(c);
}
// ended with whitespace
if (isWhiteSpace && lastLine)
{
for (var offset = sb.Length - 1; offset >= startIndex; offset--)
{
var c = sb[offset];
if (!Char.IsWhiteSpace(c) || c == Symbols.NoBreakSpace)
{
sb.Remove(offset + 1, sb.Length - 1 - offset);
break;
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.CognitiveServices.Vision.Face
{
using Microsoft.CognitiveServices;
using Microsoft.CognitiveServices.Vision;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for FaceList.
/// </summary>
public static partial class FaceListExtensions
{
/// <summary>
/// Create an empty face list. Up to 64 face lists are allowed to exist in one
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a particular face list.
/// </param>
/// <param name='name'>
/// Name of the face list, maximum length is 128.
/// </param>
/// <param name='userData'>
/// Optional user defined data for the face list. Length should not exceed
/// 16KB.
/// </param>
public static void Create(this IFaceList operations, string faceListId, string name = default(string), string userData = default(string))
{
operations.CreateAsync(faceListId, name, userData).GetAwaiter().GetResult();
}
/// <summary>
/// Create an empty face list. Up to 64 face lists are allowed to exist in one
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a particular face list.
/// </param>
/// <param name='name'>
/// Name of the face list, maximum length is 128.
/// </param>
/// <param name='userData'>
/// Optional user defined data for the face list. Length should not exceed
/// 16KB.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateAsync(this IFaceList operations, string faceListId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateWithHttpMessagesAsync(faceListId, name, userData, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieve a face list's information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
public static GetFaceListResult Get(this IFaceList operations, string faceListId)
{
return operations.GetAsync(faceListId).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a face list's information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GetFaceListResult> GetAsync(this IFaceList operations, string faceListId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(faceListId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update information of a face list.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='name'>
/// Name of the face list, maximum length is 128.
/// </param>
/// <param name='userData'>
/// Optional user defined data for the face list. Length should not exceed
/// 16KB.
/// </param>
public static void Update(this IFaceList operations, string faceListId, string name = default(string), string userData = default(string))
{
operations.UpdateAsync(faceListId, name, userData).GetAwaiter().GetResult();
}
/// <summary>
/// Update information of a face list.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='name'>
/// Name of the face list, maximum length is 128.
/// </param>
/// <param name='userData'>
/// Optional user defined data for the face list. Length should not exceed
/// 16KB.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateAsync(this IFaceList operations, string faceListId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateWithHttpMessagesAsync(faceListId, name, userData, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Delete an existing face list according to faceListId. Persisted face images
/// in the face list will also be deleted.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
public static void Delete(this IFaceList operations, string faceListId)
{
operations.DeleteAsync(faceListId).GetAwaiter().GetResult();
}
/// <summary>
/// Delete an existing face list according to faceListId. Persisted face images
/// in the face list will also be deleted.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IFaceList operations, string faceListId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(faceListId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieve information about all existing face lists. Only faceListId, name
/// and userData will be returned.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IList<GetFaceListResult> List(this IFaceList operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve information about all existing face lists. Only faceListId, name
/// and userData will be returned.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<GetFaceListResult>> ListAsync(this IFaceList operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete an existing face from a face list (given by a persisitedFaceId and a
/// faceListId). Persisted image related to the face will also be deleted.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// faceListId of an existing face list.
/// </param>
/// <param name='persistedFaceId'>
/// persistedFaceId of an existing face.
/// </param>
public static void DeleteFace(this IFaceList operations, string faceListId, string persistedFaceId)
{
operations.DeleteFaceAsync(faceListId, persistedFaceId).GetAwaiter().GetResult();
}
/// <summary>
/// Delete an existing face from a face list (given by a persisitedFaceId and a
/// faceListId). Persisted image related to the face will also be deleted.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// faceListId of an existing face list.
/// </param>
/// <param name='persistedFaceId'>
/// persistedFaceId of an existing face.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteFaceAsync(this IFaceList operations, string faceListId, string persistedFaceId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteFaceWithHttpMessagesAsync(faceListId, persistedFaceId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Add a face to a face list. The input face is specified as an image with a
/// targetFace rectangle. It returns a persistedFaceId representing the added
/// face, and persistedFaceId will not expire.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='userData'>
/// User-specified data about the face list for any purpose. The maximum
/// length is 1KB.
/// </param>
/// <param name='targetFace'>
/// A face rectangle to specify the target face to be added into the face list,
/// in the format of "targetFace=left,top,width,height". E.g.
/// "targetFace=10,10,100,100". If there is more than one face in the image,
/// targetFace is required to specify which face to add. No targetFace means
/// there is only one face detected in the entire image.
/// </param>
public static void AddFace(this IFaceList operations, string faceListId, string userData = default(string), string targetFace = default(string))
{
operations.AddFaceAsync(faceListId, userData, targetFace).GetAwaiter().GetResult();
}
/// <summary>
/// Add a face to a face list. The input face is specified as an image with a
/// targetFace rectangle. It returns a persistedFaceId representing the added
/// face, and persistedFaceId will not expire.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='userData'>
/// User-specified data about the face list for any purpose. The maximum
/// length is 1KB.
/// </param>
/// <param name='targetFace'>
/// A face rectangle to specify the target face to be added into the face list,
/// in the format of "targetFace=left,top,width,height". E.g.
/// "targetFace=10,10,100,100". If there is more than one face in the image,
/// targetFace is required to specify which face to add. No targetFace means
/// there is only one face detected in the entire image.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task AddFaceAsync(this IFaceList operations, string faceListId, string userData = default(string), string targetFace = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.AddFaceWithHttpMessagesAsync(faceListId, userData, targetFace, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Add a face to a face list. The input face is specified as an image with a
/// targetFace rectangle. It returns a persistedFaceId representing the added
/// face, and persistedFaceId will not expire.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='userData'>
/// User-specified data about the face list for any purpose. The maximum
/// length is 1KB.
/// </param>
/// <param name='targetFace'>
/// A face rectangle to specify the target face to be added into the face list,
/// in the format of "targetFace=left,top,width,height". E.g.
/// "targetFace=10,10,100,100". If there is more than one face in the image,
/// targetFace is required to specify which face to add. No targetFace means
/// there is only one face detected in the entire image.
/// </param>
public static void AddFaceFromStream(this IFaceList operations, string faceListId, string userData = default(string), string targetFace = default(string))
{
operations.AddFaceFromStreamAsync(faceListId, userData, targetFace).GetAwaiter().GetResult();
}
/// <summary>
/// Add a face to a face list. The input face is specified as an image with a
/// targetFace rectangle. It returns a persistedFaceId representing the added
/// face, and persistedFaceId will not expire.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='userData'>
/// User-specified data about the face list for any purpose. The maximum
/// length is 1KB.
/// </param>
/// <param name='targetFace'>
/// A face rectangle to specify the target face to be added into the face list,
/// in the format of "targetFace=left,top,width,height". E.g.
/// "targetFace=10,10,100,100". If there is more than one face in the image,
/// targetFace is required to specify which face to add. No targetFace means
/// there is only one face detected in the entire image.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task AddFaceFromStreamAsync(this IFaceList operations, string faceListId, string userData = default(string), string targetFace = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.AddFaceFromStreamWithHttpMessagesAsync(faceListId, userData, targetFace, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| |
/*
* 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.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests the mapping of the ETF symbol that has a constituent universe attached to it and ensures
/// that data is loaded after the mapping event takes place.
/// </summary>
public class ETFConstituentUniverseMappedCompositeRegressionAlgorithm: QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _aapl;
private Symbol _qqq;
private Dictionary<DateTime, int> _filterDateConstituentSymbolCount = new Dictionary<DateTime, int>();
private Dictionary<DateTime, bool> _constituentDataEncountered = new Dictionary<DateTime, bool>();
private HashSet<Symbol> _constituentSymbols = new HashSet<Symbol>();
private bool _mappingEventOccurred;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2011, 2, 1);
SetEndDate(2011, 4, 4);
SetCash(100000);
UniverseSettings.Resolution = Resolution.Hour;
_aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
_qqq = AddEquity("QQQ", Resolution.Daily).Symbol;
AddUniverse(Universe.ETF(_qqq, universeFilterFunc: FilterETFs));
}
private IEnumerable<Symbol> FilterETFs(IEnumerable<ETFConstituentData> constituents)
{
var constituentSymbols = constituents.Select(x => x.Symbol).ToHashSet();
if (!constituentSymbols.Contains(_aapl))
{
throw new Exception("AAPL not found in QQQ constituents");
}
_filterDateConstituentSymbolCount[UtcTime.Date] = constituentSymbols.Count;
foreach (var symbol in constituentSymbols)
{
_constituentSymbols.Add(symbol);
}
return constituentSymbols;
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (data.SymbolChangedEvents.Count != 0)
{
foreach (var symbolChanged in data.SymbolChangedEvents.Values)
{
if (symbolChanged.Symbol != _qqq)
{
throw new Exception($"Mapped symbol is not QQQ. Instead, found: {symbolChanged.Symbol}");
}
if (symbolChanged.OldSymbol != "QQQQ")
{
throw new Exception($"Old QQQ Symbol is not QQQQ. Instead, found: {symbolChanged.OldSymbol}");
}
if (symbolChanged.NewSymbol != "QQQ")
{
throw new Exception($"New QQQ Symbol is not QQQ. Instead, found: {symbolChanged.NewSymbol}");
}
_mappingEventOccurred = true;
}
}
if (data.Keys.Count == 1 && data.ContainsKey(_qqq))
{
return;
}
if (!_constituentDataEncountered.ContainsKey(UtcTime.Date))
{
_constituentDataEncountered[UtcTime.Date] = false;
}
if (_constituentSymbols.Intersect(data.Keys).Any())
{
_constituentDataEncountered[UtcTime.Date] = true;
}
if (!Portfolio.Invested)
{
SetHoldings(_aapl, 0.5m);
}
}
public override void OnEndOfAlgorithm()
{
if (_filterDateConstituentSymbolCount.Count != 2)
{
throw new Exception($"ETF constituent filtering function was not called 2 times (actual: {_filterDateConstituentSymbolCount.Count}");
}
if (!_mappingEventOccurred)
{
throw new Exception("No mapping/SymbolChangedEvent occurred. Expected for QQQ to be mapped from QQQQ -> QQQ");
}
foreach (var kvp in _filterDateConstituentSymbolCount)
{
if (kvp.Value < 25)
{
throw new Exception($"Expected 25 or more constituents in filter function on {kvp.Key:yyyy-MM-dd HH:mm:ss.fff}, found {kvp.Value}");
}
}
foreach (var kvp in _constituentDataEncountered)
{
if (!kvp.Value)
{
throw new Exception($"Received data in OnData(...) but it did not contain any constituent data on {kvp.Key:yyyy-MM-dd HH:mm:ss.fff}");
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-9.690%"},
{"Drawdown", "4.200%"},
{"Expectancy", "0"},
{"Net Profit", "-1.743%"},
{"Sharpe Ratio", "-0.977"},
{"Probabilistic Sharpe Ratio", "18.957%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.154"},
{"Beta", "0.446"},
{"Annual Standard Deviation", "0.09"},
{"Annual Variance", "0.008"},
{"Information Ratio", "-2.349"},
{"Tracking Error", "0.1"},
{"Treynor Ratio", "-0.198"},
{"Total Fees", "$22.93"},
{"Estimated Strategy Capacity", "$75000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-1.691"},
{"Return Over Maximum Drawdown", "-2.806"},
{"Portfolio Turnover", "0.01"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "50e968429008fb1c39fd577f5ebe74cf"}
};
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
/// <summary>
/// Extension of GraphicRaycaster to support ray casting with world space rays instead of just screen-space
/// pointer positions
/// </summary>
[RequireComponent(typeof(Canvas))]
public class OVRRaycaster : GraphicRaycaster, IPointerEnterHandler
{
[Tooltip("A world space pointer for this canvas")]
public GameObject pointer;
public int sortOrder = 0;
protected OVRRaycaster()
{ }
[NonSerialized]
private Canvas m_Canvas;
private Canvas canvas
{
get
{
if (m_Canvas != null)
return m_Canvas;
m_Canvas = GetComponent<Canvas>();
return m_Canvas;
}
}
public override Camera eventCamera
{
get
{
return canvas.worldCamera;
}
}
public override int sortOrderPriority
{
get
{
return sortOrder;
}
}
/// <summary>
/// For the given ray, find graphics on this canvas which it intersects and are not blocked by other
/// world objects
/// </summary>
[NonSerialized]
private List<RaycastHit> m_RaycastResults = new List<RaycastHit>();
private void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList, Ray ray, bool checkForBlocking)
{
//This function is closely based on
//void GraphicRaycaster.Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
if (canvas == null)
return;
float hitDistance = float.MaxValue;
if (checkForBlocking && blockingObjects != BlockingObjects.None)
{
float dist = eventCamera.farClipPlane;
if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All)
{
var hits = Physics.RaycastAll(ray, dist, m_BlockingMask);
if (hits.Length > 0 && hits[0].distance < hitDistance)
{
hitDistance = hits[0].distance;
}
}
if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All)
{
var hits = Physics2D.GetRayIntersectionAll(ray, dist, m_BlockingMask);
if (hits.Length > 0 && hits[0].fraction * dist < hitDistance)
{
hitDistance = hits[0].fraction * dist;
}
}
}
m_RaycastResults.Clear();
GraphicRaycast(canvas, ray, m_RaycastResults);
for (var index = 0; index < m_RaycastResults.Count; index++)
{
var go = m_RaycastResults[index].graphic.gameObject;
bool appendGraphic = true;
if (ignoreReversedGraphics)
{
// If we have a camera compare the direction against the cameras forward.
var cameraFoward = ray.direction;
var dir = go.transform.rotation * Vector3.forward;
appendGraphic = Vector3.Dot(cameraFoward, dir) > 0;
}
// Ignore points behind us (can happen with a canvas pointer)
if (eventCamera.transform.InverseTransformPoint(m_RaycastResults[index].worldPos).z <= 0)
{
appendGraphic = false;
}
if (appendGraphic)
{
float distance = Vector3.Distance(ray.origin, m_RaycastResults[index].worldPos);
if (distance >= hitDistance)
{
continue;
}
var castResult = new RaycastResult
{
gameObject = go,
module = this,
distance = distance,
index = resultAppendList.Count,
depth = m_RaycastResults[index].graphic.depth,
worldPosition = m_RaycastResults[index].worldPos
};
resultAppendList.Add(castResult);
}
}
}
/// <summary>
/// Performs a raycast using eventData.worldSpaceRay
/// </summary>
/// <param name="eventData"></param>
/// <param name="resultAppendList"></param>
public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
{
if (eventData.IsVRPointer())
{
Raycast(eventData, resultAppendList, eventData.GetRay(), true);
}
}
/// <summary>
/// Performs a raycast using the pointer object attached to this OVRRaycaster
/// </summary>
/// <param name="eventData"></param>
/// <param name="resultAppendList"></param>
public void RaycastPointer(PointerEventData eventData, List<RaycastResult> resultAppendList)
{
if (pointer != null && pointer.activeInHierarchy)
{
Raycast(eventData, resultAppendList, new Ray(eventCamera.transform.position, (pointer.transform.position - eventCamera.transform.position).normalized), false);
}
}
/// <summary>
/// Perform a raycast into the screen and collect all graphics underneath it.
/// </summary>
[NonSerialized]
static readonly List<RaycastHit> s_SortedGraphics = new List<RaycastHit>();
private void GraphicRaycast(Canvas canvas, Ray ray, List<RaycastHit> results)
{
//This function is based closely on :
// void GraphicRaycaster.Raycast(Canvas canvas, Camera eventCamera, Vector2 pointerPosition, List<Graphic> results)
// But modified to take a Ray instead of a canvas pointer, and also to explicitly ignore
// the graphic associated with the pointer
// Necessary for the event system
var foundGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas);
s_SortedGraphics.Clear();
for (int i = 0; i < foundGraphics.Count; ++i)
{
Graphic graphic = foundGraphics[i];
// -1 means it hasn't been processed by the canvas, which means it isn't actually drawn
if (graphic.depth == -1 || (pointer == graphic.gameObject))
continue;
Vector3 worldPos;
if (RayIntersectsRectTransform(graphic.rectTransform, ray, out worldPos))
{
//Work out where this is on the screen for compatibility with existing Unity UI code
Vector2 screenPos = eventCamera.WorldToScreenPoint(worldPos);
// mask/image intersection - See Unity docs on eventAlphaThreshold for when this does anything
if (graphic.Raycast(screenPos, eventCamera))
{
RaycastHit hit;
hit.graphic = graphic;
hit.worldPos = worldPos;
hit.fromMouse = false;
s_SortedGraphics.Add(hit);
}
}
}
s_SortedGraphics.Sort((g1, g2) => g2.graphic.depth.CompareTo(g1.graphic.depth));
for (int i = 0; i < s_SortedGraphics.Count; ++i)
{
results.Add(s_SortedGraphics[i]);
}
}
/// <summary>
/// Get screen position of worldPosition contained in this RaycastResult
/// </summary>
/// <param name="worldPosition"></param>
/// <returns></returns>
public Vector2 GetScreenPosition(RaycastResult raycastResult)
{
// In future versions of Uinty RaycastResult will contain screenPosition so this will not be necessary
return eventCamera.WorldToScreenPoint(raycastResult.worldPosition);
}
/// <summary>
/// Detects whether a ray intersects a RectTransform and if it does also
/// returns the world position of the intersection.
/// </summary>
/// <param name="rectTransform"></param>
/// <param name="ray"></param>
/// <param name="worldPos"></param>
/// <returns></returns>
static bool RayIntersectsRectTransform(RectTransform rectTransform, Ray ray, out Vector3 worldPos)
{
Vector3[] corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
Plane plane = new Plane(corners[0], corners[1], corners[2]);
float enter;
if (!plane.Raycast(ray, out enter))
{
worldPos = Vector3.zero;
return false;
}
Vector3 intersection = ray.GetPoint(enter);
Vector3 BottomEdge = corners[3] - corners[0];
Vector3 LeftEdge = corners[1] - corners[0];
float BottomDot = Vector3.Dot(intersection - corners[0], BottomEdge);
float LeftDot = Vector3.Dot(intersection - corners[0], LeftEdge);
if (BottomDot < BottomEdge.sqrMagnitude && // Can use sqrMag because BottomEdge is not normalized
LeftDot < LeftEdge.sqrMagnitude &&
BottomDot >= 0 &&
LeftDot >= 0)
{
worldPos = corners[0] + LeftDot * LeftEdge / LeftEdge.sqrMagnitude + BottomDot * BottomEdge / BottomEdge.sqrMagnitude;
return true;
}
else
{
worldPos = Vector3.zero;
return false;
}
}
struct RaycastHit
{
public Graphic graphic;
public Vector3 worldPos;
public bool fromMouse;
};
/// <summary>
/// Is this the currently focussed Raycaster according to the InputModule
/// </summary>
/// <returns></returns>
public bool IsFocussed()
{
OVRInputModule inputModule = EventSystem.current.currentInputModule as OVRInputModule;
return inputModule && inputModule.activeGraphicRaycaster == this;
}
public void OnPointerEnter(PointerEventData e)
{
if (e.IsVRPointer())
{
// Gaze has entered this canvas. We'll make it the active one so that canvas-mouse pointer can be used.
OVRInputModule inputModule = EventSystem.current.currentInputModule as OVRInputModule;
inputModule.activeGraphicRaycaster = this;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Threading;
using CoreAnimation;
using CoreGraphics;
using Foundation;
using Metal;
using OpenTK;
using UIKit;
namespace MetalTexturedQuad
{
public class Renderer
{
const float interfaceOrientationLandscapeAngle = 35.0f;
const float interfaceOrientationPortraitAngle = 50.0f;
const float prespectiveNear = 0.1f;
const float prespectiveFar = 100.0f;
const int maxInflightBuffers = 3;
nuint sampleCount;
IMTLDevice device;
MTLPixelFormat depthPixelFormat;
MTLPixelFormat stencilPixelFormat;
Quad mpQuad;
// Interface Orientation
UIInterfaceOrientation mnOrientation;
Semaphore inflightSemaphore;
// Renderer globals
IMTLCommandQueue commandQueue;
IMTLLibrary shaderLibrary;
IMTLDepthStencilState depthState;
// textured Quad
Texture mpInTexture;
IMTLRenderPipelineState pipelineState;
#pragma warning disable 649
// Dimensions
CGSize size;
#pragma warning restore 649
// Viewing matrix is derived from an eye point, a reference point
// indicating the center of the scene, and an up vector.
Matrix4 lookAt;
// Translate the object in (x,y,z) space.
Matrix4 translate;
// Quad transform buffers
Matrix4 transform;
IMTLBuffer transformBuffer;
public Renderer ()
{
// initialize properties
sampleCount = 1;
depthPixelFormat = MTLPixelFormat.Depth32Float;
stencilPixelFormat = MTLPixelFormat.Invalid;
// find a usable Device
device = MTLDevice.SystemDefault;
// create a new command queue
commandQueue = device.CreateCommandQueue ();
NSError error;
shaderLibrary = device.CreateLibrary ("default.metallib", out error);
// if the shader libary isnt loading, nothing good will happen
if (shaderLibrary == null)
throw new Exception ("ERROR: Couldnt create a default shader library");
inflightSemaphore = new Semaphore (maxInflightBuffers, maxInflightBuffers);
}
public void Encode (IMTLRenderCommandEncoder renderEncoder)
{
renderEncoder.PushDebugGroup ("encode quad");
renderEncoder.SetFrontFacingWinding (MTLWinding.CounterClockwise);
renderEncoder.SetDepthStencilState (depthState);
renderEncoder.SetRenderPipelineState (pipelineState);
renderEncoder.SetVertexBuffer (transformBuffer, 0, 2);
renderEncoder.SetFragmentTexture (mpInTexture.MetalTexture, 0);
// Encode quad vertex and texture coordinate buffers
mpQuad.Encode (renderEncoder);
// tell the render context we want to draw our primitives
renderEncoder.DrawPrimitives (MTLPrimitiveType.Triangle, 0, 6, 1);
renderEncoder.EndEncoding ();
renderEncoder.PopDebugGroup ();
}
public void Reshape (ImageView view)
{
// To correctly compute the aspect ration determine the device
// interface orientation.
UIInterfaceOrientation orientation = UIApplication.SharedApplication.StatusBarOrientation;
// Update the quad and linear _transformation matrices, if and
// only if, the device orientation is changed.
if (mnOrientation == orientation)
return;
float angleInDegrees = GetActualAngle (orientation, view.Layer.Bounds);
CreateMatrix (angleInDegrees);
UpdateBuffer ();
}
public void Render (ImageView view)
{
inflightSemaphore.WaitOne ();
IMTLCommandBuffer commandBuffer = commandQueue.CommandBuffer ();
// compute image processing on the (same) drawable texture
ICAMetalDrawable drawable = view.GetNextDrawable ();
// create a render command encoder so we can render into something
MTLRenderPassDescriptor renderPassDescriptor = view.GetRenderPassDescriptor (drawable);
if (renderPassDescriptor == null) {
inflightSemaphore.Release ();
return;
}
// Get a render encoder
IMTLRenderCommandEncoder renderEncoder = commandBuffer.CreateRenderCommandEncoder (renderPassDescriptor);
// render textured quad
Encode (renderEncoder);
commandBuffer.AddCompletedHandler ((IMTLCommandBuffer buffer) => {
inflightSemaphore.Release ();
drawable.Dispose ();
});
commandBuffer.PresentDrawable (drawable);
commandBuffer.Commit ();
}
public void Configure (ImageView renderView)
{
renderView.DepthPixelFormat = depthPixelFormat;
renderView.StencilPixelFormat = stencilPixelFormat;
renderView.SampleCount = sampleCount;
// we need to set the framebuffer only property of the layer to NO so we
// can perform compute on the drawable's texture
var metalLayer = (CAMetalLayer)renderView.Layer;
metalLayer.FramebufferOnly = false;
if (!PreparePipelineState ())
throw new ApplicationException ("ERROR: Failed creating a depth stencil state descriptor!");
if (!PrepareTexturedQuad ("Default", "jpg"))
throw new ApplicationException ("ERROR: Failed creating a textured quad!");
if (!PrepareDepthStencilState ())
throw new ApplicationException ("ERROR: Failed creating a depth stencil state!");
if (!PrepareTransformBuffer ())
throw new ApplicationException ("ERROR: Failed creating a transform buffer!");
// Default orientation is unknown
mnOrientation = UIInterfaceOrientation.Unknown;
// Create linear transformation matrices
PrepareTransforms ();
}
bool PreparePipelineState ()
{
// get the fragment function from the library
IMTLFunction fragmentProgram = shaderLibrary.CreateFunction ("texturedQuadFragment");
if (fragmentProgram == null)
Console.WriteLine ("ERROR: Couldn't load fragment function from default library");
// get the vertex function from the library
IMTLFunction vertexProgram = shaderLibrary.CreateFunction ("texturedQuadVertex");
if (vertexProgram == null)
Console.WriteLine ("ERROR: Couldn't load vertex function from default library");
// create a pipeline state for the quad
var quadPipelineStateDescriptor = new MTLRenderPipelineDescriptor {
DepthAttachmentPixelFormat = depthPixelFormat,
StencilAttachmentPixelFormat = MTLPixelFormat.Invalid,
SampleCount = sampleCount,
VertexFunction = vertexProgram,
FragmentFunction = fragmentProgram
};
quadPipelineStateDescriptor.ColorAttachments [0].PixelFormat = MTLPixelFormat.BGRA8Unorm;
NSError error;
pipelineState = device.CreateRenderPipelineState (quadPipelineStateDescriptor, out error);
if (pipelineState == null) {
Console.WriteLine ("ERROR: Failed acquiring pipeline state descriptor: %@", error.Description);
return false;
}
return true;
}
bool PrepareTexturedQuad (string texStr, string extStr)
{
mpInTexture = new Texture (texStr, extStr);
bool isAcquired = mpInTexture.Finalize (device);
mpInTexture.MetalTexture.Label = texStr;
if (!isAcquired) {
Console.WriteLine ("ERROR: Failed creating an input 2d texture!");
return false;
}
size.Width = mpInTexture.Width;
size.Height = mpInTexture.Height;
mpQuad = new Quad (device) {
Size = size
};
return true;
}
bool PrepareTransformBuffer ()
{
// allocate regions of memory for the constant buffer
transformBuffer = device.CreateBuffer ((nuint)Marshal.SizeOf<Matrix4> (), MTLResourceOptions.CpuCacheModeDefault);
if (transformBuffer == null)
return false;
transformBuffer.Label = "TransformBuffer";
return true;
}
bool PrepareDepthStencilState ()
{
var depthStateDesc = new MTLDepthStencilDescriptor {
DepthCompareFunction = MTLCompareFunction.Always,
DepthWriteEnabled = true
};
depthState = device.CreateDepthStencilState (depthStateDesc);
if (depthState == null)
return false;
return true;
}
void PrepareTransforms ()
{
// Create a viewing matrix derived from an eye point, a reference point
// indicating the center of the scene, and an up vector.
var eye = Vector3.Zero;
var center = new Vector3 (0f, 0f, 1f);
var up = new Vector3 (0f, 1f, 0f);
lookAt = MathUtils.LookAt (eye, center, up);
// Translate the object in (x,y,z) space.
translate = MathUtils.Translate (0.0f, -0.25f, 2.0f);
}
float GetActualAngle (UIInterfaceOrientation orientation, CGRect bounds)
{
// Update the device orientation
mnOrientation = orientation;
// Get the bounds for the current rendering layer
mpQuad.Bounds = bounds;
// Based on the device orientation, set the angle in degrees
// between a plane which passes through the camera position
// and the top of your screen and another plane which passes
// through the camera position and the bottom of your screen.
float dangle = 0.0f;
switch (mnOrientation) {
case UIInterfaceOrientation.LandscapeLeft:
case UIInterfaceOrientation.LandscapeRight:
dangle = interfaceOrientationLandscapeAngle;
break;
case UIInterfaceOrientation.Portrait:
case UIInterfaceOrientation.PortraitUpsideDown:
default:
dangle = interfaceOrientationPortraitAngle;
break;
}
return dangle;
}
void CreateMatrix (float angle)
{
// Describes a tranformation matrix that produces a perspective projection
float near = prespectiveNear;
float far = prespectiveFar;
float rangle = MathUtils.Radians (angle);
float length = near * (float)Math.Tan (rangle);
float right = length / (float)mpQuad.Aspect;
float left = -right;
float top = length;
float bottom = -top;
Matrix4 perspective = MathUtils.FrustrumOc (left, right, bottom, top, near, far);
// Create a viewing matrix derived from an eye point, a reference point
// indicating the center of the scene, and an up vector.
transform = (lookAt * translate).SwapColumnsAndRows ();
// Create a linear _transformation matrix
transform = (perspective * transform).SwapColumnsAndRows ();
}
void UpdateBuffer ()
{
// Update the buffer associated with the linear _transformation matrix
int rawsize = Marshal.SizeOf <Matrix4> ();
var rawdata = new byte[rawsize];
GCHandle pinnedTransform = GCHandle.Alloc (transform, GCHandleType.Pinned);
IntPtr ptr = pinnedTransform.AddrOfPinnedObject ();
Marshal.Copy (ptr, rawdata, 0, rawsize);
pinnedTransform.Free ();
Marshal.Copy (rawdata, 0, transformBuffer.Contents, rawsize);
}
}
}
| |
using UnityEngine;
using System.Collections;
namespace RootMotion.FinalIK {
/// <summary>
/// Foot placement system.
/// </summary>
[System.Serializable]
public partial class Grounding {
#region Main Interface
/// <summary>
/// The raycasting quality. Fastest is a single raycast per foot, Simple is three raycasts, Best is one raycast and a capsule cast per foot.
/// </summary>
[System.Serializable]
public enum Quality {
Fastest,
Simple,
Best
}
/// <summary>
/// Layers to ground the character to. Make sure to exclude the layer of the character controller.
/// </summary>
[Tooltip("Layers to ground the character to. Make sure to exclude the layer of the character controller.")]
public LayerMask layers;
/// <summary>
/// Max step height. Maximum vertical distance of Grounding from the root of the character.
/// </summary>
[Tooltip("Max step height. Maximum vertical distance of Grounding from the root of the character.")]
public float maxStep = 0.5f;
/// <summary>
/// The height offset of the root.
/// </summary>
[Tooltip("The height offset of the root.")]
public float heightOffset;
/// <summary>
/// The speed of moving the feet up/down.
/// </summary>
[Tooltip("The speed of moving the feet up/down.")]
public float footSpeed = 2.5f;
/// <summary>
/// CapsuleCast radius. Should match approximately with the size of the feet.
/// </summary>
[Tooltip("CapsuleCast radius. Should match approximately with the size of the feet.")]
public float footRadius = 0.15f;
/// <summary>
/// Amount of velocity based prediction of the foot positions.
/// </summary>
[Tooltip("Amount of velocity based prediction of the foot positions.")]
public float prediction = 0.05f;
/// <summary>
/// Weight of rotating the feet to the ground normal offset.
/// </summary>
[Tooltip("Weight of rotating the feet to the ground normal offset.")]
[Range(0f, 1f)]
public float footRotationWeight = 1f;
/// <summary>
/// Speed of slerping the feet to their grounded rotations.
/// </summary>
[Tooltip("Speed of slerping the feet to their grounded rotations.")]
public float footRotationSpeed = 7f;
/// <summary>
/// Max Foot Rotation Angle, Max angular offset from the foot's rotation (Reasonable range: 0-90 degrees).
/// </summary>
[Tooltip("Max Foot Rotation Angle. Max angular offset from the foot's rotation.")]
[Range(0f, 90f)]
public float maxFootRotationAngle = 45f;
/// <summary>
/// If true, solver will rotate with the character root so the character can be grounded for example to spherical planets.
/// For performance reasons leave this off unless needed.
/// </summary>
[Tooltip("If true, solver will rotate with the character root so the character can be grounded for example to spherical planets. For performance reasons leave this off unless needed.")]
public bool rotateSolver;
/// <summary>
/// The speed of moving the character up/down.
/// </summary>
[Tooltip("The speed of moving the character up/down.")]
public float pelvisSpeed = 5f;
/// <summary>
/// Used for smoothing out vertical pelvis movement (range 0 - 1).
/// </summary>
[Tooltip("Used for smoothing out vertical pelvis movement (range 0 - 1).")]
[Range(0f, 1f)]
public float pelvisDamper;
/// <summary>
/// The weight of lowering the pelvis to the lowest foot.
/// </summary>
[Tooltip("The weight of lowering the pelvis to the lowest foot.")]
public float lowerPelvisWeight = 1f;
/// <summary>
/// The weight of lifting the pelvis to the highest foot. This is useful when you don't want the feet to go too high relative to the body when crouching.
/// </summary>
[Tooltip("The weight of lifting the pelvis to the highest foot. This is useful when you don't want the feet to go too high relative to the body when crouching.")]
public float liftPelvisWeight;
/// <summary>
/// The radius of the spherecast from the root that determines whether the character root is grounded.
/// </summary>
[Tooltip("The radius of the spherecast from the root that determines whether the character root is grounded.")]
public float rootSphereCastRadius = 0.1f;
/// <summary>
/// The raycasting quality. Fastest is a single raycast per foot, Simple is three raycasts, Best is one raycast and a capsule cast per foot.
/// </summary>
[Tooltip("The raycasting quality. Fastest is a single raycast per foot, Simple is three raycasts, Best is one raycast and a capsule cast per foot.")]
public Quality quality = Quality.Best;
/// <summary>
/// The %Grounding legs.
/// </summary>
public Leg[] legs { get; private set; }
/// <summary>
/// The %Grounding pelvis.
/// </summary>
public Pelvis pelvis { get; private set; }
/// <summary>
/// Gets a value indicating whether any of the legs are grounded
/// </summary>
public bool isGrounded { get; private set; }
/// <summary>
/// The root Transform
/// </summary>
public Transform root { get; private set; }
/// <summary>
/// Ground height at the root position.
/// </summary>
public RaycastHit rootHit { get; private set; }
/// <summary>
/// Is the RaycastHit from the root grounded?
/// </summary>
public bool rootGrounded {
get {
return rootHit.distance < maxStep * 2f;
}
}
/// <summary>
/// Raycasts or sphereCasts to find the root ground point. Distance of the Ray/Sphere cast is maxDistanceMlp x maxStep. Use this instead of rootHit if the Grounder is weighed out/disabled and not updated.
/// </summary>
public RaycastHit GetRootHit(float maxDistanceMlp = 10f) {
RaycastHit h = new RaycastHit();
Vector3 _up = up;
Vector3 legsCenter = Vector3.zero;
foreach (Leg leg in legs) legsCenter += leg.transform.position;
legsCenter /= (float)legs.Length;
h.point = legsCenter - _up * maxStep * 10f;
float distMlp = maxDistanceMlp + 1;
h.distance = maxStep * distMlp;
if (maxStep <= 0f) return h;
if (quality != Quality.Best) Physics.Raycast(legsCenter + _up * maxStep, -_up, out h, maxStep * distMlp, layers);
else Physics.SphereCast(legsCenter + _up * maxStep, rootSphereCastRadius, -up, out h, maxStep * distMlp, layers);
return h;
}
/// <summary>
/// Gets a value indicating whether this <see cref="Grounding"/> is valid.
/// </summary>
public bool IsValid(ref string errorMessage) {
if (root == null) {
errorMessage = "Root transform is null. Can't initiate Grounding.";
return false;
}
if (legs == null) {
errorMessage = "Grounding legs is null. Can't initiate Grounding.";
return false;
}
if (pelvis == null) {
errorMessage = "Grounding pelvis is null. Can't initiate Grounding.";
return false;
}
if (legs.Length == 0) {
errorMessage = "Grounding has 0 legs. Can't initiate Grounding.";
return false;
}
return true;
}
/// <summary>
/// Initiate the %Grounding as an integrated solver by providing the root Transform, leg solvers, pelvis Transform and spine solver.
/// </summary>
public void Initiate(Transform root, Transform[] feet) {
this.root = root;
initiated = false;
rootHit = new RaycastHit();
// Constructing Legs
if (legs == null) legs = new Leg[feet.Length];
if (legs.Length != feet.Length) legs = new Leg[feet.Length];
for (int i = 0; i < feet.Length; i++) if (legs[i] == null) legs[i] = new Leg();
// Constructing pelvis
if (pelvis == null) pelvis = new Pelvis();
string errorMessage = string.Empty;
if (!IsValid(ref errorMessage)) {
Warning.Log(errorMessage, root, false);
return;
}
// Initiate solvers only if application is playing
if (Application.isPlaying) {
for (int i = 0; i < feet.Length; i++) legs[i].Initiate(this, feet[i]);
pelvis.Initiate(this);
initiated = true;
}
}
/// <summary>
/// Updates the Grounding.
/// </summary>
public void Update() {
if (!initiated) return;
if (layers == 0) LogWarning("Grounding layers are set to nothing. Please add a ground layer.");
maxStep = Mathf.Clamp(maxStep, 0f, maxStep);
footRadius = Mathf.Clamp(footRadius, 0.0001f, maxStep);
pelvisDamper = Mathf.Clamp(pelvisDamper, 0f, 1f);
rootSphereCastRadius = Mathf.Clamp(rootSphereCastRadius, 0.0001f, rootSphereCastRadius);
maxFootRotationAngle = Mathf.Clamp(maxFootRotationAngle, 0f, 90f);
prediction = Mathf.Clamp(prediction, 0f, prediction);
footSpeed = Mathf.Clamp(footSpeed, 0f, footSpeed);
// Root hit
rootHit = GetRootHit();
float lowestOffset = Mathf.NegativeInfinity;
float highestOffset = Mathf.Infinity;
isGrounded = false;
// Process legs
foreach (Leg leg in legs) {
leg.Process();
if (leg.IKOffset > lowestOffset) lowestOffset = leg.IKOffset;
if (leg.IKOffset < highestOffset) highestOffset = leg.IKOffset;
if (leg.isGrounded) isGrounded = true;
}
// Precess pelvis
pelvis.Process(-lowestOffset * lowerPelvisWeight, -highestOffset * liftPelvisWeight, isGrounded);
}
// Calculate the normal of the plane defined by leg positions, so we know how to rotate the body
public Vector3 GetLegsPlaneNormal() {
if (!initiated) return Vector3.up;
Vector3 _up = up;
Vector3 normal = _up;
// Go through all the legs, rotate the normal by it's offset
for (int i = 0; i < legs.Length; i++) {
// Direction from the root to the leg
Vector3 legDirection = legs[i].IKPosition - root.position;
// Find the tangent
Vector3 legNormal = _up;
Vector3 legTangent = legDirection;
Vector3.OrthoNormalize(ref legNormal, ref legTangent);
// Find the rotation offset from the tangent to the direction
Quaternion fromTo = Quaternion.FromToRotation(legTangent, legDirection);
// Rotate the normal
normal = fromTo * normal;
}
return normal;
}
// Set everything to 0
public void Reset() {
if (!Application.isPlaying) return;
pelvis.Reset();
foreach (Leg leg in legs) leg.Reset();
}
#endregion Main Interface
private bool initiated;
// Logs the warning if no other warning has beed logged in this session.
public void LogWarning(string message) {
Warning.Log(message, root);
}
// The up vector in solver rotation space.
public Vector3 up {
get {
return (useRootRotation? root.up: Vector3.up);
}
}
// Gets the vertical offset between two vectors in solver rotation space
public float GetVerticalOffset(Vector3 p1, Vector3 p2) {
if (useRootRotation) {
Vector3 v = Quaternion.Inverse(root.rotation) * (p1 - p2);
return v.y;
}
return p1.y - p2.y;
}
// Flattens a vector to ground plane in solver rotation space
public Vector3 Flatten(Vector3 v) {
if (useRootRotation) {
Vector3 tangent = v;
Vector3 normal = root.up;
Vector3.OrthoNormalize(ref normal, ref tangent);
return Vector3.Project(v, tangent);
}
v.y = 0;
return v;
}
// Determines whether to use root rotation as solver rotation
private bool useRootRotation {
get {
if (!rotateSolver) return false;
if (root.up == Vector3.up) return false;
return true;
}
}
}
}
| |
/*
* 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.Generic;
using System.Xml;
using System.Xml.Serialization;
using OpenMetaverse;
namespace OpenSim.Framework
{
public class LandAccessEntry
{
public UUID AgentID;
public int Expires;
public AccessList Flags;
}
/// <summary>
/// Details of a Parcel of land
/// </summary>
public class LandData
{
// use only one serializer to give the runtime a chance to
// optimize it (it won't do that if you use a new instance
// every time)
private static XmlSerializer serializer = new XmlSerializer(typeof(LandData));
private Vector3 _AABBMax = new Vector3();
private Vector3 _AABBMin = new Vector3();
private int _area = 0;
private uint _auctionID = 0; //Unemplemented. If set to 0, not being auctioned
private UUID _authBuyerID = UUID.Zero; //Unemplemented. Authorized Buyer's UUID
private ParcelCategory _category = ParcelCategory.None; //Unemplemented. Parcel's chosen category
private int _claimDate = 0;
private int _claimPrice = 0; //Unemplemented
private UUID _globalID = UUID.Zero;
private UUID _groupID = UUID.Zero;
private bool _isGroupOwned = false;
private byte[] _bitmap = new byte[512];
private string _description = String.Empty;
private uint _flags = (uint)ParcelFlags.AllowFly | (uint)ParcelFlags.AllowLandmark |
(uint)ParcelFlags.AllowAPrimitiveEntry |
(uint)ParcelFlags.AllowDeedToGroup |
(uint)ParcelFlags.CreateObjects | (uint)ParcelFlags.AllowOtherScripts |
(uint)ParcelFlags.AllowVoiceChat;
private byte _landingType = (byte)OpenMetaverse.LandingType.Direct;
private string _name = "Your Parcel";
private ParcelStatus _status = ParcelStatus.Leased;
private int _localID = 0;
private byte _mediaAutoScale = 0;
private UUID _mediaID = UUID.Zero;
private string _mediaURL = String.Empty;
private string _musicURL = String.Empty;
private UUID _ownerID = UUID.Zero;
private List<LandAccessEntry> _parcelAccessList = new List<LandAccessEntry>();
private float _passHours = 0;
private int _passPrice = 0;
private int _salePrice = 0; //Unemeplemented. Parcels price.
private int _simwideArea = 0;
private int _simwidePrims = 0;
private UUID _snapshotID = UUID.Zero;
private Vector3 _userLocation = new Vector3();
private Vector3 _userLookAt = new Vector3();
private int _otherCleanTime = 0;
private string _mediaType = "none/none";
private string _mediaDescription = "";
private int _mediaHeight = 0;
private int _mediaWidth = 0;
private bool _mediaLoop = false;
private bool _obscureMusic = false;
private bool _obscureMedia = false;
private float _dwell = 0;
public bool SeeAVs { get; set; }
public bool AnyAVSounds { get; set; }
public bool GroupAVSounds { get; set; }
/// <summary>
/// Traffic count of parcel
/// </summary>
[XmlIgnore]
public float Dwell
{
get
{
return _dwell;
}
set
{
_dwell = value;
}
}
/// <summary>
/// Whether to obscure parcel media URL
/// </summary>
[XmlIgnore]
public bool ObscureMedia
{
get
{
return _obscureMedia;
}
set
{
_obscureMedia = value;
}
}
/// <summary>
/// Whether to obscure parcel music URL
/// </summary>
[XmlIgnore]
public bool ObscureMusic
{
get
{
return _obscureMusic;
}
set
{
_obscureMusic = value;
}
}
/// <summary>
/// Whether to loop parcel media
/// </summary>
[XmlIgnore]
public bool MediaLoop
{
get
{
return _mediaLoop;
}
set
{
_mediaLoop = value;
}
}
/// <summary>
/// Height of parcel media render
/// </summary>
[XmlIgnore]
public int MediaHeight
{
get
{
return _mediaHeight;
}
set
{
_mediaHeight = value;
}
}
/// <summary>
/// Width of parcel media render
/// </summary>
[XmlIgnore]
public int MediaWidth
{
get
{
return _mediaWidth;
}
set
{
_mediaWidth = value;
}
}
/// <summary>
/// Upper corner of the AABB for the parcel
/// </summary>
[XmlIgnore]
public Vector3 AABBMax
{
get
{
return _AABBMax;
}
set
{
_AABBMax = value;
}
}
/// <summary>
/// Lower corner of the AABB for the parcel
/// </summary>
[XmlIgnore]
public Vector3 AABBMin
{
get
{
return _AABBMin;
}
set
{
_AABBMin = value;
}
}
/// <summary>
/// Area in meters^2 the parcel contains
/// </summary>
public int Area
{
get
{
return _area;
}
set
{
_area = value;
}
}
/// <summary>
/// ID of auction (3rd Party Integration) when parcel is being auctioned
/// </summary>
public uint AuctionID
{
get
{
return _auctionID;
}
set
{
_auctionID = value;
}
}
/// <summary>
/// UUID of authorized buyer of parcel. This is UUID.Zero if anyone can buy it.
/// </summary>
public UUID AuthBuyerID
{
get
{
return _authBuyerID;
}
set
{
_authBuyerID = value;
}
}
/// <summary>
/// Category of parcel. Used for classifying the parcel in classified listings
/// </summary>
public ParcelCategory Category
{
get
{
return _category;
}
set
{
_category = value;
}
}
/// <summary>
/// Date that the current owner purchased or claimed the parcel
/// </summary>
public int ClaimDate
{
get
{
return _claimDate;
}
set
{
_claimDate = value;
}
}
/// <summary>
/// The last price that the parcel was sold at
/// </summary>
public int ClaimPrice
{
get
{
return _claimPrice;
}
set
{
_claimPrice = value;
}
}
/// <summary>
/// Global ID for the parcel. (3rd Party Integration)
/// </summary>
public UUID GlobalID
{
get
{
return _globalID;
}
set
{
_globalID = value;
}
}
/// <summary>
/// Unique ID of the Group that owns
/// </summary>
public UUID GroupID
{
get
{
return _groupID;
}
set
{
_groupID = value;
}
}
/// <summary>
/// Returns true if the Land Parcel is owned by a group
/// </summary>
public bool IsGroupOwned
{
get
{
return _isGroupOwned;
}
set
{
_isGroupOwned = value;
}
}
/// <summary>
/// jp2 data for the image representative of the parcel in the parcel dialog
/// </summary>
public byte[] Bitmap
{
get
{
return _bitmap;
}
set
{
_bitmap = value;
}
}
/// <summary>
/// Parcel Description
/// </summary>
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
/// <summary>
/// Parcel settings. Access flags, Fly, NoPush, Voice, Scripts allowed, etc. ParcelFlags
/// </summary>
public uint Flags
{
get
{
return _flags;
}
set
{
_flags = value;
}
}
/// <summary>
/// Determines if people are able to teleport where they please on the parcel or if they
/// get constrainted to a specific point on teleport within the parcel
/// </summary>
public byte LandingType
{
get
{
return _landingType;
}
set
{
_landingType = value;
}
}
/// <summary>
/// Parcel Name
/// </summary>
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
/// <summary>
/// Status of Parcel, Leased, Abandoned, For Sale
/// </summary>
public ParcelStatus Status
{
get
{
return _status;
}
set
{
_status = value;
}
}
/// <summary>
/// Internal ID of the parcel. Sometimes the client will try to use this value
/// </summary>
public int LocalID
{
get
{
return _localID;
}
set
{
_localID = value;
}
}
/// <summary>
/// Determines if we scale the media based on the surface it's on
/// </summary>
public byte MediaAutoScale
{
get
{
return _mediaAutoScale;
}
set
{
_mediaAutoScale = value;
}
}
/// <summary>
/// Texture Guid to replace with the output of the media stream
/// </summary>
public UUID MediaID
{
get
{
return _mediaID;
}
set
{
_mediaID = value;
}
}
/// <summary>
/// URL to the media file to display
/// </summary>
public string MediaURL
{
get
{
return _mediaURL;
}
set
{
_mediaURL = value;
}
}
public string MediaType
{
get
{
return _mediaType;
}
set
{
_mediaType = value;
}
}
/// <summary>
/// URL to the shoutcast music stream to play on the parcel
/// </summary>
public string MusicURL
{
get
{
return _musicURL;
}
set
{
_musicURL = value;
}
}
/// <summary>
/// Owner Avatar or Group of the parcel. Naturally, all land masses must be
/// owned by someone
/// </summary>
public UUID OwnerID
{
get
{
return _ownerID;
}
set
{
_ownerID = value;
}
}
/// <summary>
/// List of access data for the parcel. User data, some bitflags, and a time
/// </summary>
public List<LandAccessEntry> ParcelAccessList
{
get
{
return _parcelAccessList;
}
set
{
_parcelAccessList = value;
}
}
/// <summary>
/// How long in hours a Pass to the parcel is given
/// </summary>
public float PassHours
{
get
{
return _passHours;
}
set
{
_passHours = value;
}
}
/// <summary>
/// Price to purchase a Pass to a restricted parcel
/// </summary>
public int PassPrice
{
get
{
return _passPrice;
}
set
{
_passPrice = value;
}
}
/// <summary>
/// When the parcel is being sold, this is the price to purchase the parcel
/// </summary>
public int SalePrice
{
get
{
return _salePrice;
}
set
{
_salePrice = value;
}
}
/// <summary>
/// Number of meters^2 that the land owner has in the Simulator
/// </summary>
[XmlIgnore]
public int SimwideArea
{
get
{
return _simwideArea;
}
set
{
_simwideArea = value;
}
}
/// <summary>
/// Number of SceneObjectPart in the Simulator
/// </summary>
[XmlIgnore]
public int SimwidePrims
{
get
{
return _simwidePrims;
}
set
{
_simwidePrims = value;
}
}
/// <summary>
/// ID of the snapshot used in the client parcel dialog of the parcel
/// </summary>
public UUID SnapshotID
{
get
{
return _snapshotID;
}
set
{
_snapshotID = value;
}
}
/// <summary>
/// When teleporting is restricted to a certain point, this is the location
/// that the user will be redirected to
/// </summary>
public Vector3 UserLocation
{
get
{
return _userLocation;
}
set
{
_userLocation = value;
}
}
/// <summary>
/// When teleporting is restricted to a certain point, this is the rotation
/// that the user will be positioned
/// </summary>
public Vector3 UserLookAt
{
get
{
return _userLookAt;
}
set
{
_userLookAt = value;
}
}
/// <summary>
/// Autoreturn number of minutes to return SceneObjectGroup that are owned by someone who doesn't own
/// the parcel and isn't set to the same 'group' as the parcel.
/// </summary>
public int OtherCleanTime
{
get
{
return _otherCleanTime;
}
set
{
_otherCleanTime = value;
}
}
/// <summary>
/// parcel media description
/// </summary>
public string MediaDescription
{
get
{
return _mediaDescription;
}
set
{
_mediaDescription = value;
}
}
public LandData()
{
_globalID = UUID.Random();
SeeAVs = true;
AnyAVSounds = true;
GroupAVSounds = true;
}
/// <summary>
/// Make a new copy of the land data
/// </summary>
/// <returns></returns>
public LandData Copy()
{
LandData landData = new LandData();
landData._AABBMax = _AABBMax;
landData._AABBMin = _AABBMin;
landData._area = _area;
landData._auctionID = _auctionID;
landData._authBuyerID = _authBuyerID;
landData._category = _category;
landData._claimDate = _claimDate;
landData._claimPrice = _claimPrice;
landData._globalID = _globalID;
landData._groupID = _groupID;
landData._isGroupOwned = _isGroupOwned;
landData._localID = _localID;
landData._landingType = _landingType;
landData._mediaAutoScale = _mediaAutoScale;
landData._mediaID = _mediaID;
landData._mediaURL = _mediaURL;
landData._musicURL = _musicURL;
landData._ownerID = _ownerID;
landData._bitmap = (byte[])_bitmap.Clone();
landData._description = _description;
landData._flags = _flags;
landData._name = _name;
landData._status = _status;
landData._passHours = _passHours;
landData._passPrice = _passPrice;
landData._salePrice = _salePrice;
landData._snapshotID = _snapshotID;
landData._userLocation = _userLocation;
landData._userLookAt = _userLookAt;
landData._otherCleanTime = _otherCleanTime;
landData._mediaType = _mediaType;
landData._mediaDescription = _mediaDescription;
landData._mediaWidth = _mediaWidth;
landData._mediaHeight = _mediaHeight;
landData._mediaLoop = _mediaLoop;
landData._obscureMusic = _obscureMusic;
landData._obscureMedia = _obscureMedia;
landData._simwideArea = _simwideArea;
landData._simwidePrims = _simwidePrims;
landData._dwell = _dwell;
landData.SeeAVs = SeeAVs;
landData.AnyAVSounds = AnyAVSounds;
landData.GroupAVSounds = GroupAVSounds;
landData._parcelAccessList.Clear();
foreach (LandAccessEntry entry in _parcelAccessList)
{
LandAccessEntry newEntry = new LandAccessEntry();
newEntry.AgentID = entry.AgentID;
newEntry.Flags = entry.Flags;
newEntry.Expires = entry.Expires;
landData._parcelAccessList.Add(newEntry);
}
return landData;
}
// public void ToXml(XmlWriter xmlWriter)
// {
// serializer.Serialize(xmlWriter, this);
// }
/// <summary>
/// Restore a LandData object from the serialized xml representation.
/// </summary>
/// <param name="xmlReader"></param>
/// <returns></returns>
// public static LandData FromXml(XmlReader xmlReader)
// {
// LandData land = (LandData)serializer.Deserialize(xmlReader);
//
// return land;
// }
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using FlubuCore.IO;
using FlubuCore.Tasks.FlubuWebApi;
namespace FlubuCore.Tasks.Solution.VSSolutionBrowsing
{
/// <summary>
/// Holds information about a VisualStudio project.
/// </summary>
public class VSProject : VSProjectInfo
{
public const string MSBuildNamespace = @"http://schemas.microsoft.com/developer/msbuild/2003";
public VSProject(
VSSolution ownerSolution,
Guid projectGuid,
string projectName,
LocalPath projectFileName,
Guid projectTypeGuid)
: base(ownerSolution, projectGuid, projectName, projectTypeGuid)
{
ProjectFileName = projectFileName;
}
/// <summary>
/// Gets or sets the <see cref="VSProjectDetails"/> object holding the detailed information about this VisualStudio
/// project.
/// </summary>
/// <value>The <see cref="VSProjectDetails"/> object .</value>
public VSProjectDetails ProjectDetails { get; set; }
/// <summary>
/// Gets the path to the directory where the project file is located.
/// </summary>
/// <value>The project directory path.</value>
public FullPath ProjectDirectoryPath => OwnerSolution.SolutionDirectoryPath.CombineWith(ProjectFileName).ParentPath;
/// <summary>
/// Gets the name of the project file. The file name is relative to the solution's directory.
/// </summary>
/// <remarks>The full path to the project file can be retrieved using the <see cref="ProjectFileNameFull"/>
/// property.</remarks>
/// <value>The name of the project file.</value>
public LocalPath ProjectFileName { get; }
/// <summary>
/// Gets the full path to the project file.
/// </summary>
/// <value>The full path to the project file.</value>
public FileFullPath ProjectFileNameFull => OwnerSolution.SolutionDirectoryPath.CombineWith(ProjectFileName).ToFileFullPath();
public string TargetFramework
{
get
{
if (ProjectDetails == null)
{
return null;
}
if (ProjectDetails.Properties.ContainsKey("TargetFramework"))
{
return ProjectDetails.Properties["TargetFramework"];
}
if (ProjectDetails.Properties.ContainsKey("TargetFrameworks"))
{
return ProjectDetails.Properties["TargetFrameworks"];
}
return null;
}
}
public string RuntimeIdentifier
{
get
{
if (ProjectDetails == null)
{
return null;
}
if (ProjectDetails.Properties.ContainsKey("RuntimeIdentifier"))
{
return ProjectDetails.Properties["RuntimeIdentifier"];
}
return null;
}
}
public string OutputType
{
get
{
if (ProjectDetails == null)
{
return null;
}
if (ProjectDetails.Properties.ContainsKey("OutputType"))
{
return ProjectDetails.Properties["OutputType"];
}
return null;
}
}
public string AssemblyName
{
get
{
if (ProjectDetails == null)
{
return null;
}
if (ProjectDetails.Properties.ContainsKey("AssemblyName"))
{
return ProjectDetails.Properties["AssemblyName"];
}
return null;
}
}
public string Version
{
get
{
if (ProjectDetails == null)
{
return null;
}
if (ProjectDetails.Properties.ContainsKey("Version"))
{
return ProjectDetails.Properties["Version"];
}
return null;
}
}
public string AssemblyVersion
{
get
{
if (ProjectDetails == null)
{
return null;
}
if (ProjectDetails.Properties.ContainsKey("AssemblyVersion"))
{
return ProjectDetails.Properties["AssemblyVersion"];
}
return null;
}
}
public string FileVersion
{
get
{
if (ProjectDetails == null)
{
return null;
}
if (ProjectDetails.Properties.ContainsKey("FileVersion"))
{
return ProjectDetails.Properties["FileVersion"];
}
return null;
}
}
/// <summary>
/// Gets the output path for a specified VisualStudio project. The output path is relative
/// to the directory where the project file is located.
/// </summary>
/// <param name="buildConfiguration">The build configuration.</param>
/// <returns>
/// The output path or <c>null</c> if the project is not compatible.
/// </returns>
/// <exception cref="ArgumentException">The method could not extract the data from the project file.</exception>
public LocalPath GetProjectOutputPath(string buildConfiguration)
{
// skip non-C# projects
if (ProjectTypeGuid != VSProjectType.CSharpProjectType.ProjectTypeGuid && ProjectTypeGuid != VSProjectType.NewCSharpProjectType.ProjectTypeGuid)
return null;
// find the project configuration
string condition = string.Format(
CultureInfo.InvariantCulture,
"'$(Configuration)|$(Platform)' == '{0}|AnyCPU'",
buildConfiguration);
VSProjectConfiguration projectConfiguration = ProjectDetails.FindConfiguration(condition);
if (projectConfiguration == null)
{
string message = string.Format(
CultureInfo.InvariantCulture,
"Could not find '{0}' configuration for the project '{1}'.",
condition,
ProjectName);
throw new ArgumentException(message);
}
if (projectConfiguration.Properties.ContainsKey("OutputPath") == false)
{
string message = string.Format(
CultureInfo.InvariantCulture,
"Missing OutputPath for the '{0}' configuration of the project '{1}'.",
buildConfiguration,
ProjectName);
throw new ArgumentException(message);
}
return new LocalPath(projectConfiguration.Properties["OutputPath"]);
}
public override void Parse(VSSolutionFileParser parser)
{
while (true)
{
string line = parser.NextLine();
if (line == null)
parser.ThrowParserException("Unexpected end of solution file.");
Match endProjectMatch = VSSolution.RegexEndProject.Match(line);
if (endProjectMatch.Success)
break;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Xml;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using System.Collections;
namespace System.Data.Common
{
internal sealed class SqlStringStorage : DataStorage
{
private SqlString[] _values;
public SqlStringStorage(DataColumn column)
: base(column, typeof(SqlString), SqlString.Null, SqlString.Null, StorageType.SqlString)
{
}
public override object Aggregate(int[] recordNos, AggregateType kind)
{
try
{
int i;
switch (kind)
{
case AggregateType.Min:
int min = -1;
for (i = 0; i < recordNos.Length; i++)
{
if (IsNull(recordNos[i]))
continue;
min = recordNos[i];
break;
}
if (min >= 0)
{
for (i = i + 1; i < recordNos.Length; i++)
{
if (IsNull(recordNos[i]))
continue;
if (Compare(min, recordNos[i]) > 0)
{
min = recordNos[i];
}
}
return Get(min);
}
return _nullValue;
case AggregateType.Max:
int max = -1;
for (i = 0; i < recordNos.Length; i++)
{
if (IsNull(recordNos[i]))
continue;
max = recordNos[i];
break;
}
if (max >= 0)
{
for (i = i + 1; i < recordNos.Length; i++)
{
if (Compare(max, recordNos[i]) < 0)
{
max = recordNos[i];
}
}
return Get(max);
}
return _nullValue;
case AggregateType.Count:
int count = 0;
for (i = 0; i < recordNos.Length; i++)
{
if (!IsNull(recordNos[i]))
count++;
}
return count;
}
}
catch (OverflowException)
{
throw ExprException.Overflow(typeof(SqlString));
}
throw ExceptionBuilder.AggregateException(kind, _dataType);
}
public override int Compare(int recordNo1, int recordNo2)
{
return Compare(_values[recordNo1], _values[recordNo2]);
}
public int Compare(SqlString valueNo1, SqlString valueNo2)
{
if (valueNo1.IsNull && valueNo2.IsNull)
return 0;
if (valueNo1.IsNull)
return -1;
if (valueNo2.IsNull)
return 1;
return _table.Compare(valueNo1.Value, valueNo2.Value);
}
public override int CompareValueTo(int recordNo, object value)
{
return Compare(_values[recordNo], (SqlString)value);
}
public override object ConvertValue(object value)
{
if (null != value)
{
return SqlConvert.ConvertToSqlString(value);
}
return _nullValue;
}
public override void Copy(int recordNo1, int recordNo2)
{
_values[recordNo2] = _values[recordNo1];
}
public override object Get(int record)
{
return _values[record];
}
public override int GetStringLength(int record)
{
SqlString value = _values[record];
return ((value.IsNull) ? 0 : value.Value.Length);
}
public override bool IsNull(int record)
{
return (_values[record].IsNull);
}
public override void Set(int record, object value)
{
_values[record] = SqlConvert.ConvertToSqlString(value);
}
public override void SetCapacity(int capacity)
{
SqlString[] newValues = new SqlString[capacity];
if (null != _values)
{
Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length));
}
_values = newValues;
}
public override object ConvertXmlToObject(string s)
{
SqlString newValue = new SqlString();
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
IXmlSerializable tmp = newValue;
using (XmlTextReader xmlTextReader = new XmlTextReader(strReader))
{
tmp.ReadXml(xmlTextReader);
}
return ((SqlString)tmp);
}
public override string ConvertObjectToXml(object value)
{
Debug.Assert(!DataStorage.IsObjectNull(value), "we shouldn't have null here");
Debug.Assert((value.GetType() == typeof(SqlString)), "wrong input type");
StringWriter strwriter = new StringWriter(FormatProvider); // consider passing cultureinfo with CultureInfo.InvariantCulture
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(strwriter))
{
((IXmlSerializable)value).WriteXml(xmlTextWriter);
}
return (strwriter.ToString());
}
protected override object GetEmptyStorage(int recordCount)
{
return new SqlString[recordCount];
}
protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex)
{
SqlString[] typedStore = (SqlString[])store;
typedStore[storeIndex] = _values[record];
nullbits.Set(storeIndex, IsNull(record));
}
protected override void SetStorage(object store, BitArray nullbits)
{
_values = (SqlString[])store;
//SetNullStorage(nullbits);
}
}
}
| |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using XenAPI;
using XenAdmin.Actions;
using XenAdmin.Network;
using XenAdmin.Core;
namespace XenAdmin.Dialogs
{
public partial class RoleElevationDialog : XenDialogBase
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public Session elevatedSession = null;
public string elevatedPassword;
public string elevatedUsername;
public string originalUsername;
public string originalPassword;
private List<Role> authorizedRoles;
/// <summary>
/// Displays a dialog informing the user they need a different role to complete the task, and offers the chance to switch user. Optionally logs
/// out the elevated session. If successful exposes the elevated session, password and username as fields.
/// </summary>
/// <param name="connection">The current server connection with the role information</param>
/// <param name="session">The session on which we have been denied access</param>
/// <param name="authorizedRoles">A list of roles that are able to complete the task</param>
/// <param name="actionTitle">A description of the current action, if null or empty will not be displayed</param>
public RoleElevationDialog(IXenConnection connection, Session session, List<Role> authorizedRoles, string actionTitle)
{
InitializeComponent();
Image icon = SystemIcons.Exclamation.ToBitmap();
pictureBox1.Image = icon;
pictureBox1.Width = icon.Width;
pictureBox1.Height = icon.Height;
this.connection = connection;
UserDetails ud = session.CurrentUserDetails;
labelCurrentUserValue.Text = ud.UserDisplayName ?? ud.UserName ?? Messages.UNKNOWN_AD_USER;
labelCurrentRoleValue.Text = Role.FriendlyCSVRoleList(session.Roles);
authorizedRoles.Sort((r1, r2) => r2.CompareTo(r1));
labelRequiredRoleValue.Text = Role.FriendlyCSVRoleList(authorizedRoles);
labelServerValue.Text = Helpers.GetName(connection);
labelServer.Text = Helpers.IsPool(connection) ? Messages.POOL_COLON : Messages.SERVER_COLON;
originalUsername = session.Connection.Username;
originalPassword = session.Connection.Password;
if (string.IsNullOrEmpty(actionTitle))
{
labelCurrentAction.Visible = false;
labelCurrentActionValue.Visible = false;
}
else
{
labelCurrentActionValue.Text = actionTitle;
}
this.authorizedRoles = authorizedRoles;
}
private void buttonAuthorize_Click(object sender, EventArgs e)
{
try
{
Exception delegateException = null;
log.Debug("Testing logging in with the new credentials");
DelegatedAsyncAction loginAction = new DelegatedAsyncAction(connection,
Messages.AUTHORIZING_USER,
Messages.CREDENTIALS_CHECKING,
Messages.CREDENTIALS_CHECK_COMPLETE,
delegate
{
try
{
elevatedSession = connection.ElevatedSession(TextBoxUsername.Text.Trim(), TextBoxPassword.Text);
}
catch (Exception ex)
{
delegateException = ex;
}
});
using (var dlg = new ActionProgressDialog(loginAction, ProgressBarStyle.Marquee, false))
dlg.ShowDialog(this);
// The exception would have been handled by the action progress dialog, just return the user to the sudo dialog
if (loginAction.Exception != null)
return;
if(HandledAnyDelegateException(delegateException))
return;
if (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession))
{
elevatedUsername = TextBoxUsername.Text.Trim();
elevatedPassword = TextBoxPassword.Text;
DialogResult = DialogResult.OK;
Close();
return;
}
ShowNotAuthorisedDialog();
return;
}
catch (Exception ex)
{
log.DebugFormat("Exception when attempting to sudo action: {0} ", ex);
using (var dlg = new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
String.Format(Messages.USER_AUTHORIZATION_FAILED, TextBoxUsername.Text),
Messages.XENCENTER)))
{
dlg.ShowDialog(Parent);
}
}
finally
{
// Check whether we have a successful elevated session and whether we have been asked to log it out
// If non successful (most likely the new subject is not authorized) then log it out anyway.
if (elevatedSession != null && DialogResult != DialogResult.OK)
{
elevatedSession.Connection.Logout(elevatedSession);
elevatedSession = null;
}
}
}
private bool HandledAnyDelegateException(Exception delegateException)
{
if (delegateException != null)
{
Failure f = delegateException as Failure;
if (f != null && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
{
ShowNotAuthorisedDialog();
return true;
}
throw delegateException;
}
return false;
}
private void ShowNotAuthorisedDialog()
{
using (var dlg = new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
Messages.USER_NOT_AUTHORIZED,
Messages.PERMISSION_DENIED)))
{
dlg.ShowDialog(this);
}
}
private bool SessionAuthorized(Session s)
{
UserDetails ud = s.CurrentUserDetails;
foreach (Role r in s.Roles)
{
if (authorizedRoles.Contains(r))
{
log.DebugFormat("Subject '{0}' is authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid);
return true;
}
}
log.DebugFormat("Subject '{0}' is not authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid);
return false;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void UpdateButtons()
{
buttonAuthorize.Enabled = TextBoxUsername.Text.Trim() != "" && TextBoxPassword.Text != "";
}
private void TextBoxUsername_TextChanged(object sender, EventArgs e)
{
UpdateButtons();
}
private void TextBoxPassword_TextChanged(object sender, EventArgs e)
{
UpdateButtons();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime.Operations;
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "member", Target = "IronPython.Runtime.Exceptions.TraceBackFrame..ctor(System.Object,System.Object,System.Object)", MessageId = "0#globals")]
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "member", Target = "IronPython.Runtime.Exceptions.TraceBackFrame.Globals", MessageId = "Globals")]
namespace IronPython.Runtime.Exceptions {
[PythonType("traceback")]
[Serializable]
public class TraceBack {
private readonly TraceBack _next;
private readonly TraceBackFrame _frame;
private int _line;
public TraceBack(TraceBack nextTraceBack, TraceBackFrame fromFrame) {
_next = nextTraceBack;
_frame = fromFrame;
}
public TraceBack tb_next {
get {
return _next;
}
}
public TraceBackFrame tb_frame {
get {
return _frame;
}
}
public int tb_lineno {
get {
return _line;
}
}
public int tb_lasti {
get {
return 0; // not presently tracked
}
}
internal void SetLine(int lineNumber) {
_line = lineNumber;
}
/// <summary>
/// returns string containing human readable representation of traceback
/// </summary>
internal string Extract() {
var sb = new StringBuilder();
var tb = this;
while (tb != null) {
var f = tb._frame;
var lineno = tb._line;
var co = f.f_code;
var filename = co.co_filename;
var name = co.co_name;
sb.AppendFormat(" File \"{0}\", line {1}, in {2}{3}", filename, lineno, name, Environment.NewLine);
tb = tb._next;
}
return sb.ToString();
}
}
[PythonType("frame")]
[DebuggerDisplay("Code = {f_code.co_name}, Line = {f_lineno}")]
[Serializable]
public class TraceBackFrame {
private readonly PythonTracebackListener _traceAdapter;
private TracebackDelegate _trace;
private object _traceObject;
internal int _lineNo;
private readonly PythonDebuggingPayload _debugProperties;
private readonly Func<IDictionary<object, object>> _scopeCallback;
private readonly PythonDictionary _globals;
private readonly object _locals;
private readonly FunctionCode _code;
private readonly CodeContext/*!*/ _context;
private readonly TraceBackFrame _back;
internal TraceBackFrame(CodeContext/*!*/ context, PythonDictionary globals, object locals, FunctionCode code) {
_globals = globals;
_locals = locals;
_code = code;
_context = context;
}
internal TraceBackFrame(CodeContext/*!*/ context, PythonDictionary globals, object locals, FunctionCode code, TraceBackFrame back) {
_globals = globals;
_locals = locals;
_code = code;
_context = context;
_back = back;
}
internal TraceBackFrame(PythonTracebackListener traceAdapter, FunctionCode code, TraceBackFrame back, PythonDebuggingPayload debugProperties, Func<IDictionary<object, object>> scopeCallback) {
_traceAdapter = traceAdapter;
_code = code;
_back = back;
_debugProperties = debugProperties;
_scopeCallback = scopeCallback;
}
[SpecialName, PropertyMethod]
public object Getf_trace() {
if (_traceAdapter != null) {
return _traceObject;
} else {
return null;
}
}
[SpecialName, PropertyMethod]
public void Setf_trace(object value) {
_traceObject = value;
_trace = (TracebackDelegate)Converter.ConvertToDelegate(value, typeof(TracebackDelegate));
}
[SpecialName, PropertyMethod]
public void Deletef_trace() {
Setf_trace(null);
}
internal CodeContext Context {
get {
return _context;
}
}
internal TracebackDelegate TraceDelegate {
get {
if (_traceAdapter != null) {
return _trace;
} else {
return null;
}
}
}
public PythonDictionary f_globals {
get {
object context;
if (_scopeCallback != null &&
_scopeCallback().TryGetValue(Compiler.Ast.PythonAst.GlobalContextName, out context) && context != null) {
return ((CodeContext)context).GlobalDict;
} else {
return _globals;
}
}
}
public object f_locals {
get {
if (_traceAdapter != null && _scopeCallback != null) {
if (_code.IsModule) {
// don't use the scope callback for locals in a module, use our globals dictionary instead
return f_globals;
}
return new PythonDictionary(new DebuggerDictionaryStorage(_scopeCallback()));
} else {
return _locals;
}
}
}
public FunctionCode f_code {
get {
return _code;
}
}
public object f_builtins {
get {
return _context.LanguageContext.BuiltinModuleDict;
}
}
public TraceBackFrame f_back {
get {
return _back;
}
}
public object f_exc_traceback {
[Python3Warning("f_exc_traceback has been removed in 3.x")]
get {
return null;
}
}
public object f_exc_type {
[Python3Warning("f_exc_type has been removed in 3.x")]
get {
return null;
}
}
public bool f_restricted {
get {
return false;
}
}
public object f_lineno {
get {
if (_traceAdapter != null) {
return _lineNo;
} else {
return 1;
}
}
set {
if (!(value is int)) {
throw PythonOps.ValueError("lineno must be an integer");
}
SetLineNumber((int)value);
}
}
private void SetLineNumber(int newLineNum) {
var pyThread = PythonOps.GetFunctionStackNoCreate();
if (_traceAdapter == null || !IsTopMostFrame(pyThread)) {
throw PythonOps.ValueError("f_lineno can only be set by a trace function on the topmost frame");
}
FunctionCode funcCode = _debugProperties.Code;
Dictionary<int, Dictionary<int, bool>> loopAndFinallyLocations = _debugProperties.LoopAndFinallyLocations;
Dictionary<int, bool> handlerLocations = _debugProperties.HandlerLocations;
Dictionary<int, bool> currentLoopIds = null;
bool inForLoopOrFinally = loopAndFinallyLocations != null && loopAndFinallyLocations.TryGetValue(_lineNo, out currentLoopIds);
int originalNewLine = newLineNum;
if (newLineNum < funcCode.Span.Start.Line) {
throw PythonOps.ValueError("line {0} comes before the current code block", newLineNum);
} else if (newLineNum > funcCode.Span.End.Line) {
throw PythonOps.ValueError("line {0} comes after the current code block", newLineNum);
}
while (newLineNum <= funcCode.Span.End.Line) {
var span = new SourceSpan(new SourceLocation(0, newLineNum, 1), new SourceLocation(0, newLineNum, Int32.MaxValue));
// Check if we're jumping onto a handler
bool handlerIsFinally;
if (handlerLocations != null && handlerLocations.TryGetValue(newLineNum, out handlerIsFinally)) {
throw PythonOps.ValueError("can't jump to 'except' line");
}
// Check if we're jumping into a for-loop
Dictionary<int, bool> jumpIntoLoopIds;
if (loopAndFinallyLocations != null && loopAndFinallyLocations.TryGetValue(newLineNum, out jumpIntoLoopIds)) {
// If we're not in any loop already - then we can't jump into a loop
if (!inForLoopOrFinally) {
throw BadForOrFinallyJump(newLineNum, jumpIntoLoopIds);
}
// If we're in loops - we can only jump if we're not entering a new loop
foreach (int jumpIntoLoopId in jumpIntoLoopIds.Keys) {
if (!currentLoopIds.ContainsKey(jumpIntoLoopId)) {
throw BadForOrFinallyJump(newLineNum, currentLoopIds);
}
}
} else if (currentLoopIds != null) {
foreach (bool isFinally in currentLoopIds.Values) {
if (isFinally) {
throw PythonOps.ValueError("can't jump out of 'finally block'");
}
}
}
if (_traceAdapter.PythonContext.TracePipeline.TrySetNextStatement(_code.co_filename, span)) {
_lineNo = newLineNum;
return;
}
++newLineNum;
}
throw PythonOps.ValueError("line {0} is invalid jump location ({1} - {2} are valid)", originalNewLine, funcCode.Span.Start.Line, funcCode.Span.End.Line);
}
private bool IsTopMostFrame(List<FunctionStack> pyThread) {
return pyThread != null && pyThread.Count != 0 && pyThread[pyThread.Count - 1].Frame == this;
}
private static Exception BadForOrFinallyJump(int newLineNum, Dictionary<int, bool> jumpIntoLoopIds) {
foreach (bool isFinally in jumpIntoLoopIds.Values) {
if (isFinally) {
return PythonOps.ValueError("can't jump into 'finally block'", newLineNum);
}
}
return PythonOps.ValueError("can't jump into 'for loop'", newLineNum);
}
}
public delegate TracebackDelegate TracebackDelegate(TraceBackFrame frame, string result, object payload);
}
| |
//! \file ArcAil.cs
//! \date Mon Apr 20 21:21:49 2015
//! \brief Ail resource archives.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using GameRes.Utility;
namespace GameRes.Formats.Ail
{
[Export(typeof(ArchiveFormat))]
[ExportMetadata("Priority", -1)]
public class DatOpener : ArchiveFormat
{
public override string Tag { get { return "DAT/Ail"; } }
public override string Description { get { return "Ail resource archive"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public DatOpener ()
{
Extensions = new string[] { "dat", "snl" };
}
public override ArcFile TryOpen (ArcView file)
{
int count = file.View.ReadInt32 (0);
if (!IsSaneCount (count))
return null;
var dir = ReadIndex (file, 4, count);
if (null == dir)
return null;
return new ArcFile (file, this, dir);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var input = arc.File.CreateStream (entry.Offset, entry.Size);
var pentry = entry as PackedEntry;
if (null == pentry || !pentry.IsPacked)
return input;
using (input)
{
byte[] data = new byte[pentry.UnpackedSize];
LzssUnpack (input, data);
return new BinMemoryStream (data, entry.Name);
}
}
internal List<Entry> ReadIndex (ArcView file, uint index_offset, int count)
{
var base_name = Path.GetFileNameWithoutExtension (file.Name);
long offset = index_offset + count*4;
if (offset >= file.MaxOffset)
return null;
var dir = new List<Entry> (count/2);
for (int i = 0; i < count; ++i)
{
uint size = file.View.ReadUInt32 (index_offset);
if (size != 0 && size != uint.MaxValue)
{
var entry = new PackedEntry
{
Name = string.Format ("{0}#{1:D5}", base_name, i),
Offset = offset,
Size = size,
IsPacked = false,
};
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
offset += size;
}
index_offset += 4;
}
if (0 == dir.Count || (file.MaxOffset - offset) > 0x80000)
return null;
DetectFileTypes (file, dir);
return dir;
}
internal void DetectFileTypes (ArcView file, List<Entry> dir)
{
byte[] preview = new byte[16];
byte[] sign_buf = new byte[4];
foreach (PackedEntry entry in dir)
{
uint extra = 6;
if (extra > entry.Size)
continue;
uint signature = file.View.ReadUInt32 (entry.Offset);
if (1 == (signature & 0xFFFF))
{
entry.IsPacked = true;
entry.UnpackedSize = file.View.ReadUInt32 (entry.Offset+2);
}
else if (0 == signature || file.View.AsciiEqual (entry.Offset+4, "OggS"))
{
extra = 4;
}
entry.Offset += extra;
entry.Size -= extra;
if (entry.IsPacked)
{
file.View.Read (entry.Offset, preview, 0, (uint)preview.Length);
using (var input = new MemoryStream (preview))
{
LzssUnpack (input, sign_buf);
signature = LittleEndian.ToUInt32 (sign_buf, 0);
}
}
else
{
signature = file.View.ReadUInt32 (entry.Offset);
}
if (0 != signature)
SetEntryType (entry, signature);
}
}
static void SetEntryType (Entry entry, uint signature)
{
if (0xBA010000 == signature)
{
entry.Type = "video";
entry.Name = Path.ChangeExtension (entry.Name, "mpg");
}
else
{
var res = AutoEntry.DetectFileType (signature);
if (null != res)
entry.ChangeType (res);
}
}
/// <summary>
/// Custom LZSS decompression with frame pre-initialization and reveresed control bits meaning.
/// </summary>
static void LzssUnpack (Stream input, byte[] output)
{
int frame_pos = 0xfee;
byte[] frame = new byte[0x1000];
for (int i = 0; i < frame_pos; ++i)
frame[i] = 0x20;
int dst = 0;
int ctl = 0;
while (dst < output.Length)
{
ctl >>= 1;
if (0 == (ctl & 0x100))
{
ctl = input.ReadByte();
if (-1 == ctl)
break;
ctl |= 0xff00;
}
if (0 == (ctl & 1))
{
int v = input.ReadByte();
if (-1 == v)
break;
output[dst++] = (byte)v;
frame[frame_pos++] = (byte)v;
frame_pos &= 0xfff;
}
else
{
int offset = input.ReadByte();
if (-1 == offset)
break;
int count = input.ReadByte();
if (-1 == count)
break;
offset |= (count & 0xf0) << 4;
count = (count & 0x0f) + 3;
for (int i = 0; i < count; i++)
{
if (dst >= output.Length)
break;
byte v = frame[offset++];
offset &= 0xfff;
frame[frame_pos++] = v;
frame_pos &= 0xfff;
output[dst++] = v;
}
}
}
}
}
}
| |
#if NET_4_0 || NET_4_5 || PORTABLE
using System;
using System.Threading.Tasks;
using NUnit.Framework;
#if NET_4_0 || PORTABLE
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.TestData
{
public class AsyncRealFixture
{
[Test]
public async void AsyncVoid()
{
var result = await ReturnOne();
Assert.AreEqual(1, result);
}
#region async Task
[Test]
public async System.Threading.Tasks.Task AsyncTaskSuccess()
{
var result = await ReturnOne();
Assert.AreEqual(1, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskFailure()
{
var result = await ReturnOne();
Assert.AreEqual(2, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskError()
{
await ThrowException();
Assert.Fail("Should never get here");
}
#endregion
#region non-async Task
[Test]
public System.Threading.Tasks.Task TaskSuccess()
{
return Task.Run(() => Assert.AreEqual(1, 1));
}
[Test]
public System.Threading.Tasks.Task TaskFailure()
{
return Task.Run(() => Assert.AreEqual(1, 2));
}
[Test]
public System.Threading.Tasks.Task TaskError()
{
throw new InvalidOperationException();
}
#endregion
[Test]
public async Task<int> AsyncTaskResult()
{
return await ReturnOne();
}
[Test]
public Task<int> TaskResult()
{
return ReturnOne();
}
#region async Task<T>
[TestCase(ExpectedResult = 1)]
public async Task<int> AsyncTaskResultCheckSuccess()
{
return await ReturnOne();
}
[TestCase(ExpectedResult = 2)]
public async Task<int> AsyncTaskResultCheckFailure()
{
return await ReturnOne();
}
[TestCase(ExpectedResult = 0)]
public async Task<int> AsyncTaskResultCheckError()
{
return await ThrowException();
}
#endregion
#region non-async Task<T>
[TestCase(ExpectedResult = 1)]
public Task<int> TaskResultCheckSuccess()
{
return ReturnOne();
}
[TestCase(ExpectedResult = 2)]
public Task<int> TaskResultCheckFailure()
{
return ReturnOne();
}
[TestCase(ExpectedResult = 0)]
public Task<int> TaskResultCheckError()
{
return ThrowException();
}
#endregion
[TestCase(1, 2)]
public async System.Threading.Tasks.Task AsyncTaskTestCaseWithParametersSuccess(int a, int b)
{
Assert.AreEqual(await ReturnOne(), b - a);
}
[TestCase(ExpectedResult = null)]
public async Task<object> AsyncTaskResultCheckSuccessReturningNull()
{
return await Task.Run(() => (object)null);
}
[TestCase(ExpectedResult = null)]
public Task<object> TaskResultCheckSuccessReturningNull()
{
return Task.Run(() => (object)null);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskSuccess()
{
var result = await Task.Run(async () => await ReturnOne());
Assert.AreEqual(1, result);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskFailure()
{
var result = await Task.Run(async () => await ReturnOne());
Assert.AreEqual(2, result);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskError()
{
await Task.Run(async () => await ThrowException());
Assert.Fail("Should never get here");
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleSuccess()
{
var result = await ReturnOne();
Assert.AreEqual(await ReturnOne(), result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleFailure()
{
var result = await ReturnOne();
Assert.AreEqual(await ReturnOne() + 1, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleError()
{
await ThrowException();
Assert.Fail("Should never get here");
}
[Test]
public async System.Threading.Tasks.Task TaskCheckTestContextAcrossTasks()
{
var testName = await GetTestNameFromContext();
Assert.IsNotNull(testName);
Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name);
}
[Test]
public async System.Threading.Tasks.Task TaskCheckTestContextWithinTestBody()
{
var testName = TestContext.CurrentContext.Test.Name;
await ReturnOne();
Assert.IsNotNull(testName);
Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name);
}
private static Task<string> GetTestNameFromContext()
{
return Task.Run(() => TestContext.CurrentContext.Test.Name);
}
private static Task<int> ReturnOne()
{
return Task.Run(() => 1);
}
private static Task<int> ThrowException()
{
Func<int> throws = () => { throw new InvalidOperationException(); };
return Task.Run( throws );
}
}
}
#endif
| |
/*
* 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 copyrightD
* 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.Generic;
using System.Text;
using OMV = OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModules.SharedBase;
namespace OpenSim.Region.PhysicsModule.BulletS
{
/*
* Class to wrap all objects.
* The rest of BulletSim doesn't need to keep checking for avatars or prims
* unless the difference is significant.
*
* Variables in the physicsl objects are in three forms:
* VariableName: used by the simulator and performs taint operations, etc
* RawVariableName: direct reference to the BulletSim storage for the variable value
* ForceVariableName: direct reference (store and fetch) to the value in the physics engine.
* The last one should only be referenced in taint-time.
*/
/*
* As of 20121221, the following are the call sequences (going down) for different script physical functions:
* llApplyImpulse llApplyRotImpulse llSetTorque llSetForce
* SOP.ApplyImpulse SOP.ApplyAngularImpulse SOP.SetAngularImpulse SOP.SetForce
* SOG.ApplyImpulse SOG.ApplyAngularImpulse SOG.SetAngularImpulse
* PA.AddForce PA.AddAngularForce PA.Torque = v PA.Force = v
* BS.ApplyCentralForce BS.ApplyTorque
*/
// Flags used to denote which properties updates when making UpdateProperties calls to linksets, etc.
public enum UpdatedProperties : uint
{
Position = 1 << 0,
Orientation = 1 << 1,
Velocity = 1 << 2,
Acceleration = 1 << 3,
RotationalVelocity = 1 << 4,
EntPropUpdates = Position | Orientation | Velocity | Acceleration | RotationalVelocity,
}
public abstract class BSPhysObject : PhysicsActor
{
protected BSPhysObject()
{
}
protected BSPhysObject(BSScene parentScene, uint localID, string name, string typeName)
{
IsInitialized = false;
PhysScene = parentScene;
LocalID = localID;
PhysObjectName = name;
Name = name; // PhysicsActor also has the name of the object. Someday consolidate.
TypeName = typeName;
// Oddity if object is destroyed and recreated very quickly it could still have the old body.
if (!PhysBody.HasPhysicalBody)
PhysBody = new BulletBody(localID);
// Clean out anything that might be in the physical actor list.
// Again, a workaround for destroying and recreating an object very quickly.
PhysicalActors.Dispose();
UserSetCenterOfMassDisplacement = null;
PrimAssetState = PrimAssetCondition.Unknown;
// Initialize variables kept in base.
// Beware that these cause taints to be queued whch can cause race conditions on startup.
GravModifier = 1.0f;
Gravity = new OMV.Vector3(0f, 0f, BSParam.Gravity);
HoverActive = false;
// Default material type. Also sets Friction, Restitution and Density.
SetMaterial((int)MaterialAttributes.Material.Wood);
CollisionsLastTickStep = -1;
SubscribedEventsMs = 0;
// Crazy values that will never be true
CollidingStep = BSScene.NotASimulationStep;
CollidingGroundStep = BSScene.NotASimulationStep;
CollisionAccumulation = BSScene.NotASimulationStep;
ColliderIsMoving = false;
CollisionScore = 0;
// All axis free.
LockedLinearAxis = LockedAxisFree;
LockedAngularAxis = LockedAxisFree;
}
// Tell the object to clean up.
public virtual void Destroy()
{
PhysicalActors.Enable(false);
PhysScene.TaintedObject(LocalID, "BSPhysObject.Destroy", delegate()
{
PhysicalActors.Dispose();
});
}
public BSScene PhysScene { get; protected set; }
// public override uint LocalID { get; set; } // Use the LocalID definition in PhysicsActor
public string PhysObjectName { get; protected set; }
public string TypeName { get; protected set; }
// Set to 'true' when the object is completely initialized.
// This mostly prevents property updates and collisions until the object is completely here.
public bool IsInitialized { get; protected set; }
// Set to 'true' if an object (mesh/linkset/sculpty) is not completely constructed.
// This test is used to prevent some updates to the object when it only partially exists.
// There are several reasons and object might be incomplete:
// Its underlying mesh/sculpty is an asset which must be fetched from the asset store
// It is a linkset who is being added to or removed from
// It is changing state (static to physical, for instance) which requires rebuilding
// This is a computed value based on the underlying physical object construction
abstract public bool IsIncomplete { get; }
// Return the object mass without calculating it or having side effects
public abstract float RawMass { get; }
// Set the raw mass but also update physical mass properties (inertia, ...)
// 'inWorld' true if the object has already been added to the dynamic world.
public abstract void UpdatePhysicalMassProperties(float mass, bool inWorld);
// The gravity being applied to the object. A function of default grav, GravityModifier and Buoyancy.
public virtual OMV.Vector3 Gravity { get; set; }
// The last value calculated for the prim's inertia
public OMV.Vector3 Inertia { get; set; }
// Reference to the physical body (btCollisionObject) of this object
public BulletBody PhysBody = new BulletBody(0);
// Reference to the physical shape (btCollisionShape) of this object
public BSShape PhysShape = new BSShapeNull();
// The physical representation of the prim might require an asset fetch.
// The asset state is first 'Unknown' then 'Waiting' then either 'Failed' or 'Fetched'.
public enum PrimAssetCondition
{
Unknown, Waiting, FailedAssetFetch, FailedMeshing, Fetched
}
public PrimAssetCondition PrimAssetState { get; set; }
public virtual bool AssetFailed()
{
return ( (this.PrimAssetState == PrimAssetCondition.FailedAssetFetch)
|| (this.PrimAssetState == PrimAssetCondition.FailedMeshing) );
}
// The objects base shape information. Null if not a prim type shape.
public PrimitiveBaseShape BaseShape { get; protected set; }
// When the physical properties are updated, an EntityProperty holds the update values.
// Keep the current and last EntityProperties to enable computation of differences
// between the current update and the previous values.
public EntityProperties CurrentEntityProperties { get; set; }
public EntityProperties LastEntityProperties { get; set; }
public virtual OMV.Vector3 Scale { get; set; }
// It can be confusing for an actor to know if it should move or update an object
// depeneding on the setting of 'selected', 'physical, ...
// This flag is the true test -- if true, the object is being acted on in the physical world
public abstract bool IsPhysicallyActive { get; }
// Detailed state of the object.
public abstract bool IsSolid { get; }
public abstract bool IsStatic { get; }
public abstract bool IsSelected { get; }
public abstract bool IsVolumeDetect { get; }
// Materialness
public MaterialAttributes.Material Material { get; private set; }
public override void SetMaterial(int material)
{
Material = (MaterialAttributes.Material)material;
// Setting the material sets the material attributes also.
// TODO: decide if this is necessary -- the simulator does this.
MaterialAttributes matAttrib = BSMaterials.GetAttributes(Material, false);
Friction = matAttrib.friction;
Restitution = matAttrib.restitution;
Density = matAttrib.density;
// DetailLog("{0},{1}.SetMaterial,Mat={2},frict={3},rest={4},den={5}", LocalID, TypeName, Material, Friction, Restitution, Density);
}
public override float Density
{
get
{
return base.Density;
}
set
{
DetailLog("{0},BSPhysObject.Density,set,den={1}", LocalID, value);
base.Density = value;
}
}
// Stop all physical motion.
public abstract void ZeroMotion(bool inTaintTime);
public abstract void ZeroAngularMotion(bool inTaintTime);
// Update the physical location and motion of the object. Called with data from Bullet.
public abstract void UpdateProperties(EntityProperties entprop);
public virtual OMV.Vector3 RawPosition { get; set; }
public abstract OMV.Vector3 ForcePosition { get; set; }
public virtual OMV.Quaternion RawOrientation { get; set; }
public abstract OMV.Quaternion ForceOrientation { get; set; }
public virtual OMV.Vector3 RawVelocity { get; set; }
public abstract OMV.Vector3 ForceVelocity { get; set; }
public OMV.Vector3 RawForce { get; set; }
public OMV.Vector3 RawTorque { get; set; }
public override void AddAngularForce(OMV.Vector3 force, bool pushforce)
{
AddAngularForce(force, pushforce, false);
}
public abstract void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime);
public abstract void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime);
public abstract OMV.Vector3 ForceRotationalVelocity { get; set; }
public abstract float ForceBuoyancy { get; set; }
public virtual bool ForceBodyShapeRebuild(bool inTaintTime) { return false; }
public override bool PIDActive
{
get { return MoveToTargetActive; }
set { MoveToTargetActive = value; }
}
public override OMV.Vector3 PIDTarget { set { MoveToTargetTarget = value; } }
public override float PIDTau { set { MoveToTargetTau = value; } }
public bool MoveToTargetActive { get; set; }
public OMV.Vector3 MoveToTargetTarget { get; set; }
public float MoveToTargetTau { get; set; }
// Used for llSetHoverHeight and maybe vehicle height. Hover Height will override MoveTo target's Z
public override bool PIDHoverActive {get {return HoverActive;} set { HoverActive = value; } }
public override float PIDHoverHeight { set { HoverHeight = value; } }
public override PIDHoverType PIDHoverType { set { HoverType = value; } }
public override float PIDHoverTau { set { HoverTau = value; } }
public bool HoverActive { get; set; }
public float HoverHeight { get; set; }
public PIDHoverType HoverType { get; set; }
public float HoverTau { get; set; }
// For RotLookAt
public override OMV.Quaternion APIDTarget { set { return; } }
public override bool APIDActive { set { return; } }
public override float APIDStrength { set { return; } }
public override float APIDDamping { set { return; } }
// The current velocity forward
public virtual float ForwardSpeed
{
get
{
OMV.Vector3 characterOrientedVelocity = RawVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation));
return characterOrientedVelocity.X;
}
}
// The forward speed we are trying to achieve (TargetVelocity)
public virtual float TargetVelocitySpeed
{
get
{
OMV.Vector3 characterOrientedVelocity = TargetVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation));
return characterOrientedVelocity.X;
}
}
// The user can optionally set the center of mass. The user's setting will override any
// computed center-of-mass (like in linksets).
// Note this is a displacement from the root's coordinates. Zero means use the root prim as center-of-mass.
public OMV.Vector3? UserSetCenterOfMassDisplacement { get; set; }
public OMV.Vector3 LockedLinearAxis; // zero means locked. one means free.
public OMV.Vector3 LockedAngularAxis; // zero means locked. one means free.
public const float FreeAxis = 1f;
public const float LockedAxis = 0f;
public readonly OMV.Vector3 LockedAxisFree = new OMV.Vector3(FreeAxis, FreeAxis, FreeAxis); // All axis are free
// If an axis is locked (flagged above) then the limits of that axis are specified here.
// Linear axis limits are relative to the object's starting coordinates.
// Angular limits are limited to -PI to +PI
public OMV.Vector3 LockedLinearAxisLow;
public OMV.Vector3 LockedLinearAxisHigh;
public OMV.Vector3 LockedAngularAxisLow;
public OMV.Vector3 LockedAngularAxisHigh;
// Enable physical actions. Bullet will keep sleeping non-moving physical objects so
// they need waking up when parameters are changed.
// Called in taint-time!!
public void ActivateIfPhysical(bool forceIt)
{
if (PhysBody.HasPhysicalBody)
{
if (IsPhysical)
{
// Physical objects might need activating
PhysScene.PE.Activate(PhysBody, forceIt);
}
else
{
// Clear the collision cache since we've changed some properties.
PhysScene.PE.ClearCollisionProxyCache(PhysScene.World, PhysBody);
}
}
}
// 'actors' act on the physical object to change or constrain its motion. These can range from
// hovering to complex vehicle motion.
// May be called at non-taint time as this just adds the actor to the action list and the real
// work is done during the simulation step.
// Note that, if the actor is already in the list and we are disabling same, the actor is just left
// in the list disabled.
public delegate BSActor CreateActor();
public void EnableActor(bool enableActor, string actorName, CreateActor creator)
{
lock (PhysicalActors)
{
BSActor theActor;
if (PhysicalActors.TryGetActor(actorName, out theActor))
{
// The actor already exists so just turn it on or off
DetailLog("{0},BSPhysObject.EnableActor,enablingExistingActor,name={1},enable={2}", LocalID, actorName, enableActor);
theActor.Enabled = enableActor;
}
else
{
// The actor does not exist. If it should, create it.
if (enableActor)
{
DetailLog("{0},BSPhysObject.EnableActor,creatingActor,name={1}", LocalID, actorName);
theActor = creator();
PhysicalActors.Add(actorName, theActor);
theActor.Enabled = true;
}
else
{
DetailLog("{0},BSPhysObject.EnableActor,notCreatingActorSinceNotEnabled,name={1}", LocalID, actorName);
}
}
}
}
#region Collisions
// Requested number of milliseconds between collision events. Zero means disabled.
protected int SubscribedEventsMs { get; set; }
// Given subscription, the time that a collision may be passed up
protected int NextCollisionOkTime { get; set; }
// The simulation step that last had a collision
protected long CollidingStep { get; set; }
// The simulation step that last had a collision with the ground
protected long CollidingGroundStep { get; set; }
// The simulation step that last collided with an object
protected long CollidingObjectStep { get; set; }
// The collision flags we think are set in Bullet
protected CollisionFlags CurrentCollisionFlags { get; set; }
// On a collision, check the collider and remember if the last collider was moving
// Used to modify the standing of avatars (avatars on stationary things stand still)
public bool ColliderIsMoving;
// 'true' if the last collider was a volume detect object
public bool ColliderIsVolumeDetect;
// Used by BSCharacter to manage standing (and not slipping)
public bool IsStationary;
// Count of collisions for this object
protected long CollisionAccumulation { get; set; }
public override bool IsColliding {
get { return (CollidingStep == PhysScene.SimulationStep); }
set {
if (value)
CollidingStep = PhysScene.SimulationStep;
else
CollidingStep = BSScene.NotASimulationStep;
}
}
// Complex objects (like linksets) need to know if there is a collision on any part of
// their shape. 'IsColliding' has an existing definition of reporting a collision on
// only this specific prim or component of linksets.
// 'HasSomeCollision' is defined as reporting if there is a collision on any part of
// the complex body that this prim is the root of.
public virtual bool HasSomeCollision
{
get { return IsColliding; }
set { IsColliding = value; }
}
public override bool CollidingGround {
get { return (CollidingGroundStep == PhysScene.SimulationStep); }
set
{
if (value)
CollidingGroundStep = PhysScene.SimulationStep;
else
CollidingGroundStep = BSScene.NotASimulationStep;
}
}
public override bool CollidingObj {
get { return (CollidingObjectStep == PhysScene.SimulationStep); }
set {
if (value)
CollidingObjectStep = PhysScene.SimulationStep;
else
CollidingObjectStep = BSScene.NotASimulationStep;
}
}
// The collisions that have been collected for the next collision reporting (throttled by subscription)
protected CollisionEventUpdate CollisionCollection = new CollisionEventUpdate();
// This is the collision collection last reported to the Simulator.
public CollisionEventUpdate CollisionsLastReported = new CollisionEventUpdate();
// Remember the collisions recorded in the last tick for fancy collision checking
// (like a BSCharacter walking up stairs).
public CollisionEventUpdate CollisionsLastTick = new CollisionEventUpdate();
private long CollisionsLastTickStep = -1;
// The simulation step is telling this object about a collision.
// Return 'true' if a collision was processed and should be sent up.
// Return 'false' if this object is not enabled/subscribed/appropriate for or has already seen this collision.
// Called at taint time from within the Step() function
public delegate bool CollideCall(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth);
public virtual bool Collide(uint collidingWith, BSPhysObject collidee,
OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth)
{
bool ret = false;
// The following lines make IsColliding(), CollidingGround() and CollidingObj work
CollidingStep = PhysScene.SimulationStep;
if (collidingWith <= PhysScene.TerrainManager.HighestTerrainID)
{
CollidingGroundStep = PhysScene.SimulationStep;
}
else
{
CollidingObjectStep = PhysScene.SimulationStep;
}
CollisionAccumulation++;
// For movement tests, remember if we are colliding with an object that is moving.
ColliderIsMoving = collidee != null ? (collidee.RawVelocity != OMV.Vector3.Zero) : false;
ColliderIsVolumeDetect = collidee != null ? (collidee.IsVolumeDetect) : false;
// Make a collection of the collisions that happened the last simulation tick.
// This is different than the collection created for sending up to the simulator as it is cleared every tick.
if (CollisionsLastTickStep != PhysScene.SimulationStep)
{
CollisionsLastTick = new CollisionEventUpdate();
CollisionsLastTickStep = PhysScene.SimulationStep;
}
CollisionsLastTick.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth));
// If someone has subscribed for collision events log the collision so it will be reported up
if (SubscribedEvents()) {
lock (PhysScene.CollisionLock)
{
CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth));
}
DetailLog("{0},{1}.Collision.AddCollider,call,with={2},point={3},normal={4},depth={5},colliderMoving={6}",
LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth, ColliderIsMoving);
ret = true;
}
return ret;
}
// Send the collected collisions into the simulator.
// Called at taint time from within the Step() function thus no locking problems
// with CollisionCollection and ObjectsWithNoMoreCollisions.
// Called with BSScene.CollisionLock locked to protect the collision lists.
// Return 'true' if there were some actual collisions passed up
public virtual bool SendCollisions()
{
bool ret = true;
// If no collisions this call but there were collisions last call, force the collision
// event to be happen right now so quick collision_end.
bool force = (CollisionCollection.Count == 0 && CollisionsLastReported.Count != 0);
// throttle the collisions to the number of milliseconds specified in the subscription
if (force || (PhysScene.SimulationNowTime >= NextCollisionOkTime))
{
NextCollisionOkTime = PhysScene.SimulationNowTime + SubscribedEventsMs;
// We are called if we previously had collisions. If there are no collisions
// this time, send up one last empty event so OpenSim can sense collision end.
if (CollisionCollection.Count == 0)
{
// If I have no collisions this time, remove me from the list of objects with collisions.
ret = false;
}
DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count);
base.SendCollisionUpdate(CollisionCollection);
// Remember the collisions from this tick for some collision specific processing.
CollisionsLastReported = CollisionCollection;
// The CollisionCollection instance is passed around in the simulator.
// Make sure we don't have a handle to that one and that a new one is used for next time.
// This fixes an interesting 'gotcha'. If we call CollisionCollection.Clear() here,
// a race condition is created for the other users of this instance.
CollisionCollection = new CollisionEventUpdate();
}
return ret;
}
// Subscribe for collision events.
// Parameter is the millisecond rate the caller wishes collision events to occur.
public override void SubscribeEvents(int ms) {
// DetailLog("{0},{1}.SubscribeEvents,subscribing,ms={2}", LocalID, TypeName, ms);
SubscribedEventsMs = ms;
if (ms > 0)
{
// make sure first collision happens
NextCollisionOkTime = Util.EnvironmentTickCountSubtract(SubscribedEventsMs);
PhysScene.TaintedObject(LocalID, TypeName+".SubscribeEvents", delegate()
{
if (PhysBody.HasPhysicalBody)
CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
});
}
else
{
// Subscribing for zero or less is the same as unsubscribing
UnSubscribeEvents();
}
}
public override void UnSubscribeEvents() {
// DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName);
SubscribedEventsMs = 0;
PhysScene.TaintedObject(LocalID, TypeName+".UnSubscribeEvents", delegate()
{
// Make sure there is a body there because sometimes destruction happens in an un-ideal order.
if (PhysBody.HasPhysicalBody)
CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
});
}
// Return 'true' if the simulator wants collision events
public override bool SubscribedEvents() {
return (SubscribedEventsMs > 0);
}
// Because 'CollisionScore' is called many times while sorting, it should not be recomputed
// each time called. So this is built to be light weight for each collision and to do
// all the processing when the user asks for the info.
public void ComputeCollisionScore()
{
// Scale the collision count by the time since the last collision.
// The "+1" prevents dividing by zero.
long timeAgo = PhysScene.SimulationStep - CollidingStep + 1;
CollisionScore = CollisionAccumulation / timeAgo;
}
public override float CollisionScore { get; set; }
#endregion // Collisions
#region Per Simulation Step actions
public BSActorCollection PhysicalActors = new BSActorCollection();
// When an update to the physical properties happens, this event is fired to let
// different actors to modify the update before it is passed around
public delegate void PreUpdatePropertyAction(ref EntityProperties entprop);
public event PreUpdatePropertyAction OnPreUpdateProperty;
protected void TriggerPreUpdatePropertyAction(ref EntityProperties entprop)
{
PreUpdatePropertyAction actions = OnPreUpdateProperty;
if (actions != null)
actions(ref entprop);
}
#endregion // Per Simulation Step actions
// High performance detailed logging routine used by the physical objects.
protected void DetailLog(string msg, params Object[] args)
{
if (PhysScene.PhysicsLogging.Enabled)
PhysScene.DetailLog(msg, args);
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using Microsoft.Win32;
namespace System.IO
{
public sealed class DirectoryInfo : FileSystemInfo
{
[System.Security.SecuritySafeCritical]
public DirectoryInfo(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
Init(path);
}
[System.Security.SecurityCritical]
private void Init(String path)
{
// Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead
if ((path.Length == 2) && (path[1] == ':'))
{
OriginalPath = ".";
}
else
{
OriginalPath = path;
}
String fullPath = PathHelpers.GetFullPathInternal(path);
FullPath = fullPath;
DisplayPath = GetDisplayName(OriginalPath, FullPath);
}
[System.Security.SecuritySafeCritical]
internal DirectoryInfo(String fullPath, IFileSystemObject fileSystemObject) : base(fileSystemObject)
{
Debug.Assert(PathHelpers.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
// Fast path when we know a DirectoryInfo exists.
OriginalPath = Path.GetFileName(fullPath);
FullPath = fullPath;
DisplayPath = GetDisplayName(OriginalPath, FullPath);
}
public override String Name
{
get
{
// DisplayPath is dir name for coreclr
Debug.Assert(GetDirName(FullPath) == DisplayPath || DisplayPath == ".");
return DisplayPath;
}
}
public DirectoryInfo Parent
{
[System.Security.SecuritySafeCritical]
get
{
String parentName;
// FullPath might be either "c:\bar" or "c:\bar\". Handle
// those cases, as well as avoiding mangling "c:\".
String s = FullPath;
if (s.Length > 3 && s[s.Length - 1] == Path.DirectorySeparatorChar)
s = FullPath.Substring(0, FullPath.Length - 1);
parentName = Path.GetDirectoryName(s);
if (parentName == null)
return null;
DirectoryInfo dir = new DirectoryInfo(parentName, null);
return dir;
}
}
[System.Security.SecuritySafeCritical]
public DirectoryInfo CreateSubdirectory(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return CreateSubdirectoryHelper(path);
}
[System.Security.SecurityCritical] // auto-generated
private DirectoryInfo CreateSubdirectoryHelper(String path)
{
Contract.Requires(path != null);
PathHelpers.ThrowIfEmptyOrRootedPath(path);
String newDirs = Path.Combine(FullPath, path);
String fullPath = Path.GetFullPath(newDirs);
if (0 != String.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.GetComparison()))
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), "path");
}
FileSystem.Current.CreateDirectory(fullPath);
// Check for read permission to directory we hand back by calling this constructor.
return new DirectoryInfo(fullPath);
}
[System.Security.SecurityCritical]
public void Create()
{
FileSystem.Current.CreateDirectory(FullPath);
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
public override bool Exists
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
try
{
return FileSystemObject.Exists;
}
catch
{
return false;
}
}
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
[SecurityCritical]
public FileInfo[] GetFiles(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileInfo> enble = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
List<FileInfo> fileList = new List<FileInfo>(enble);
return fileList.ToArray();
}
// Returns an array of Files in the DirectoryInfo specified by path
public FileInfo[] GetFiles()
{
return InternalGetFiles("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current directory.
public DirectoryInfo[] GetDirectories()
{
return InternalGetDirectories("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt").
public FileSystemInfo[] GetFileSystemInfos(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt").
public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, searchOption);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt").
private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
List<FileSystemInfo> fileList = new List<FileSystemInfo>(enumerable);
return fileList.ToArray();
}
// Returns an array of strongly typed FileSystemInfo entries which will contain a listing
// of all the files and directories.
public FileSystemInfo[] GetFileSystemInfos()
{
return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "System*" could match the System & System32
// directories).
private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
List<DirectoryInfo> fileList = new List<DirectoryInfo>(enumerable);
return fileList.ToArray();
}
public IEnumerable<DirectoryInfo> EnumerateDirectories()
{
return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, searchOption);
}
private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
}
public IEnumerable<FileInfo> EnumerateFiles()
{
return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, searchOption);
}
private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos()
{
return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, searchOption);
}
private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null.
//
public DirectoryInfo Root
{
[System.Security.SecuritySafeCritical]
get
{
String rootPath = Path.GetPathRoot(FullPath);
return new DirectoryInfo(rootPath);
}
}
[System.Security.SecuritySafeCritical]
public void MoveTo(String destDirName)
{
if (destDirName == null)
throw new ArgumentNullException("destDirName");
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName");
Contract.EndContractBlock();
String fullDestDirName = PathHelpers.GetFullPathInternal(destDirName);
if (fullDestDirName[fullDestDirName.Length - 1] != Path.DirectorySeparatorChar)
fullDestDirName = fullDestDirName + PathHelpers.DirectorySeparatorCharAsString;
String fullSourcePath;
if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar)
fullSourcePath = FullPath;
else
fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString;
StringComparison pathComparison = PathInternal.GetComparison();
if (String.Equals(fullSourcePath, fullDestDirName, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
String sourceRoot = Path.GetPathRoot(fullSourcePath);
String destinationRoot = Path.GetPathRoot(fullDestDirName);
if (!String.Equals(sourceRoot, destinationRoot, pathComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
FileSystem.Current.MoveDirectory(FullPath, fullDestDirName);
FullPath = fullDestDirName;
OriginalPath = destDirName;
DisplayPath = GetDisplayName(OriginalPath, FullPath);
// Flush any cached information about the directory.
Invalidate();
}
[System.Security.SecuritySafeCritical]
public override void Delete()
{
FileSystem.Current.RemoveDirectory(FullPath, false);
}
[System.Security.SecuritySafeCritical]
public void Delete(bool recursive)
{
FileSystem.Current.RemoveDirectory(FullPath, recursive);
}
// Returns the fully qualified path
public override String ToString()
{
return DisplayPath;
}
private static String GetDisplayName(String originalPath, String fullPath)
{
Debug.Assert(originalPath != null);
Debug.Assert(fullPath != null);
String displayName = "";
// Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead
if ((originalPath.Length == 2) && (originalPath[1] == ':'))
{
displayName = ".";
}
else
{
displayName = GetDirName(fullPath);
}
return displayName;
}
private static String GetDirName(String fullPath)
{
Debug.Assert(fullPath != null);
String dirName = null;
if (fullPath.Length > 3)
{
String s = fullPath;
if (fullPath[fullPath.Length - 1] == Path.DirectorySeparatorChar)
{
s = fullPath.Substring(0, fullPath.Length - 1);
}
dirName = Path.GetFileName(s);
}
else
{
dirName = fullPath; // For rooted paths, like "c:\"
}
return dirName;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using System.IO;
using Inspire.GameEngine.ScreenManager.Network;
using Inspire.Network;
using Inspire.Network.Packets.Client;
using Inspire.Network.Packets.Client.Content;
using Inspire.Network.Packets.Server;
using Inspire.Network.Packets.Server.Content;
using Inspire.Shared.Models.Enums;
using Inspire.Shared.Models.Templates;
using Toolkit.Configuration;
using Toolkit.Docking;
using Toolkit.Docking.Content;
using Toolkit.Mapping;
using Toolkit.Mapping.Actions;
using WeifenLuo.WinFormsUI.Docking;
using Style = WeifenLuo.WinFormsUI.Docking.Skins.Style;
namespace Toolkit
{
public partial class MainForm : Form
{
//Our windows we should use internally
FormContentExplorer _contentExplorer = new FormContentExplorer();
FormAssetExplorer _assetExplorer = new FormAssetExplorer();
// All the dock windows being used
ContentDockForm _contentDockForm = new ContentDockForm();
HistoryDockForm _historyDockForm = new HistoryDockForm();
LayersDockForm _layersDockForm = new LayersDockForm();
TilesetDockForm _tilesetDockForm = new TilesetDockForm();
private bool m_bSaveLayout = true;
private DeserializeDockContent m_deserializeDockContent;
private Thread thread;
// collection of button groups
private readonly ReadOnlyCollection<ReadOnlyCollection<ToolStripButton>> mGroups;
// an individual button group
private readonly ReadOnlyCollection<ToolStripButton> mGroup;
public MainForm()
{
CheckForIllegalCrossThreadCalls = false;
Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
InitializeComponent();
dockPanel.Theme = new VS2012LightTheme();
//dockPanel.Theme = new VS2005Theme();
m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);
// Bind for events
_contentDockForm.ContentRequested += ContentRequested;
// Listen for some particular events
PacketService.RegisterPacket<ContentResultPacket>(Handler);
PacketService.RegisterPacket<ContentSaveResultPacket>(HandleSaveResult);
//RegisterHotkeys();
dockPanel.ActiveDocumentChanged += DockPanelOnActiveDocumentChanged;
// add controls to this list as needed
mGroup = new List<ToolStripButton>()
{
buttonPencil,
buttonEraser,
buttonFill,
buttonDropper
}.AsReadOnly();
// add new groups to this list as needed
mGroups = new List<ReadOnlyCollection<ToolStripButton>>
{
mGroup
}.AsReadOnly();
}
private void DockPanelOnActiveDocumentChanged(object sender, EventArgs eventArgs)
{
var form = ((DockPanel)sender).ActiveDocument as MapForm;
TryAndBindMap(form);
}
private void TryAndBindMap(MapForm form)
{
if (form != null)
{
form.TryToMakeContext();
_layersDockForm.BindLayers(form);
}
}
private void RegisterHotkeys()
{
Hotkey hk = new Hotkey();
hk.Windows = true;
hk.Pressed += HkOnPressed;
hk.Register(this);
}
private void HkOnPressed(object sender, HandledEventArgs handledEventArgs)
{
}
private void HandleSaveResult(ContentSaveResultPacket contentSaveResultPacket)
{
if (contentSaveResultPacket.RequestResult == RequestResult.Succesful)
{
//TODO: Notify the user it was successful
}
else
{
ShowMessageBox(
"The server rejected your save request. This usually happens due to trying to save locked content.",
"Server Response");
}
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.S | Keys.ShiftKey))
{
buttonSaveContent.PerformClick();
return true;
}
if (keyData == (Keys.Control | Keys.S))
{
buttonSaveContent.PerformClick();
return true;
}
if (keyData == (Keys.Control | Keys.C))
{
copyButton.PerformClick();
return true;
}
if (keyData == (Keys.Control | Keys.V))
{
pasteButton.PerformClick();
return true;
}
if (keyData == (Keys.Control | Keys.X))
{
cutButton.PerformClick();
return true;
}
if (keyData == (Keys.Control | Keys.Z))
{
buttonUndo.PerformClick();
return true;
}
if (keyData == (Keys.Control | Keys.Y))
{
buttonRedo.PerformClick();
return true;
}
if (keyData == (Keys.P))
{
buttonPencil.PerformClick();
return true;
}
if (keyData == (Keys.D))
{
buttonDropper.PerformClick();
return true;
}
if (keyData == (Keys.F))
{
buttonFill.PerformClick();
return true;
}
if (keyData == (Keys.E))
{
buttonEraser.PerformClick();
return true;
}
if (keyData == (Keys.Q))
{
_layersDockForm.LayerMoveUp();
}
if (keyData == (Keys.W))
{
_layersDockForm.LayerMoveDown();
}
return base.ProcessCmdKey(ref msg, keyData);
}
public DialogResult ShowMessageBox(String message, String caption)
{
if (this.InvokeRequired)
{
return (DialogResult)this.Invoke(new FormDatabase.PassStringStringReturnDialogResultDelegate(ShowMessageBox), message, caption);
}
return MessageBox.Show(this, message, caption);
}
private void Handler(ContentResultPacket obj)
{
_pendingNetworkRequest = false;
if (obj.Locked)
{
ShowMessageBox("The server rejected your request for this content. This usually happens because someone else has it checked out.", "Server Response");
return;
}
_garb = obj;
if (obj.ContentType != ContentType.Map)
ShowForm();
else
ShowMapForm();
}
private void ShowMapForm()
{
if (this.InvokeRequired)
{ // this refers to the current form
this.Invoke(new Action(ShowMapForm)); // this line invokes the same function on the same thread as the current form
return;
}
var bindForm = new MapForm();
bindForm.SetBinding(_garb.ContentObject);
bindForm.Show(dockPanel, DockState.Document);
}
private ContentResultPacket _garb;
private void ShowForm()
{
if (this.InvokeRequired)
{ // this refers to the current form
this.Invoke(new Action(ShowForm)); // this line invokes the same function on the same thread as the current form
return;
}
var bindForm = new GenericContentBindForm();
bindForm.Show(dockPanel, DockState.Document);
bindForm.SetBinding(_garb.ContentObject, _garb.ContentType);
}
// This is a list of pending requests from the network
private bool _pendingNetworkRequest = false;
private void ContentRequested(object sender, TreeNodeMouseClickEventArgs treeNodeMouseClickEventArgs)
{
if (_pendingNetworkRequest)
{
MessageBox.Show("You must wait for your current network request to complete before issuing another.");
return;
}
// Retrieve the entry
var entry = (EditorTemplateEntry)treeNodeMouseClickEventArgs.Node.Tag;
_pendingNetworkRequest = true;
var request = new ContentRequestPacket(entry.ContentType, entry.ID);
// Send the request
NetworkManager.Instance.SendPacket(request);
}
void Application_ApplicationExit(object sender, EventArgs e)
{
//Kill the network loop
thread.Abort();
}
#region Methods
private IDockContent FindDocument(string text)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
if (form.Text == text)
return form as IDockContent;
return null;
}
else
{
foreach (IDockContent content in dockPanel.Documents)
if (content.DockHandler.TabText == text)
return content;
return null;
}
}
private void CloseAllDocuments()
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
form.Close();
}
else
{
for (int index = dockPanel.Contents.Count - 1; index >= 0; index--)
{
if (dockPanel.Contents[index] is IDockContent)
{
IDockContent content = (IDockContent)dockPanel.Contents[index];
content.DockHandler.Close();
}
}
}
}
private IDockContent GetContentFromPersistString(string persistString)
{
if (persistString == typeof(ContentDockForm).ToString())
return _contentDockForm;
if (persistString == typeof(HistoryDockForm).ToString())
return _historyDockForm;
if (persistString == typeof(LayersDockForm).ToString())
return _layersDockForm;
if (persistString == typeof(TilesetDockForm).ToString())
return _tilesetDockForm;
if (persistString == typeof(GenericContentBindForm).ToString())
return null;
if (persistString == typeof(MapForm).ToString())
return null;
throw new Exception("A backwards compatibilty issue was detected - regressing");
}
private void CloseAllContents()
{
// Close all other document windows
CloseAllDocuments();
}
#endregion
#region Event Handlers
private void MainForm_Load(object sender, System.EventArgs e)
{
//Set to the working directory
ProjectSettings.Instance.Location = Directory.GetCurrentDirectory();
ProjectSettings.Instance.SaveProject();
Text = "Inspire - " + ProjectSettings.Instance.Name + " [" + ProjectSettings.Instance.Location + "]";
// _contentExplorer.Show(dockPanel);
// _assetExplorer.Show(dockPanel);
//Update the network manager
thread = new Thread(NetworkLoop);
thread.Start();
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "windows.config");
if (File.Exists(configFile))
dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
if (!_contentDockForm.Visible)
_contentDockForm.Show(dockPanel, DockState.DockLeft);
// Show the login dialog - need to get an authentication token before we can do anything interesting
var loginForm = new FormLogin();
loginForm.ShowDialog();
// Show the waiting screen and ask for patience
// Generate the ContentMap dynamically, assinging everyone a backing
foreach (var contentType in GetValues<ContentType>())
{
// Send out a request for each content type
var request = new ContentListRequestPacket(contentType);
NetworkManager.Instance.SendPacket(request);
}
}
private static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "windows.config");
if (m_bSaveLayout)
dockPanel.SaveAsXml(configFile);
else if (File.Exists(configFile))
File.Delete(configFile);
// Save out to the app config
AppConfiguration.Instance.Serialize();
}
#endregion
private void mapToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void MainForm_Shown(object sender, EventArgs e)
{
}
void NetworkLoop()
{
while (true)
{
NetworkManager.Instance.Update();
Thread.Sleep(10);
}
}
private void CreateNewProject()
{
FormNewProject form = new FormNewProject();
form.StartPosition = FormStartPosition.CenterParent;
DialogResult result = form.ShowDialog();
if (result == DialogResult.OK)
{
//This was the newest loaded project, update editor.config
File.WriteAllText("editor.config", ProjectSettings.Instance.Location);
}
//If the user dosen't end up making a new project anyway, just reboot for now
Application.Restart();
}
private void toolStripMenuItemNewProject_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Creating a new project will close the current one - continue?", "Warning",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
//Create the new project...
CreateNewProject();
}
}
private void etcToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
//Tell the application it is time to terminate
Application.Exit();
}
private void testToolStripMenuItem_Click(object sender, EventArgs e)
{
//Start up the game engine
Process process = new Process();
process.StartInfo = new ProcessStartInfo(Directory.GetCurrentDirectory() + "\\GameClient.exe");
process.Start();
}
void process_Exited(object sender, EventArgs e)
{
MainMenuStrip.Enabled = true;
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
new FormAbout().ShowDialog();
}
private void closeAllToolStripMenuItem_Click(object sender, EventArgs e)
{
CloseAllDocuments();
}
private void contentExplorerToolStripMenuItem_Click(object sender, EventArgs e)
{
_contentDockForm.Show();
//if (!_contentExplorer.IsHidden)
// _contentExplorer.Hide();
//else
// _contentExplorer.Show();
}
private void assetExplorerToolStripMenuItem_Click(object sender, EventArgs e)
{
_assetExplorer.Show(dockPanel);
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
}
private void dockPanel_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
}
private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void itemToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("TODO: Implement...");
}
private void toolStripMenuItem5_Click(object sender, EventArgs e)
{
var form = new FormDatabase();
form.ShowDialog();
}
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
_historyDockForm.Show(dockPanel);
}
private void layersToolStripMenuItem_Click(object sender, EventArgs e)
{
_layersDockForm.Show(dockPanel);
}
private void tilesetsToolStripMenuItem_Click(object sender, EventArgs e)
{
_tilesetDockForm.Show(dockPanel);
}
private void MainForm_Leave(object sender, EventArgs e)
{
thread.Abort();
}
private void buttonSaveContent_Click(object sender, EventArgs e)
{
var activePanel = dockPanel.ActiveDocument;
var saveable = activePanel as ISaveable;
var x = 12;
if (saveable != null)
{
saveable.Save();
}
}
private void buttonSaveAll_Click(object sender, EventArgs e)
{
foreach (var window in dockPanel.FloatWindows)
{
var saveable = window as ISaveable;
if (saveable != null)
{
saveable.Save();
}
}
}
private void toolStripMenuItem6_Click(object sender, EventArgs e)
{
buttonSaveContent.PerformClick();
}
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
buttonSaveAll.PerformClick();
}
private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
{
Process.Start("http://neoindies.com/");
}
private void buttonPencil_Click(object sender, EventArgs e)
{
VerifySingleCheck(sender);
MapEditorGlobals.ActiveActionType = typeof(PencilAction);
}
private void VerifySingleCheck(object sender)
{
foreach (ReadOnlyCollection<ToolStripButton> group in mGroups)
if (@group.Contains(sender))
foreach (ToolStripButton b in @group)
b.Checked = b == sender;
}
private void buttonDropper_Click(object sender, EventArgs e)
{
VerifySingleCheck(sender);
}
private void buttonEraser_Click(object sender, EventArgs e)
{
MapEditorGlobals.ActiveActionType = typeof(EraserAction);
VerifySingleCheck(sender);
}
private void buttonFill_Click(object sender, EventArgs e)
{
MapEditorGlobals.ActiveActionType = typeof(FloodToolAction);
VerifySingleCheck(sender);
}
public MapForm GetActiveMap()
{
return dockPanel.ActiveDocument as MapForm;
}
private void UpdateRedoAndUndo()
{
var map = GetActiveMap();
var undosLeft = map.UndoManager;
}
private void buttonUndo_Click(object sender, EventArgs e)
{
var map = GetActiveMap();
if (map != null)
{
if (map.UndoManager.UndosLeft == 0)
{
MessageBox.Show("There's nothing left to undo.");
return;
}
map.UndoManager.PerformUndo();
return;
map.RedoStack.Push(new GameMapSnapshot(map.Map, typeof(PencilAction)));
var backupState = map.BackupStack.Pop();
map.Map = backupState.Map;
TryAndBindMap(map);
}
else
{
MessageBox.Show("Please select a map before trying to perform map actions.");
}
}
private void buttonRedo_Click(object sender, EventArgs e)
{
var map = GetActiveMap();
if (map != null)
{
if (map.UndoManager.RedosLeft == 0)
{
MessageBox.Show("There's nothing left to redo.");
return;
}
map.UndoManager.PerformRedo();
return;
var state = map.RedoStack.Pop();
var backupState = map.BackupStack.Pop();
map.Map = backupState.Map;
TryAndBindMap(map);
}
else
{
MessageBox.Show("Please select a map before trying to perform map actions.");
}
}
private void toolStripButton4_Click(object sender, EventArgs e)
{
var map = GetActiveMap();
if (map != null)
map.CutTiles();
}
private void toolStripButton6_Click(object sender, EventArgs e)
{
var map = GetActiveMap();
if (map != null)
map.CopyCurrentMapToBuffer();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
var map = GetActiveMap();
if (map != null)
map.PasteTiles();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.