context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Camera\CameraAnimInst.h:18
namespace UnrealEngine
{
public partial class UCameraAnimInst : UObject
{
public UCameraAnimInst(IntPtr adress)
: base(adress)
{
}
public UCameraAnimInst(UObject Parent = null, string Name = "CameraAnimInst")
: base(IntPtr.Zero)
{
NativePointer = E_NewObject_UCameraAnimInst(Parent, Name);
NativeManager.AddNativeWrapper(NativePointer, this);
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraAnimInst_BasePlayScale_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraAnimInst_BasePlayScale_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraAnimInst_CurrentBlendWeight_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraAnimInst_CurrentBlendWeight_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraAnimInst_CurTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraAnimInst_CurTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UCameraAnimInst_InitialCamToWorld_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraAnimInst_InitialCamToWorld_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraAnimInst_InitialFOV_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraAnimInst_InitialFOV_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UCameraAnimInst_LastCameraLoc_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraAnimInst_LastCameraLoc_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraAnimInst_PlayRate_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraAnimInst_PlayRate_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UCameraAnimInst_TransientScaleModifier_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraAnimInst_TransientScaleModifier_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UCameraAnimInst_UserPlaySpaceMatrix_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UCameraAnimInst_UserPlaySpaceMatrix_SET(IntPtr Ptr, IntPtr Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_NewObject_UCameraAnimInst(IntPtr Parent, string Name);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraAnimInst_AdvanceAnim(IntPtr self, float deltaTime, bool bJump);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraAnimInst_ApplyToView(IntPtr self, IntPtr inOutPOV);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraAnimInst_ApplyTransientScaling(IntPtr self, float scalar);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_UCameraAnimInst_GetCurrentTime(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraAnimInst_SetCurrentTime(IntPtr self, float newTime);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraAnimInst_SetDuration(IntPtr self, float newDuration);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraAnimInst_SetScale(IntPtr self, float newDuration);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraAnimInst_SetStopAutomatically(IntPtr self, bool bNewStopAutoMatically);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraAnimInst_Stop(IntPtr self, bool bImmediate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UCameraAnimInst_Update(IntPtr self, float newRate, float newScale, float newBlendInTime, float newBlendOutTime, float newDuration);
#endregion
#region Property
/// <summary>
/// "Intensity" value used to scale keyframe values.
/// </summary>
public float BasePlayScale
{
get => E_PROP_UCameraAnimInst_BasePlayScale_GET(NativePointer);
set => E_PROP_UCameraAnimInst_BasePlayScale_SET(NativePointer, value);
}
public float CurrentBlendWeight
{
get => E_PROP_UCameraAnimInst_CurrentBlendWeight_GET(NativePointer);
set => E_PROP_UCameraAnimInst_CurrentBlendWeight_SET(NativePointer, value);
}
/// <summary>
/// Current time for the animation
/// </summary>
public float CurTime
{
get => E_PROP_UCameraAnimInst_CurTime_GET(NativePointer);
set => E_PROP_UCameraAnimInst_CurTime_SET(NativePointer, value);
}
/// <summary>
/// transform of initial anim key, used for treating anim keys as offsets from initial key
/// </summary>
public FTransform InitialCamToWorld
{
get => E_PROP_UCameraAnimInst_InitialCamToWorld_GET(NativePointer);
set => E_PROP_UCameraAnimInst_InitialCamToWorld_SET(NativePointer, value);
}
/// <summary>
/// FOV of the initial anim key, used for treating fov keys as offsets from initial key.
/// </summary>
public float InitialFOV
{
get => E_PROP_UCameraAnimInst_InitialFOV_GET(NativePointer);
set => E_PROP_UCameraAnimInst_InitialFOV_SET(NativePointer, value);
}
/// <summary>
/// Camera Anim debug variable to trace back to previous location
/// </summary>
public FVector LastCameraLoc
{
get => E_PROP_UCameraAnimInst_LastCameraLoc_GET(NativePointer);
set => E_PROP_UCameraAnimInst_LastCameraLoc_SET(NativePointer, value);
}
/// <summary>
/// Multiplier for playback rate. 1.0 = normal.
/// </summary>
public float PlayRate
{
get => E_PROP_UCameraAnimInst_PlayRate_GET(NativePointer);
set => E_PROP_UCameraAnimInst_PlayRate_SET(NativePointer, value);
}
/// <summary>
/// A supplemental scale factor, allowing external systems to scale this anim as necessary. This is reset to 1.f each frame.
/// </summary>
public float TransientScaleModifier
{
get => E_PROP_UCameraAnimInst_TransientScaleModifier_GET(NativePointer);
set => E_PROP_UCameraAnimInst_TransientScaleModifier_SET(NativePointer, value);
}
/// <summary>
/// The user-defined space for UserDefined PlaySpace
/// </summary>
public FMatrix UserPlaySpaceMatrix
{
get => E_PROP_UCameraAnimInst_UserPlaySpaceMatrix_GET(NativePointer);
set => E_PROP_UCameraAnimInst_UserPlaySpaceMatrix_SET(NativePointer, value);
}
#endregion
#region ExternMethods
/// <summary>
/// advances the animation by the specified time - updates any modified interp properties, moves the group actor, etc
/// </summary>
public void AdvanceAnim(float deltaTime, bool bJump)
=> E_UCameraAnimInst_AdvanceAnim(this, deltaTime, bJump);
/// <summary>
/// Takes the given view and applies the camera anim transform and fov changes to it. Does not affect PostProcess.
/// </summary>
public void ApplyToView(FMinimalViewInfo inOutPOV)
=> E_UCameraAnimInst_ApplyToView(this, inOutPOV);
/// <summary>
/// Applies given scaling factor to the playing animation for the next update only.
/// </summary>
public void ApplyTransientScaling(float scalar)
=> E_UCameraAnimInst_ApplyTransientScaling(this, scalar);
/// <summary>
/// Returns the current playback time.
/// </summary>
public float GetCurrentTime()
=> E_UCameraAnimInst_GetCurrentTime(this);
/// <summary>
/// Jumps he camera anim to the given (unscaled) time.
/// </summary>
public void SetCurrentTime(float newTime)
=> E_UCameraAnimInst_SetCurrentTime(this, newTime);
/// <summary>
/// Changes the running duration of this active anim, while maintaining playback position.
/// </summary>
public void SetDuration(float newDuration)
=> E_UCameraAnimInst_SetDuration(this, newDuration);
/// <summary>
/// Changes the scale of the animation while playing.
/// </summary>
public void SetScale(float newDuration)
=> E_UCameraAnimInst_SetScale(this, newDuration);
/// <summary>
/// Sets whether this anim instance should automatically stop when finished.
/// </summary>
public void SetStopAutomatically(bool bNewStopAutoMatically)
=> E_UCameraAnimInst_SetStopAutomatically(this, bNewStopAutoMatically);
/// <summary>
/// Stops this instance playing whatever animation it is playing.
/// </summary>
public void Stop(bool bImmediate = false)
=> E_UCameraAnimInst_Stop(this, bImmediate);
/// <summary>
/// Updates this active instance with new parameters.
/// </summary>
public void Update(float newRate, float newScale, float newBlendInTime, float newBlendOutTime, float newDuration)
=> E_UCameraAnimInst_Update(this, newRate, newScale, newBlendInTime, newBlendOutTime, newDuration);
#endregion
public static implicit operator IntPtr(UCameraAnimInst self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator UCameraAnimInst(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<UCameraAnimInst>(PtrDesc);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
namespace System.Net.Sockets
{
internal partial class SafeCloseSocket :
#if DEBUG
DebugSafeHandleMinusOneIsInvalid
#else
SafeHandleMinusOneIsInvalid
#endif
{
private int _receiveTimeout = -1;
private int _sendTimeout = -1;
private bool _nonBlocking;
public SocketAsyncContext AsyncContext
{
get
{
return _innerSocket == null ?
SocketAsyncContext.ClosedAsyncContext :
_innerSocket.AsyncContext;
}
}
public int FileDescriptor
{
get
{
return (int)handle;
}
}
public bool IsNonBlocking
{
get
{
return _nonBlocking;
}
set
{
_nonBlocking = value;
//
// If transitioning to non-blocking, we need to set the native socket to non-blocking mode.
// If we ever transition back to blocking, we keep the native socket in non-blocking mode, and emulate
// blocking. This avoids problems with switching to native blocking while there are pending async
// operations.
//
if (value)
{
_innerSocket.SetNonBlocking();
}
}
}
public int ReceiveTimeout
{
get
{
return _receiveTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0);
_receiveTimeout = value;;
}
}
public int SendTimeout
{
get
{
return _sendTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0);
_sendTimeout = value;
}
}
public unsafe static SafeCloseSocket CreateSocket(int fileDescriptor)
{
return CreateSocket(InnerSafeCloseSocket.CreateSocket(fileDescriptor));
}
public unsafe static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.CreateSocket(addressFamily, socketType, protocolType, out errorCode));
return errorCode;
}
public unsafe static SocketError Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressSize, out SafeCloseSocket socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize, out errorCode));
return errorCode;
}
private void InnerReleaseHandle()
{
// No-op for Unix.
}
internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid
{
private SocketAsyncContext _asyncContext;
public void SetNonBlocking()
{
AsyncContext.SetNonBlocking();
}
public SocketAsyncContext AsyncContext
{
get
{
if (Volatile.Read(ref _asyncContext) == null)
{
Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext((int)handle, SocketAsyncEngine.Instance), null);
}
return _asyncContext;
}
}
private unsafe SocketError InnerReleaseHandle()
{
int errorCode;
if (_asyncContext != null)
{
_asyncContext.Close();
}
// If _blockable was set in BlockingRelease, it's safe to block here, which means
// we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which
// case we need to do some recovery.
if (_blockable)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") Following 'blockable' branch.");
}
errorCode = Interop.Sys.Close(handle);
if (errorCode == -1)
{
errorCode = (int)Interop.Sys.GetLastError();
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close()#1:" + errorCode.ToString());
}
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
// If it's not EWOULDBLOCK, there's no more recourse - we either succeeded or failed.
if (errorCode != (int)Interop.Error.EWOULDBLOCK)
{
if (errorCode == 0 && _asyncContext != null)
{
_asyncContext.Close();
}
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
// The socket must be non-blocking with a linger timeout set.
// We have to set the socket to blocking.
errorCode = Interop.Sys.Fcntl.SetIsNonBlocking(handle, 0);
if (errorCode == 0)
{
// The socket successfully made blocking; retry the close().
errorCode = Interop.Sys.Close(handle);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close()#2:" + errorCode.ToString());
}
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (errorCode == 0 && _asyncContext != null)
{
_asyncContext.Close();
}
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
// The socket could not be made blocking; fall through to the regular abortive close.
}
// By default or if CloseAsIs() path failed, set linger timeout to zero to get an abortive close (RST).
var linger = new Interop.Sys.LingerOption {
OnOff = 1,
Seconds = 0
};
errorCode = (int)Interop.Sys.SetLingerOption((int)handle, &linger);
#if DEBUG
_closeSocketLinger = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") setsockopt():" + errorCode.ToString());
}
if (errorCode != 0 && errorCode != (int)Interop.Error.EINVAL && errorCode != (int)Interop.Error.ENOPROTOOPT)
{
// Too dangerous to try closesocket() - it might block!
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
errorCode = Interop.Sys.Close(handle);
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close#3():" + (errorCode == -1 ? (int)Interop.Sys.GetLastError() : errorCode).ToString());
}
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
public static InnerSafeCloseSocket CreateSocket(int fileDescriptor)
{
var res = new InnerSafeCloseSocket();
res.SetHandle((IntPtr)fileDescriptor);
return res;
}
public static unsafe InnerSafeCloseSocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SocketError errorCode)
{
int fd;
Interop.Error error = Interop.Sys.Socket(addressFamily, socketType, protocolType, &fd);
if (error == Interop.Error.SUCCESS)
{
Debug.Assert(fd != -1);
errorCode = SocketError.Success;
// The socket was created successfully; enable IPV6_V6ONLY by default for AF_INET6 sockets.
if (addressFamily == AddressFamily.InterNetworkV6)
{
int on = 1;
error = Interop.Sys.SetSockOpt(fd, SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, (byte*)&on, sizeof(int));
if (error != Interop.Error.SUCCESS)
{
Interop.Sys.Close((IntPtr)fd);
fd = -1;
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
}
}
else
{
Debug.Assert(fd == -1);
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
var res = new InnerSafeCloseSocket();
res.SetHandle((IntPtr)fd);
return res;
}
public static unsafe InnerSafeCloseSocket Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressLen, out SocketError errorCode)
{
int acceptedFd;
if (!socketHandle.IsNonBlocking)
{
errorCode = socketHandle.AsyncContext.Accept(socketAddress, ref socketAddressLen, -1, out acceptedFd);
}
else
{
SocketPal.TryCompleteAccept(socketHandle.FileDescriptor, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode);
}
var res = new InnerSafeCloseSocket();
res.SetHandle((IntPtr)acceptedFd);
return res;
}
}
}
}
| |
/*
* Automata procedual dungeon generation proof-of-concept
*
*
* Developed by Adam White
* https://csharpcodewhisperer.blogspot.com
*
*
*/
using System;
using System.Collections.Generic;
using Microsoft.Win32;
namespace AutomataMapGenerator
{
public class MapHandler
{
Random rand = new Random();
public int MapWidth { get; set; }
public int MapHeight { get; set; }
public int PercentAreWalls { get; set; }
public int[,] Map;
public void MakeCaverns()
{
// By initilizing column in the outter loop, its only created ONCE
for(int column=0, row=0; row <= MapHeight-1; row++)
{
for(column = 0; column <= MapWidth-1; column++)
{
Map[column,row] = PlaceWallLogic(column,row);
}
}
}
public int PlaceWallLogic(int x,int y)
{
int numWalls = GetAdjacentWalls(x,y,1,1);
if(Map[x,y]==1)
{
if( numWalls >= 4 )
{
return 1;
}
if(numWalls<2)
{
return 0;
}
}
else
{
if(numWalls>=5)
{
return 1;
}
}
return 0;
}
public int GetAdjacentWalls(int x,int y,int scopeX,int scopeY)
{
int startX = x - scopeX;
int startY = y - scopeY;
int endX = x + scopeX;
int endY = y + scopeY;
int iX = startX;
int iY = startY;
int wallCounter = 0;
for(iY = startY; iY <= endY; iY++) {
for(iX = startX; iX <= endX; iX++)
{
if(!(iX==x && iY==y))
{
if(IsWall(iX,iY))
{
wallCounter += 1;
}
}
}
}
return wallCounter;
}
bool IsWall(int x,int y)
{
// Consider out-of-bound a wall
if( IsOutOfBounds(x,y) )
{
return true;
}
if( Map[x,y]==1 )
{
return true;
}
if( Map[x,y]==0 )
{
return false;
}
return false;
}
bool IsOutOfBounds(int x, int y)
{
if( x<0 || y<0 )
{
return true;
}
else if( x>MapWidth-1 || y>MapHeight-1 )
{
return true;
}
return false;
}
public void PrintMap()
{
Console.Clear();
Console.Write(MapToString());
}
string MapToString()
{
string returnString = string.Join(" ", // Seperator between each element
"Width:",
MapWidth.ToString(),
"\tHeight:",
MapHeight.ToString(),
"\t% Walls:",
PercentAreWalls.ToString(),
Environment.NewLine
);
List<string> mapSymbols = new List<string>();
mapSymbols.Add(".");
mapSymbols.Add("#");
mapSymbols.Add("+");
for(int column=0,row=0; row < MapHeight; row++ ) {
for( column = 0; column < MapWidth; column++ )
{
returnString += mapSymbols[Map[column,row]];
}
returnString += Environment.NewLine;
}
return returnString;
}
public MapHandler(int mapWidth, int mapHeight, int[,] map, int percentWalls=40)
{
this.MapWidth = mapWidth;
this.MapHeight = mapHeight;
this.PercentAreWalls = percentWalls;
this.Map = map;
}
public MapHandler()
{
MapWidth = 40;
MapHeight = 21;
PercentAreWalls = 40;
Map = new int[MapWidth,MapHeight];
RandomFillMap();
}
public void BlankMap()
{
for(int column=0,row=0; row < MapHeight; row++) {
for(column = 0; column < MapWidth; column++) {
Map[column,row] = 0;
}
}
}
public void RandomFillMap()
{
// New, empty map
Map = new int[MapWidth,MapHeight];
int mapMiddle = 0; // Temp variable
for(int column=0,row=0; row < MapHeight; row++) {
for(column = 0; column < MapWidth; column++)
{
// If coordinants lie on the the edge of the map (creates a border)
if(column == 0)
{
Map[column,row] = 1;
}
else if (row == 0)
{
Map[column,row] = 1;
}
else if (column == MapWidth-1)
{
Map[column,row] = 1;
}
else if (row == MapHeight-1)
{
Map[column,row] = 1;
}
// Else, fill with a wall a random percent of the time
else
{
mapMiddle = (MapHeight / 2);
if(row == mapMiddle)
{
Map[column,row] = 0;
}
else
{
Map[column,row] = RandomPercent(PercentAreWalls);
}
}
}
}
}
int RandomPercent(int percent)
{
if(percent>=rand.Next(1,101))
{
return 1;
}
return 0;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Datastream
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Unmanaged;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Data streamer internal interface to get rid of generics.
/// </summary>
internal interface IDataStreamer
{
/// <summary>
/// Callback invoked on topology size change.
/// </summary>
/// <param name="topVer">New topology version.</param>
/// <param name="topSize">New topology size.</param>
void TopologyChange(long topVer, int topSize);
}
/// <summary>
/// Data streamer implementation.
/// </summary>
internal class DataStreamerImpl<TK, TV> : PlatformDisposableTarget, IDataStreamer, IDataStreamer<TK, TV>
{
#pragma warning disable 0420
/** Policy: continue. */
internal const int PlcContinue = 0;
/** Policy: close. */
internal const int PlcClose = 1;
/** Policy: cancel and close. */
internal const int PlcCancelClose = 2;
/** Policy: flush. */
internal const int PlcFlush = 3;
/** Operation: update. */
private const int OpUpdate = 1;
/** Operation: set receiver. */
private const int OpReceiver = 2;
/** Cache name. */
private readonly string _cacheName;
/** Lock. */
private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
/** Closed event. */
private readonly ManualResetEventSlim _closedEvt = new ManualResetEventSlim(false);
/** Close future. */
private readonly Future<object> _closeFut = new Future<object>();
/** GC handle to this streamer. */
private readonly long _hnd;
/** Topology version. */
private long _topVer;
/** Topology size. */
private int _topSize = 1;
/** Buffer send size. */
private volatile int _bufSndSize;
/** Current data streamer batch. */
private volatile DataStreamerBatch<TK, TV> _batch;
/** Flusher. */
private readonly Flusher<TK, TV> _flusher;
/** Receiver. */
private volatile IStreamReceiver<TK, TV> _rcv;
/** Receiver handle. */
private long _rcvHnd;
/** Receiver binary mode. */
private readonly bool _keepBinary;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="cacheName">Cache name.</param>
/// <param name="keepBinary">Binary flag.</param>
public DataStreamerImpl(IUnmanagedTarget target, Marshaller marsh, string cacheName, bool keepBinary)
: base(target, marsh)
{
_cacheName = cacheName;
_keepBinary = keepBinary;
// Create empty batch.
_batch = new DataStreamerBatch<TK, TV>();
// Allocate GC handle so that this data streamer could be easily dereferenced from native code.
WeakReference thisRef = new WeakReference(this);
_hnd = marsh.Ignite.HandleRegistry.Allocate(thisRef);
// Start topology listening. This call will ensure that buffer size member is updated.
UU.DataStreamerListenTopology(target, _hnd);
// Membar to ensure fields initialization before leaving constructor.
Thread.MemoryBarrier();
// Start flusher after everything else is initialized.
_flusher = new Flusher<TK, TV>(thisRef);
_flusher.RunThread();
}
/** <inheritDoc /> */
public string CacheName
{
get { return _cacheName; }
}
/** <inheritDoc /> */
public bool AllowOverwrite
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerAllowOverwriteGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerAllowOverwriteSet(Target, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public bool SkipStore
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerSkipStoreGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerSkipStoreSet(Target, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeBufferSize
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerPerNodeBufferSizeGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerPerNodeBufferSizeSet(Target, value);
_bufSndSize = _topSize * value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeParallelOperations
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerPerNodeParallelOperationsGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerPerNodeParallelOperationsSet(Target, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public long AutoFlushFrequency
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return _flusher.Frequency;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
_flusher.Frequency = value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task Task
{
get
{
ThrowIfDisposed();
return _closeFut.Task;
}
}
/** <inheritDoc /> */
public IStreamReceiver<TK, TV> Receiver
{
get
{
ThrowIfDisposed();
return _rcv;
}
set
{
IgniteArgumentCheck.NotNull(value, "value");
var handleRegistry = Marshaller.Ignite.HandleRegistry;
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_rcv == value)
return;
var rcvHolder = new StreamReceiverHolder(value,
(rec, grid, cache, stream, keepBinary) =>
StreamReceiverHolder.InvokeReceiver((IStreamReceiver<TK, TV>) rec, grid, cache, stream,
keepBinary));
var rcvHnd0 = handleRegistry.Allocate(rcvHolder);
try
{
DoOutOp(OpReceiver, w =>
{
w.WriteLong(rcvHnd0);
w.WriteObject(rcvHolder);
});
}
catch (Exception)
{
handleRegistry.Release(rcvHnd0);
throw;
}
if (_rcv != null)
handleRegistry.Release(_rcvHnd);
_rcv = value;
_rcvHnd = rcvHnd0;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task AddData(TK key, TV val)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerEntry<TK, TV>(key, val), 1);
}
/** <inheritDoc /> */
public Task AddData(KeyValuePair<TK, TV> pair)
{
ThrowIfDisposed();
return Add0(new DataStreamerEntry<TK, TV>(pair.Key, pair.Value), 1);
}
/** <inheritDoc /> */
public Task AddData(ICollection<KeyValuePair<TK, TV>> entries)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(entries, "entries");
return Add0(entries, entries.Count);
}
/** <inheritDoc /> */
public Task RemoveData(TK key)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerRemoveEntry<TK>(key), 1);
}
/** <inheritDoc /> */
public void TryFlush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, false, PlcFlush);
}
/** <inheritDoc /> */
public void Flush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, true, PlcFlush);
else
{
// Batch is null, i.e. data streamer is closing. Wait for close to complete.
_closedEvt.Wait();
}
}
/** <inheritDoc /> */
public void Close(bool cancel)
{
_flusher.Stop();
while (true)
{
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 == null)
{
// Wait for concurrent close to finish.
_closedEvt.Wait();
return;
}
if (Flush0(batch0, true, cancel ? PlcCancelClose : PlcClose))
{
_closeFut.OnDone(null, null);
_rwLock.EnterWriteLock();
try
{
base.Dispose(true);
if (_rcv != null)
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd);
_closedEvt.Set();
}
finally
{
_rwLock.ExitWriteLock();
}
Marshaller.Ignite.HandleRegistry.Release(_hnd);
break;
}
}
}
/** <inheritDoc /> */
public IDataStreamer<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_keepBinary)
{
var result = this as IDataStreamer<TK1, TV1>;
if (result == null)
throw new InvalidOperationException(
"Can't change type of binary streamer. WithKeepBinary has been called on an instance of " +
"binary streamer with incompatible generic arguments.");
return result;
}
return new DataStreamerImpl<TK1, TV1>(UU.ProcessorDataStreamer(Marshaller.Ignite.InteropProcessor,
_cacheName, true), Marshaller, _cacheName, true);
}
/** <inheritDoc /> */
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void Dispose(bool disposing)
{
if (disposing)
Close(false); // Normal dispose: do not cancel
else
{
// Finalizer: just close Java streamer
try
{
if (_batch != null)
_batch.Send(this, PlcCancelClose);
}
// ReSharper disable once EmptyGeneralCatchClause
catch (Exception)
{
// Finalizers should never throw
}
Marshaller.Ignite.HandleRegistry.Release(_hnd, true);
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd, true);
}
base.Dispose(false);
}
/** <inheritDoc /> */
~DataStreamerImpl()
{
Dispose(false);
}
/** <inheritDoc /> */
public void TopologyChange(long topVer, int topSize)
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_topVer < topVer)
{
_topVer = topVer;
_topSize = topSize > 0 ? topSize : 1; // Do not set to 0 to avoid 0 buffer size.
_bufSndSize = _topSize * UU.DataStreamerPerNodeBufferSizeGet(Target);
}
}
finally
{
_rwLock.ExitWriteLock();
}
}
/// <summary>
/// Internal add/remove routine.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="cnt">Items count.</param>
/// <returns>Future.</returns>
private Task Add0(object val, int cnt)
{
int bufSndSize0 = _bufSndSize;
Debug.Assert(bufSndSize0 > 0);
while (true)
{
var batch0 = _batch;
if (batch0 == null)
throw new InvalidOperationException("Data streamer is stopped.");
int size = batch0.Add(val, cnt);
if (size == -1)
{
// Batch is blocked, perform CAS.
Interlocked.CompareExchange(ref _batch,
new DataStreamerBatch<TK, TV>(batch0), batch0);
continue;
}
if (size >= bufSndSize0)
// Batch is too big, schedule flush.
Flush0(batch0, false, PlcContinue);
return batch0.Task;
}
}
/// <summary>
/// Internal flush routine.
/// </summary>
/// <param name="curBatch"></param>
/// <param name="wait">Whether to wait for flush to complete.</param>
/// <param name="plc">Whether this is the last batch.</param>
/// <returns>Whether this call was able to CAS previous batch</returns>
private bool Flush0(DataStreamerBatch<TK, TV> curBatch, bool wait, int plc)
{
// 1. Try setting new current batch to help further adders.
bool res = Interlocked.CompareExchange(ref _batch,
(plc == PlcContinue || plc == PlcFlush) ?
new DataStreamerBatch<TK, TV>(curBatch) : null, curBatch) == curBatch;
// 2. Perform actual send.
curBatch.Send(this, plc);
if (wait)
// 3. Wait for all futures to finish.
curBatch.AwaitCompletion();
return res;
}
/// <summary>
/// Start write.
/// </summary>
/// <returns>Writer.</returns>
internal void Update(Action<BinaryWriter> action)
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
DoOutOp(OpUpdate, action);
}
finally
{
_rwLock.ExitReadLock();
}
}
/// <summary>
/// Flusher.
/// </summary>
private class Flusher<TK1, TV1>
{
/** State: running. */
private const int StateRunning = 0;
/** State: stopping. */
private const int StateStopping = 1;
/** State: stopped. */
private const int StateStopped = 2;
/** Data streamer. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private readonly WeakReference _ldrRef;
/** Finish flag. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private int _state;
/** Flush frequency. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private long _freq;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ldrRef">Data streamer weak reference..</param>
public Flusher(WeakReference ldrRef)
{
_ldrRef = ldrRef;
lock (this)
{
_state = StateRunning;
}
}
/// <summary>
/// Main flusher routine.
/// </summary>
private void Run()
{
bool force = false;
long curFreq = 0;
try
{
while (true)
{
if (curFreq > 0 || force)
{
var ldr = _ldrRef.Target as DataStreamerImpl<TK1, TV1>;
if (ldr == null)
return;
ldr.TryFlush();
force = false;
}
lock (this)
{
// Stop immediately.
if (_state == StateStopping)
return;
if (curFreq == _freq)
{
// Frequency is unchanged
if (curFreq == 0)
// Just wait for a second and re-try.
Monitor.Wait(this, 1000);
else
{
// Calculate remaining time.
DateTime now = DateTime.Now;
long ticks;
try
{
ticks = now.AddMilliseconds(curFreq).Ticks - now.Ticks;
if (ticks > int.MaxValue)
ticks = int.MaxValue;
}
catch (ArgumentOutOfRangeException)
{
// Handle possible overflow.
ticks = int.MaxValue;
}
Monitor.Wait(this, TimeSpan.FromTicks(ticks));
}
}
else
{
if (curFreq != 0)
force = true;
curFreq = _freq;
}
}
}
}
finally
{
// Let streamer know about stop.
lock (this)
{
_state = StateStopped;
Monitor.PulseAll(this);
}
}
}
/// <summary>
/// Frequency.
/// </summary>
public long Frequency
{
get
{
return Interlocked.Read(ref _freq);
}
set
{
lock (this)
{
if (_freq != value)
{
_freq = value;
Monitor.PulseAll(this);
}
}
}
}
/// <summary>
/// Stop flusher.
/// </summary>
public void Stop()
{
lock (this)
{
if (_state == StateRunning)
{
_state = StateStopping;
Monitor.PulseAll(this);
}
while (_state != StateStopped)
Monitor.Wait(this);
}
}
/// <summary>
/// Runs the flusher thread.
/// </summary>
public void RunThread()
{
new Thread(Run).Start();
}
}
#pragma warning restore 0420
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// 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 Google Inc. 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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Google.ProtocolBuffers.Collections;
namespace Google.ProtocolBuffers {
/// <summary>
/// Represents a single field in an UnknownFieldSet.
///
/// An UnknownField consists of five lists of values. The lists correspond
/// to the five "wire types" used in the protocol buffer binary format.
/// The wire type of each field can be determined from the encoded form alone,
/// without knowing the field's declared type. So, we are able to parse
/// unknown values at least this far and separate them. Normally, only one
/// of the five lists will contain any values, since it is impossible to
/// define a valid message type that declares two different types for the
/// same field number. However, the code is designed to allow for the case
/// where the same unknown field number is encountered using multiple different
/// wire types.
///
/// UnknownField is an immutable class. To construct one, you must use an
/// UnknownField.Builder.
/// </summary>
public sealed class UnknownField {
private static readonly UnknownField defaultInstance = CreateBuilder().Build();
private readonly ReadOnlyCollection<ulong> varintList;
private readonly ReadOnlyCollection<uint> fixed32List;
private readonly ReadOnlyCollection<ulong> fixed64List;
private readonly ReadOnlyCollection<ByteString> lengthDelimitedList;
private readonly ReadOnlyCollection<UnknownFieldSet> groupList;
private UnknownField(ReadOnlyCollection<ulong> varintList,
ReadOnlyCollection<uint> fixed32List,
ReadOnlyCollection<ulong> fixed64List,
ReadOnlyCollection<ByteString> lengthDelimitedList,
ReadOnlyCollection<UnknownFieldSet> groupList) {
this.varintList = varintList;
this.fixed32List = fixed32List;
this.fixed64List = fixed64List;
this.lengthDelimitedList = lengthDelimitedList;
this.groupList = groupList;
}
public static UnknownField DefaultInstance {
get { return defaultInstance; }
}
/// <summary>
/// The list of varint values for this field.
/// </summary>
public IList<ulong> VarintList {
get { return varintList; }
}
/// <summary>
/// The list of fixed32 values for this field.
/// </summary>
public IList<uint> Fixed32List {
get { return fixed32List; }
}
/// <summary>
/// The list of fixed64 values for this field.
/// </summary>
public IList<ulong> Fixed64List {
get { return fixed64List; }
}
/// <summary>
/// The list of length-delimited values for this field.
/// </summary>
public IList<ByteString> LengthDelimitedList {
get { return lengthDelimitedList; }
}
/// <summary>
/// The list of embedded group values for this field. These
/// are represented using UnknownFieldSets rather than Messages
/// since the group's type is presumably unknown.
/// </summary>
public IList<UnknownFieldSet> GroupList {
get { return groupList; }
}
public override bool Equals(object other) {
if (ReferenceEquals(this, other)) {
return true;
}
UnknownField otherField = other as UnknownField;
return otherField != null
&& Lists.Equals(varintList, otherField.varintList)
&& Lists.Equals(fixed32List, otherField.fixed32List)
&& Lists.Equals(fixed64List, otherField.fixed64List)
&& Lists.Equals(lengthDelimitedList, otherField.lengthDelimitedList)
&& Lists.Equals(groupList, otherField.groupList);
}
public override int GetHashCode() {
int hash = 43;
hash = hash * 47 + Lists.GetHashCode(varintList);
hash = hash * 47 + Lists.GetHashCode(fixed32List);
hash = hash * 47 + Lists.GetHashCode(fixed64List);
hash = hash * 47 + Lists.GetHashCode(lengthDelimitedList);
hash = hash * 47 + Lists.GetHashCode(groupList);
return hash;
}
/// <summary>
/// Constructs a new Builder.
/// </summary>
public static Builder CreateBuilder() {
return new Builder();
}
/// <summary>
/// Constructs a new Builder and initializes it to a copy of <paramref name="copyFrom"/>.
/// </summary>
public static Builder CreateBuilder(UnknownField copyFrom) {
return new Builder().MergeFrom(copyFrom);
}
/// <summary>
/// Serializes the field, including the field number, and writes it to
/// <paramref name="output"/>.
/// </summary>
public void WriteTo(int fieldNumber, CodedOutputStream output) {
foreach (ulong value in varintList) {
output.WriteUInt64(fieldNumber, value);
}
foreach (uint value in fixed32List) {
output.WriteFixed32(fieldNumber, value);
}
foreach (ulong value in fixed64List) {
output.WriteFixed64(fieldNumber, value);
}
foreach (ByteString value in lengthDelimitedList) {
output.WriteBytes(fieldNumber, value);
}
foreach (UnknownFieldSet value in groupList) {
output.WriteUnknownGroup(fieldNumber, value);
}
}
/// <summary>
/// Computes the number of bytes required to encode this field, including field
/// number.
/// </summary>
public int GetSerializedSize(int fieldNumber) {
int result = 0;
foreach (ulong value in varintList) {
result += CodedOutputStream.ComputeUInt64Size(fieldNumber, value);
}
foreach (uint value in fixed32List) {
result += CodedOutputStream.ComputeFixed32Size(fieldNumber, value);
}
foreach (ulong value in fixed64List) {
result += CodedOutputStream.ComputeFixed64Size(fieldNumber, value);
}
foreach (ByteString value in lengthDelimitedList) {
result += CodedOutputStream.ComputeBytesSize(fieldNumber, value);
}
foreach (UnknownFieldSet value in groupList) {
result += CodedOutputStream.ComputeUnknownGroupSize(fieldNumber, value);
}
return result;
}
/// <summary>
/// Serializes the length-delimited values of the field, including field
/// number, and writes them to <paramref name="output"/> using the MessageSet wire format.
/// </summary>
/// <param name="fieldNumber"></param>
/// <param name="output"></param>
public void WriteAsMessageSetExtensionTo(int fieldNumber, CodedOutputStream output) {
foreach (ByteString value in lengthDelimitedList) {
output.WriteRawMessageSetExtension(fieldNumber, value);
}
}
/// <summary>
/// Get the number of bytes required to encode this field, incuding field number,
/// using the MessageSet wire format.
/// </summary>
public int GetSerializedSizeAsMessageSetExtension(int fieldNumber) {
int result = 0;
foreach (ByteString value in lengthDelimitedList) {
result += CodedOutputStream.ComputeRawMessageSetExtensionSize(fieldNumber, value);
}
return result;
}
/// <summary>
/// Used to build instances of UnknownField.
/// </summary>
public sealed class Builder {
private List<ulong> varintList;
private List<uint> fixed32List;
private List<ulong> fixed64List;
private List<ByteString> lengthDelimitedList;
private List<UnknownFieldSet> groupList;
/// <summary>
/// Builds the field. After building, the builder is reset to an empty
/// state. (This is actually easier than making it unusable.)
/// </summary>
public UnknownField Build() {
return new UnknownField(MakeReadOnly(ref varintList),
MakeReadOnly(ref fixed32List),
MakeReadOnly(ref fixed64List),
MakeReadOnly(ref lengthDelimitedList),
MakeReadOnly(ref groupList));
}
/// <summary>
/// Merge the values in <paramref name="other" /> into this field. For each list
/// of values, <paramref name="other"/>'s values are append to the ones in this
/// field.
/// </summary>
public Builder MergeFrom(UnknownField other) {
varintList = AddAll(varintList, other.VarintList);
fixed32List = AddAll(fixed32List, other.Fixed32List);
fixed64List = AddAll(fixed64List, other.Fixed64List);
lengthDelimitedList = AddAll(lengthDelimitedList, other.LengthDelimitedList);
groupList = AddAll(groupList, other.GroupList);
return this;
}
/// <summary>
/// Returns a new list containing all of the given specified values from
/// both the <paramref name="current"/> and <paramref name="extras"/> lists.
/// If <paramref name="current" /> is null and <paramref name="extras"/> is empty,
/// null is returned. Otherwise, either a new list is created (if <paramref name="current" />
/// is null) or the elements of <paramref name="extras"/> are added to <paramref name="current" />.
/// </summary>
private static List<T> AddAll<T>(List<T> current, IList<T> extras)
{
if (extras.Count == 0) {
return current;
}
if (current == null) {
current = new List<T>(extras);
} else {
current.AddRange(extras);
}
return current;
}
/// <summary>
/// Clears the contents of this builder.
/// </summary>
public Builder Clear() {
varintList = null;
fixed32List = null;
fixed64List = null;
lengthDelimitedList = null;
groupList = null;
return this;
}
/// <summary>
/// Adds a varint value.
/// </summary>
[CLSCompliant(false)]
public Builder AddVarint(ulong value) {
varintList = Add(varintList, value);
return this;
}
/// <summary>
/// Adds a fixed32 value.
/// </summary>
[CLSCompliant(false)]
public Builder AddFixed32(uint value) {
fixed32List = Add(fixed32List, value);
return this;
}
/// <summary>
/// Adds a fixed64 value.
/// </summary>
[CLSCompliant(false)]
public Builder AddFixed64(ulong value) {
fixed64List = Add(fixed64List, value);
return this;
}
/// <summary>
/// Adds a length-delimited value.
/// </summary>
public Builder AddLengthDelimited(ByteString value) {
lengthDelimitedList = Add(lengthDelimitedList, value);
return this;
}
/// <summary>
/// Adds an embedded group.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public Builder AddGroup(UnknownFieldSet value) {
groupList = Add(groupList, value);
return this;
}
/// <summary>
/// Adds <paramref name="value"/> to the <paramref name="list"/>, creating
/// a new list if <paramref name="list"/> is null. The list is returned - either
/// the original reference or the new list.
/// </summary>
private static List<T> Add<T>(List<T> list, T value) {
if (list == null) {
list = new List<T>();
}
list.Add(value);
return list;
}
/// <summary>
/// Returns a read-only version of the given IList, and clears
/// the field used for <paramref name="list"/>. If the value
/// is null, an empty list is produced using Lists.Empty.
/// </summary>
/// <returns></returns>
private static ReadOnlyCollection<T> MakeReadOnly<T>(ref List<T> list) {
ReadOnlyCollection<T> ret = list == null ? Lists<T>.Empty : new ReadOnlyCollection<T>(list);
list = null;
return ret;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Stores;
using Nop.Services.Events;
namespace Nop.Services.Directory
{
/// <summary>
/// Country service
/// </summary>
public partial class CountryService : ICountryService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : show hidden records?
/// </remarks>
private const string COUNTRIES_ALL_KEY = "Nop.country.all-{0}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string COUNTRIES_PATTERN_KEY = "Nop.country.";
#endregion
#region Fields
private readonly IRepository<Country> _countryRepository;
private readonly IRepository<StoreMapping> _storeMappingRepository;
private readonly IStoreContext _storeContext;
private readonly CatalogSettings _catalogSettings;
private readonly IEventPublisher _eventPublisher;
private readonly ICacheManager _cacheManager;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="countryRepository">Country repository</param>
/// <param name="storeMappingRepository">Store mapping repository</param>
/// <param name="storeContext">Store context</param>
/// <param name="catalogSettings">Catalog settings</param>
/// <param name="eventPublisher">Event published</param>
public CountryService(ICacheManager cacheManager,
IRepository<Country> countryRepository,
IRepository<StoreMapping> storeMappingRepository,
IStoreContext storeContext,
CatalogSettings catalogSettings,
IEventPublisher eventPublisher)
{
this._cacheManager = cacheManager;
this._countryRepository = countryRepository;
this._storeMappingRepository = storeMappingRepository;
this._storeContext = storeContext;
this._catalogSettings = catalogSettings;
this._eventPublisher = eventPublisher;
}
#endregion
#region Methods
/// <summary>
/// Deletes a country
/// </summary>
/// <param name="country">Country</param>
public virtual void DeleteCountry(Country country)
{
if (country == null)
throw new ArgumentNullException("country");
_countryRepository.Delete(country);
_cacheManager.RemoveByPattern(COUNTRIES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(country);
}
/// <summary>
/// Gets all countries
/// </summary>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Country collection</returns>
public virtual IList<Country> GetAllCountries(bool showHidden = false)
{
string key = string.Format(COUNTRIES_ALL_KEY, showHidden);
return _cacheManager.Get(key, () =>
{
var query = _countryRepository.Table;
if (!showHidden)
query = query.Where(c => c.Published);
query = query.OrderBy(c => c.DisplayOrder).ThenBy(c => c.Name);
if (!showHidden && !_catalogSettings.IgnoreStoreLimitations)
{
//Store mapping
var currentStoreId = _storeContext.CurrentStore.Id;
query = from c in query
join sc in _storeMappingRepository.Table
on new { c1 = c.Id, c2 = "Country" } equals new { c1 = sc.EntityId, c2 = sc.EntityName } into c_sc
from sc in c_sc.DefaultIfEmpty()
where !c.LimitedToStores || currentStoreId == sc.StoreId
select c;
//only distinct entities (group by ID)
query = from c in query
group c by c.Id
into cGroup
orderby cGroup.Key
select cGroup.FirstOrDefault();
query = query.OrderBy(c => c.DisplayOrder).ThenBy(c => c.Name);
}
var countries = query.ToList();
return countries;
});
}
/// <summary>
/// Gets all countries that allow billing
/// </summary>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Country collection</returns>
public virtual IList<Country> GetAllCountriesForBilling(bool showHidden = false)
{
return GetAllCountries(showHidden).Where(c => c.AllowsBilling).ToList();
}
/// <summary>
/// Gets all countries that allow shipping
/// </summary>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Country collection</returns>
public virtual IList<Country> GetAllCountriesForShipping(bool showHidden = false)
{
return GetAllCountries(showHidden).Where(c => c.AllowsShipping).ToList();
}
/// <summary>
/// Gets a country
/// </summary>
/// <param name="countryId">Country identifier</param>
/// <returns>Country</returns>
public virtual Country GetCountryById(int countryId)
{
if (countryId == 0)
return null;
return _countryRepository.GetById(countryId);
}
/// <summary>
/// Get countries by identifiers
/// </summary>
/// <param name="countryIds">Country identifiers</param>
/// <returns>Countries</returns>
public virtual IList<Country> GetCountriesByIds(int[] countryIds)
{
if (countryIds == null || countryIds.Length == 0)
return new List<Country>();
var query = from c in _countryRepository.Table
where countryIds.Contains(c.Id)
select c;
var countries = query.ToList();
//sort by passed identifiers
var sortedCountries = new List<Country>();
foreach (int id in countryIds)
{
var country = countries.Find(x => x.Id == id);
if (country != null)
sortedCountries.Add(country);
}
return sortedCountries;
}
/// <summary>
/// Gets a country by two letter ISO code
/// </summary>
/// <param name="twoLetterIsoCode">Country two letter ISO code</param>
/// <returns>Country</returns>
public virtual Country GetCountryByTwoLetterIsoCode(string twoLetterIsoCode)
{
var query = from c in _countryRepository.Table
where c.TwoLetterIsoCode == twoLetterIsoCode
select c;
var country = query.FirstOrDefault();
return country;
}
/// <summary>
/// Gets a country by three letter ISO code
/// </summary>
/// <param name="threeLetterIsoCode">Country three letter ISO code</param>
/// <returns>Country</returns>
public virtual Country GetCountryByThreeLetterIsoCode(string threeLetterIsoCode)
{
var query = from c in _countryRepository.Table
where c.ThreeLetterIsoCode == threeLetterIsoCode
select c;
var country = query.FirstOrDefault();
return country;
}
/// <summary>
/// Inserts a country
/// </summary>
/// <param name="country">Country</param>
public virtual void InsertCountry(Country country)
{
if (country == null)
throw new ArgumentNullException("country");
_countryRepository.Insert(country);
_cacheManager.RemoveByPattern(COUNTRIES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(country);
}
/// <summary>
/// Updates the country
/// </summary>
/// <param name="country">Country</param>
public virtual void UpdateCountry(Country country)
{
if (country == null)
throw new ArgumentNullException("country");
_countryRepository.Update(country);
_cacheManager.RemoveByPattern(COUNTRIES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(country);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Helper class to hold a resolved expression and its
/// originating parameter.
/// </summary>
internal sealed class MshResolvedExpressionParameterAssociation
{
#region tracer
[TraceSource("MshResolvedExpressionParameterAssociation", "MshResolvedExpressionParameterAssociation")]
internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("MshResolvedExpressionParameterAssociation",
"MshResolvedExpressionParameterAssociation");
#endregion tracer
internal MshResolvedExpressionParameterAssociation(MshParameter parameter, PSPropertyExpression expression)
{
if (expression == null)
throw PSTraceSource.NewArgumentNullException(nameof(expression));
OriginatingParameter = parameter;
ResolvedExpression = expression;
}
internal PSPropertyExpression ResolvedExpression { get; }
internal MshParameter OriginatingParameter { get; }
}
internal static class AssociationManager
{
internal static List<MshResolvedExpressionParameterAssociation> SetupActiveProperties(List<MshParameter> rawMshParameterList,
PSObject target, PSPropertyExpressionFactory expressionFactory)
{
// check if we received properties from the command line
if (rawMshParameterList != null && rawMshParameterList.Count > 0)
{
return AssociationManager.ExpandParameters(rawMshParameterList, target);
}
// we did not get any properties:
// try to get properties from the default property set of the object
List<MshResolvedExpressionParameterAssociation> activeAssociationList = AssociationManager.ExpandDefaultPropertySet(target, expressionFactory);
if (activeAssociationList.Count > 0)
{
// we got a valid set of properties from the default property set..add computername for
// remoteobjects (if available)
if (PSObjectHelper.ShouldShowComputerNameProperty(target))
{
activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null,
new PSPropertyExpression(RemotingConstants.ComputerNameNoteProperty)));
}
return activeAssociationList;
}
// we failed to get anything from the default property set
// just get all the properties
activeAssociationList = AssociationManager.ExpandAll(target);
// Remove PSComputerName and PSShowComputerName from the display as needed.
AssociationManager.HandleComputerNameProperties(target, activeAssociationList);
return activeAssociationList;
}
internal static List<MshResolvedExpressionParameterAssociation> ExpandTableParameters(List<MshParameter> parameters, PSObject target)
{
List<MshResolvedExpressionParameterAssociation> retVal = new List<MshResolvedExpressionParameterAssociation>();
foreach (MshParameter par in parameters)
{
PSPropertyExpression expression = par.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
List<PSPropertyExpression> expandedExpressionList = expression.ResolveNames(target);
if (!expression.HasWildCardCharacters && expandedExpressionList.Count == 0)
{
// we did not find anything, mark as unresolved
retVal.Add(new MshResolvedExpressionParameterAssociation(par, expression));
}
foreach (PSPropertyExpression ex in expandedExpressionList)
{
retVal.Add(new MshResolvedExpressionParameterAssociation(par, ex));
}
}
return retVal;
}
internal static List<MshResolvedExpressionParameterAssociation> ExpandParameters(List<MshParameter> parameters, PSObject target)
{
List<MshResolvedExpressionParameterAssociation> retVal = new List<MshResolvedExpressionParameterAssociation>();
foreach (MshParameter par in parameters)
{
PSPropertyExpression expression = par.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
List<PSPropertyExpression> expandedExpressionList = expression.ResolveNames(target);
foreach (PSPropertyExpression ex in expandedExpressionList)
{
retVal.Add(new MshResolvedExpressionParameterAssociation(par, ex));
}
}
return retVal;
}
internal static List<MshResolvedExpressionParameterAssociation> ExpandDefaultPropertySet(PSObject target, PSPropertyExpressionFactory expressionFactory)
{
List<MshResolvedExpressionParameterAssociation> retVal = new List<MshResolvedExpressionParameterAssociation>();
List<PSPropertyExpression> expandedExpressionList = PSObjectHelper.GetDefaultPropertySet(target);
foreach (PSPropertyExpression ex in expandedExpressionList)
{
retVal.Add(new MshResolvedExpressionParameterAssociation(null, ex));
}
return retVal;
}
private static List<string> GetPropertyNamesFromView(PSObject source, PSMemberViewTypes viewType)
{
Collection<CollectionEntry<PSMemberInfo>> memberCollection =
PSObject.GetMemberCollection(viewType);
PSMemberInfoIntegratingCollection<PSMemberInfo> membersToSearch =
new PSMemberInfoIntegratingCollection<PSMemberInfo>(source, memberCollection);
ReadOnlyPSMemberInfoCollection<PSMemberInfo> matchedMembers =
membersToSearch.Match("*", PSMemberTypes.Properties);
List<string> retVal = new List<string>();
foreach (PSMemberInfo member in matchedMembers)
{
retVal.Add(member.Name);
}
return retVal;
}
internal static List<MshResolvedExpressionParameterAssociation> ExpandAll(PSObject target)
{
List<string> adaptedProperties = GetPropertyNamesFromView(target, PSMemberViewTypes.Adapted);
List<string> baseProperties = GetPropertyNamesFromView(target, PSMemberViewTypes.Base);
List<string> extendedProperties = GetPropertyNamesFromView(target, PSMemberViewTypes.Extended);
var displayedProperties = adaptedProperties.Count != 0 ? adaptedProperties : baseProperties;
displayedProperties.AddRange(extendedProperties);
Dictionary<string, object> duplicatesFinder = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
List<MshResolvedExpressionParameterAssociation> retVal = new List<MshResolvedExpressionParameterAssociation>();
foreach (string property in displayedProperties)
{
if (duplicatesFinder.TryAdd(property, null))
{
PSPropertyExpression expr = new PSPropertyExpression(property, true);
retVal.Add(new MshResolvedExpressionParameterAssociation(null, expr));
}
}
return retVal;
}
/// <summary>
/// Helper method to handle PSComputerName and PSShowComputerName properties from
/// the formating objects. If PSShowComputerName exists and is false, removes
/// PSComputerName from the display.
///
/// PSShowComputerName is an internal property..so this property is always
/// removed from the display.
/// </summary>
/// <param name="so"></param>
/// <param name="activeAssociationList"></param>
internal static void HandleComputerNameProperties(PSObject so, List<MshResolvedExpressionParameterAssociation> activeAssociationList)
{
if (so.Properties[RemotingConstants.ShowComputerNameNoteProperty] != null)
{
// always remove PSShowComputerName for the display. This is an internal property
// that should never be visible to the user.
Collection<MshResolvedExpressionParameterAssociation> itemsToRemove = new Collection<MshResolvedExpressionParameterAssociation>();
foreach (MshResolvedExpressionParameterAssociation cpProp in activeAssociationList)
{
if (cpProp.ResolvedExpression.ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty,
StringComparison.OrdinalIgnoreCase))
{
itemsToRemove.Add(cpProp);
break;
}
}
// remove computername for remoteobjects..only if PSShowComputerName property exists
// otherwise the PSComputerName property does not belong to a remote object:
// Ex: icm $s { gps } | select pscomputername --> In this case we want to show
// PSComputerName
if ((so.Properties[RemotingConstants.ComputerNameNoteProperty] != null) &&
(!PSObjectHelper.ShouldShowComputerNameProperty(so)))
{
foreach (MshResolvedExpressionParameterAssociation cpProp in activeAssociationList)
{
if (cpProp.ResolvedExpression.ToString().Equals(RemotingConstants.ComputerNameNoteProperty,
StringComparison.OrdinalIgnoreCase))
{
itemsToRemove.Add(cpProp);
break;
}
}
}
if (itemsToRemove.Count > 0)
{
foreach (MshResolvedExpressionParameterAssociation itemToRemove in itemsToRemove)
{
activeAssociationList.Remove(itemToRemove);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public partial class ImmutableHashSetTest : ImmutableSetTest
{
protected override bool IncludesGetHashCodeDerivative
{
get { return true; }
}
[Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
ImmutableHashSet<string>.Empty.WithComparer(StringComparer.Ordinal),
false,
new[] { "apple", "APPLE" },
new[] { "apple", "APPLE" });
this.CustomSortTestHelper(
ImmutableHashSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase),
false,
new[] { "apple", "APPLE" },
new[] { "apple" });
}
[Fact]
public void ChangeUnorderedEqualityComparer()
{
var ordinalSet = ImmutableHashSet<string>.Empty
.WithComparer(StringComparer.Ordinal)
.Add("apple")
.Add("APPLE");
Assert.Equal(2, ordinalSet.Count); // claimed count
Assert.False(ordinalSet.Contains("aPpLe"));
var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, ignoreCaseSet.Count);
Assert.True(ignoreCaseSet.Contains("aPpLe"));
}
[Fact]
public void ToSortTest()
{
var set = ImmutableHashSet<string>.Empty
.Add("apple")
.Add("APPLE");
var sorted = set.ToImmutableSortedSet();
CollectionAssertAreEquivalent(set.ToList(), sorted.ToList());
}
[Fact]
public void EnumeratorWithHashCollisionsTest()
{
var emptySet = this.EmptyTyped<int>().WithComparer(new BadHasher<int>());
this.EnumeratorTestHelper(emptySet, null, 3, 1, 5);
}
[Fact]
public void EnumeratorWithHashCollisionsTest_RefType()
{
var emptySet = this.EmptyTyped<string>().WithComparer(new BadHasher<string>());
this.EnumeratorTestHelper(emptySet, null, "c", "a", "e");
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableHashSet.Create<int>().Add(5);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
var set = ImmutableHashSet.Create<string>();
Assert.Equal(0, set.Count);
Assert.Same(EqualityComparer<string>.Default, set.KeyComparer);
set = ImmutableHashSet.Create<string>(comparer);
Assert.Equal(0, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableHashSet.Create("a");
Assert.Equal(1, set.Count);
Assert.Same(EqualityComparer<string>.Default, set.KeyComparer);
set = ImmutableHashSet.Create(comparer, "a");
Assert.Equal(1, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableHashSet.Create("a", "b");
Assert.Equal(2, set.Count);
Assert.Same(EqualityComparer<string>.Default, set.KeyComparer);
set = ImmutableHashSet.Create(comparer, "a", "b");
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableHashSet.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(EqualityComparer<string>.Default, set.KeyComparer);
set = ImmutableHashSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableHashSet.Create(default(string));
Assert.Equal(1, set.Count);
set = ImmutableHashSet.CreateRange(new[] { null, "a", null, "b" });
Assert.Equal(3, set.Count);
}
/// <summary>
/// Verifies the non-removal of an item that does not belong to the set,
/// but which happens to have a colliding hash code with another value
/// that *is* in the set.
/// </summary>
[Fact]
public void RemoveValuesFromCollidedHashCode()
{
var set = ImmutableHashSet.Create<int>(new BadHasher<int>(), 5, 6);
Assert.Same(set, set.Remove(2));
var setAfterRemovingFive = set.Remove(5);
Assert.Equal(1, setAfterRemovingFive.Count);
Assert.Equal(new[] { 6 }, setAfterRemovingFive);
}
/// <summary>
/// Verifies the non-removal of an item that does not belong to the set,
/// but which happens to have a colliding hash code with another value
/// that *is* in the set.
/// </summary>
[Fact]
public void RemoveValuesFromCollidedHashCode_RefType()
{
var set = ImmutableHashSet.Create<string>(new BadHasher<string>(), "a", "b");
Assert.Same(set, set.Remove("c"));
var setAfterRemovingA = set.Remove("a");
Assert.Equal(1, setAfterRemovingA.Count);
Assert.Equal(new[] { "b" }, setAfterRemovingA);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableHashSet.Create<string>());
ImmutableHashSet<int> set = ImmutableHashSet.Create(1, 2, 3);
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(set);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
int[] items = itemProperty.GetValue(info.Instance) as int[];
Assert.Equal(set, items);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableHashSet.Create<string>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void SymmetricExceptWithComparerTests()
{
var set = ImmutableHashSet.Create<string>("a").WithComparer(StringComparer.OrdinalIgnoreCase);
var otherCollection = new[] { "A" };
var expectedSet = new HashSet<string>(set, set.KeyComparer);
expectedSet.SymmetricExceptWith(otherCollection);
var actualSet = set.SymmetricExcept(otherCollection);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
}
protected override IImmutableSet<T> Empty<T>()
{
return ImmutableHashSet<T>.Empty;
}
protected ImmutableHashSet<T> EmptyTyped<T>()
{
return ImmutableHashSet<T>.Empty;
}
protected override ISet<T> EmptyMutable<T>()
{
return new HashSet<T>();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Configuration;
using System.Management.Automation.Internal;
using System.Reflection;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
namespace PSTests.Sequential
{
[TestCaseOrderer("TestOrder.TestCaseOrdering.PriorityOrderer", "powershell-tests")]
public class PowerShellPolicyFixture : IDisposable
{
private const string ConfigFileName = "powershell.config.json";
private readonly string systemWideConfigFile;
private readonly string currentUserConfigFile;
private readonly string systemWideConfigBackupFile;
private readonly string currentUserConfigBackupFile;
private readonly string systemWideConfigDirectory;
private readonly string currentUserConfigDirectory;
private readonly JsonSerializer serializer;
private readonly PowerShellPolicies systemWidePolicies;
private readonly PowerShellPolicies currentUserPolicies;
private readonly bool originalTestHookValue;
public PowerShellPolicyFixture()
{
systemWideConfigDirectory = Utils.DefaultPowerShellAppBase;
currentUserConfigDirectory = Utils.GetUserConfigurationDirectory();
if (!Directory.Exists(currentUserConfigDirectory))
{
// Create the CurrentUser config directory if it doesn't exist
Directory.CreateDirectory(currentUserConfigDirectory);
}
systemWideConfigFile = Path.Combine(systemWideConfigDirectory, ConfigFileName);
currentUserConfigFile = Path.Combine(currentUserConfigDirectory, ConfigFileName);
if (File.Exists(systemWideConfigFile))
{
systemWideConfigBackupFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
File.Move(systemWideConfigFile, systemWideConfigBackupFile);
}
if (File.Exists(currentUserConfigFile))
{
currentUserConfigBackupFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
File.Move(currentUserConfigFile, currentUserConfigBackupFile);
}
var settings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.None,
MaxDepth = 10,
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
};
serializer = JsonSerializer.Create(settings);
systemWidePolicies = new PowerShellPolicies()
{
ScriptExecution = new ScriptExecution() { ExecutionPolicy = "RemoteSigned", EnableScripts = true },
ScriptBlockLogging = new ScriptBlockLogging() { EnableScriptBlockInvocationLogging = true, EnableScriptBlockLogging = false },
ModuleLogging = new ModuleLogging() { EnableModuleLogging = false, ModuleNames = new string[] { "PSReadline", "PowerShellGet" } },
ProtectedEventLogging = new ProtectedEventLogging() { EnableProtectedEventLogging = false, EncryptionCertificate = new string[] { "Joe" } },
Transcription = new Transcription() { EnableInvocationHeader = true, EnableTranscripting = true, OutputDirectory = @"c:\tmp" },
UpdatableHelp = new UpdatableHelp() { DefaultSourcePath = @"f:\temp" },
ConsoleSessionConfiguration = new ConsoleSessionConfiguration() { EnableConsoleSessionConfiguration = true, ConsoleSessionConfigurationName = "name" }
};
currentUserPolicies = new PowerShellPolicies()
{
ScriptExecution = new ScriptExecution() { ExecutionPolicy = "RemoteSigned" },
ScriptBlockLogging = new ScriptBlockLogging() { EnableScriptBlockLogging = false },
ModuleLogging = new ModuleLogging() { EnableModuleLogging = false },
ProtectedEventLogging = new ProtectedEventLogging() { EncryptionCertificate = new string[] { "Joe" } }
};
// Set the test hook to disable policy caching
originalTestHookValue = InternalTestHooks.BypassGroupPolicyCaching;
InternalTestHooks.BypassGroupPolicyCaching = true;
}
public void Dispose()
{
CleanupConfigFiles();
if (systemWideConfigBackupFile != null)
{
File.Move(systemWideConfigBackupFile, systemWideConfigFile);
}
if (currentUserConfigBackupFile != null)
{
File.Move(currentUserConfigBackupFile, currentUserConfigFile);
}
InternalTestHooks.BypassGroupPolicyCaching = originalTestHookValue;
}
internal PowerShellPolicies SystemWidePolicies
{
get { return systemWidePolicies; }
}
internal PowerShellPolicies CurrentUserPolicies
{
get { return currentUserPolicies; }
}
#region Compare_Policy_Settings
internal void CompareScriptExecution(ScriptExecution a, ScriptExecution b)
{
if (a == null)
{
Assert.Null(b);
}
else
{
Assert.Equal(a.EnableScripts, b.EnableScripts);
Assert.Equal(a.ExecutionPolicy, b.ExecutionPolicy);
}
}
internal void CompareScriptBlockLogging(ScriptBlockLogging a, ScriptBlockLogging b)
{
if (a == null)
{
Assert.Null(b);
}
else
{
Assert.Equal(a.EnableScriptBlockInvocationLogging, b.EnableScriptBlockInvocationLogging);
Assert.Equal(a.EnableScriptBlockLogging, b.EnableScriptBlockLogging);
}
}
internal void CompareModuleLogging(ModuleLogging a, ModuleLogging b)
{
if (a == null)
{
Assert.Null(b);
}
else
{
Assert.Equal(a.EnableModuleLogging, b.EnableModuleLogging);
if (a.ModuleNames == null)
{
Assert.Null(b.ModuleNames);
}
else
{
Assert.Equal(a.ModuleNames.Length, b.ModuleNames.Length);
for (int i = 0; i < a.ModuleNames.Length; i++)
{
Assert.Equal(a.ModuleNames[i], b.ModuleNames[i]);
}
}
}
}
internal void CompareProtectedEventLogging(ProtectedEventLogging a, ProtectedEventLogging b)
{
if (a == null)
{
Assert.Null(b);
}
else
{
Assert.Equal(a.EnableProtectedEventLogging, b.EnableProtectedEventLogging);
if (a.EncryptionCertificate == null)
{
Assert.Null(b.EncryptionCertificate);
}
else
{
Assert.Equal(a.EncryptionCertificate.Length, b.EncryptionCertificate.Length);
for (int i = 0; i < a.EncryptionCertificate.Length; i++)
{
Assert.Equal(a.EncryptionCertificate[i], b.EncryptionCertificate[i]);
}
}
}
}
internal void CompareTranscription(Transcription a, Transcription b)
{
if (a == null)
{
Assert.Null(b);
}
else
{
Assert.Equal(a.EnableTranscripting, b.EnableTranscripting);
Assert.Equal(a.EnableInvocationHeader, b.EnableInvocationHeader);
Assert.Equal(a.OutputDirectory, b.OutputDirectory);
}
}
internal void CompareUpdatableHelp(UpdatableHelp a, UpdatableHelp b)
{
if (a == null)
{
Assert.Null(b);
}
else
{
Assert.Equal(a.DefaultSourcePath, b.DefaultSourcePath);
}
}
internal void CompareConsoleSessionConfiguration(ConsoleSessionConfiguration a, ConsoleSessionConfiguration b)
{
if (a == null)
{
Assert.Null(b);
}
else
{
Assert.Equal(a.EnableConsoleSessionConfiguration, b.EnableConsoleSessionConfiguration);
Assert.Equal(a.ConsoleSessionConfigurationName, b.ConsoleSessionConfigurationName);
}
}
internal void CompareTwoPolicies(PowerShellPolicies a, PowerShellPolicies b)
{
// Compare 'ScriptExecution' settings
CompareScriptExecution(a.ScriptExecution, b.ScriptExecution);
// Compare 'ScriptBlockLogging' settings
CompareScriptBlockLogging(a.ScriptBlockLogging, b.ScriptBlockLogging);
// Compare 'ModuleLogging' settings
CompareModuleLogging(a.ModuleLogging, b.ModuleLogging);
// Compare 'ProtectedEventLogging' settings
CompareProtectedEventLogging(a.ProtectedEventLogging, b.ProtectedEventLogging);
// Compare 'Transcription' settings
CompareTranscription(a.Transcription, b.Transcription);
// Compare 'UpdatableHelp' settings
CompareUpdatableHelp(a.UpdatableHelp, b.UpdatableHelp);
// Compare 'ConsoleSessionConfiguration' settings
CompareConsoleSessionConfiguration(a.ConsoleSessionConfiguration, b.ConsoleSessionConfiguration);
}
#endregion
#region Configuration_File_Setup
public void CleanupConfigFiles()
{
var maxPause = 10;
while (maxPause-- != 0 && (File.Exists(systemWideConfigFile) || File.Exists(currentUserConfigFile)))
{
var pause = false;
try
{
File.Delete(systemWideConfigFile);
}
catch (IOException)
{
pause = true;
}
try
{
File.Delete(currentUserConfigFile);
}
catch (IOException)
{
pause = true;
}
if (pause)
{
Thread.Sleep(5);
}
}
}
public void SetupConfigFile1()
{
CleanupConfigFiles();
// System wide config file has all policy settings
var systemWideConfig = new { ConsolePrompting = true, PowerShellPolicies = systemWidePolicies };
using (var streamWriter = new StreamWriter(systemWideConfigFile))
{
serializer.Serialize(streamWriter, systemWideConfig);
}
// Current user config file has partial policy settings
var currentUserConfig = new { DisablePromptToUpdateHelp = false, PowerShellPolicies = currentUserPolicies };
using (var streamWriter = new StreamWriter(currentUserConfigFile))
{
serializer.Serialize(streamWriter, currentUserConfig);
}
}
public void SetupConfigFile2()
{
CleanupConfigFiles();
// System wide config file has all policy settings
var systemWideConfig = new { ConsolePrompting = true, PowerShellPolicies = systemWidePolicies };
using (var streamWriter = new StreamWriter(systemWideConfigFile))
{
serializer.Serialize(streamWriter, systemWideConfig);
}
// Current user config file is empty
CreateEmptyFile(currentUserConfigFile);
}
public void SetupConfigFile3()
{
CleanupConfigFiles();
// System wide config file is empty
CreateEmptyFile(systemWideConfigFile);
// Current user config file has partial policy settings
var currentUserConfig = new { DisablePromptToUpdateHelp = false, PowerShellPolicies = currentUserPolicies };
using (var streamWriter = new StreamWriter(currentUserConfigFile))
{
serializer.Serialize(streamWriter, currentUserConfig);
}
}
public void SetupConfigFile4()
{
CleanupConfigFiles();
// System wide config file is empty
CreateEmptyFile(systemWideConfigFile);
// Current user config file is empty
CreateEmptyFile(currentUserConfigFile);
}
private void CreateEmptyFile(string fileName)
{
File.Create(fileName).Dispose();
}
#endregion
}
public class PowerShellPolicyTests : IClassFixture<PowerShellPolicyFixture>
{
private PowerShellPolicyFixture fixture;
public PowerShellPolicyTests(PowerShellPolicyFixture fixture)
{
this.fixture = fixture;
}
[Fact, TestPriority(1)]
public void PowerShellConfig_GetPowerShellPolicies_BothConfigFilesNotEmpty()
{
fixture.SetupConfigFile1();
var sysPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers);
var userPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser);
Assert.NotNull(sysPolicies);
Assert.NotNull(userPolicies);
fixture.CompareTwoPolicies(sysPolicies, fixture.SystemWidePolicies);
fixture.CompareTwoPolicies(userPolicies, fixture.CurrentUserPolicies);
}
[Fact, TestPriority(2)]
public void PowerShellConfig_GetPowerShellPolicies_EmptyUserConfig()
{
fixture.SetupConfigFile2();
var sysPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers);
var userPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser);
Assert.NotNull(sysPolicies);
Assert.Null(userPolicies);
fixture.CompareTwoPolicies(sysPolicies, fixture.SystemWidePolicies);
}
[Fact, TestPriority(3)]
public void PowerShellConfig_GetPowerShellPolicies_EmptySystemConfig()
{
fixture.SetupConfigFile3();
var sysPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers);
var userPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser);
Assert.Null(sysPolicies);
Assert.NotNull(userPolicies);
fixture.CompareTwoPolicies(userPolicies, fixture.CurrentUserPolicies);
}
[Fact, TestPriority(4)]
public void PowerShellConfig_GetPowerShellPolicies_BothConfigFilesEmpty()
{
fixture.SetupConfigFile4();
var sysPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers);
var userPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser);
Assert.Null(sysPolicies);
Assert.Null(userPolicies);
}
[Fact, TestPriority(5)]
public void PowerShellConfig_GetPowerShellPolicies_BothConfigFilesNotExist()
{
fixture.CleanupConfigFiles();
var sysPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers);
var userPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser);
Assert.Null(sysPolicies);
Assert.Null(userPolicies);
}
[Fact, TestPriority(6)]
public void Utils_GetPolicySetting_BothConfigFilesNotEmpty()
{
fixture.SetupConfigFile1();
ScriptExecution scriptExecution;
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.SystemWideOnlyConfig);
fixture.CompareScriptExecution(scriptExecution, fixture.SystemWidePolicies.ScriptExecution);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.CurrentUserOnlyConfig);
fixture.CompareScriptExecution(scriptExecution, fixture.CurrentUserPolicies.ScriptExecution);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareScriptExecution(scriptExecution, fixture.SystemWidePolicies.ScriptExecution);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareScriptExecution(scriptExecution, fixture.CurrentUserPolicies.ScriptExecution);
ScriptBlockLogging scriptBlockLogging;
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, fixture.SystemWidePolicies.ScriptBlockLogging);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, fixture.CurrentUserPolicies.ScriptBlockLogging);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, fixture.SystemWidePolicies.ScriptBlockLogging);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, fixture.CurrentUserPolicies.ScriptBlockLogging);
ModuleLogging moduleLogging;
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareModuleLogging(moduleLogging, fixture.SystemWidePolicies.ModuleLogging);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareModuleLogging(moduleLogging, fixture.CurrentUserPolicies.ModuleLogging);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareModuleLogging(moduleLogging, fixture.SystemWidePolicies.ModuleLogging);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareModuleLogging(moduleLogging, fixture.CurrentUserPolicies.ModuleLogging);
ProtectedEventLogging protectedEventLogging;
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, fixture.SystemWidePolicies.ProtectedEventLogging);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, fixture.CurrentUserPolicies.ProtectedEventLogging);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, fixture.SystemWidePolicies.ProtectedEventLogging);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, fixture.CurrentUserPolicies.ProtectedEventLogging);
// The CurrentUser config doesn't contain any settings for 'Transcription', 'UpdatableHelp' and 'ConsoleSessionConfiguration'
Transcription transcription;
transcription = Utils.GetPolicySetting<Transcription>(Utils.SystemWideOnlyConfig);
fixture.CompareTranscription(transcription, fixture.SystemWidePolicies.Transcription);
transcription = Utils.GetPolicySetting<Transcription>(Utils.CurrentUserOnlyConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareTranscription(transcription, fixture.SystemWidePolicies.Transcription);
transcription = Utils.GetPolicySetting<Transcription>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareTranscription(transcription, fixture.SystemWidePolicies.Transcription);
UpdatableHelp updatableHelp;
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideOnlyConfig);
fixture.CompareUpdatableHelp(updatableHelp, fixture.SystemWidePolicies.UpdatableHelp);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.CurrentUserOnlyConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareUpdatableHelp(updatableHelp, fixture.SystemWidePolicies.UpdatableHelp);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareUpdatableHelp(updatableHelp, fixture.SystemWidePolicies.UpdatableHelp);
ConsoleSessionConfiguration consoleSessionConfiguration;
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.SystemWideOnlyConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, fixture.SystemWidePolicies.ConsoleSessionConfiguration);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserOnlyConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, fixture.SystemWidePolicies.ConsoleSessionConfiguration);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, fixture.SystemWidePolicies.ConsoleSessionConfiguration);
}
[Fact, TestPriority(7)]
public void Utils_GetPolicySetting_EmptyUserConfig()
{
fixture.SetupConfigFile2();
// The CurrentUser config is empty
ScriptExecution scriptExecution;
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.SystemWideOnlyConfig);
fixture.CompareScriptExecution(scriptExecution, fixture.SystemWidePolicies.ScriptExecution);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.CurrentUserOnlyConfig);
fixture.CompareScriptExecution(scriptExecution, null);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareScriptExecution(scriptExecution, fixture.SystemWidePolicies.ScriptExecution);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareScriptExecution(scriptExecution, fixture.SystemWidePolicies.ScriptExecution);
ScriptBlockLogging scriptBlockLogging;
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, fixture.SystemWidePolicies.ScriptBlockLogging);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, null);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, fixture.SystemWidePolicies.ScriptBlockLogging);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, fixture.SystemWidePolicies.ScriptBlockLogging);
ModuleLogging moduleLogging;
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareModuleLogging(moduleLogging, fixture.SystemWidePolicies.ModuleLogging);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareModuleLogging(moduleLogging, null);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareModuleLogging(moduleLogging, fixture.SystemWidePolicies.ModuleLogging);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareModuleLogging(moduleLogging, fixture.SystemWidePolicies.ModuleLogging);
ProtectedEventLogging protectedEventLogging;
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, fixture.SystemWidePolicies.ProtectedEventLogging);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, null);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, fixture.SystemWidePolicies.ProtectedEventLogging);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, fixture.SystemWidePolicies.ProtectedEventLogging);
Transcription transcription;
transcription = Utils.GetPolicySetting<Transcription>(Utils.SystemWideOnlyConfig);
fixture.CompareTranscription(transcription, fixture.SystemWidePolicies.Transcription);
transcription = Utils.GetPolicySetting<Transcription>(Utils.CurrentUserOnlyConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareTranscription(transcription, fixture.SystemWidePolicies.Transcription);
transcription = Utils.GetPolicySetting<Transcription>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareTranscription(transcription, fixture.SystemWidePolicies.Transcription);
UpdatableHelp updatableHelp;
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideOnlyConfig);
fixture.CompareUpdatableHelp(updatableHelp, fixture.SystemWidePolicies.UpdatableHelp);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.CurrentUserOnlyConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareUpdatableHelp(updatableHelp, fixture.SystemWidePolicies.UpdatableHelp);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareUpdatableHelp(updatableHelp, fixture.SystemWidePolicies.UpdatableHelp);
ConsoleSessionConfiguration consoleSessionConfiguration;
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.SystemWideOnlyConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, fixture.SystemWidePolicies.ConsoleSessionConfiguration);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserOnlyConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, fixture.SystemWidePolicies.ConsoleSessionConfiguration);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, fixture.SystemWidePolicies.ConsoleSessionConfiguration);
}
[Fact, TestPriority(8)]
public void Utils_GetPolicySetting_EmptySystemConfig()
{
fixture.SetupConfigFile3();
// The SystemWide config is empty
ScriptExecution scriptExecution;
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.SystemWideOnlyConfig);
fixture.CompareScriptExecution(scriptExecution, null);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.CurrentUserOnlyConfig);
fixture.CompareScriptExecution(scriptExecution, fixture.CurrentUserPolicies.ScriptExecution);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareScriptExecution(scriptExecution, fixture.CurrentUserPolicies.ScriptExecution);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareScriptExecution(scriptExecution, fixture.CurrentUserPolicies.ScriptExecution);
ScriptBlockLogging scriptBlockLogging;
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, null);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, fixture.CurrentUserPolicies.ScriptBlockLogging);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, fixture.CurrentUserPolicies.ScriptBlockLogging);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, fixture.CurrentUserPolicies.ScriptBlockLogging);
ModuleLogging moduleLogging;
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareModuleLogging(moduleLogging, null);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareModuleLogging(moduleLogging, fixture.CurrentUserPolicies.ModuleLogging);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareModuleLogging(moduleLogging, fixture.CurrentUserPolicies.ModuleLogging);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareModuleLogging(moduleLogging, fixture.CurrentUserPolicies.ModuleLogging);
ProtectedEventLogging protectedEventLogging;
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, null);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, fixture.CurrentUserPolicies.ProtectedEventLogging);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, fixture.CurrentUserPolicies.ProtectedEventLogging);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, fixture.CurrentUserPolicies.ProtectedEventLogging);
// The CurrentUser config doesn't contain any settings for 'Transcription', 'UpdatableHelp' and 'ConsoleSessionConfiguration'
Transcription transcription;
transcription = Utils.GetPolicySetting<Transcription>(Utils.SystemWideOnlyConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.CurrentUserOnlyConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareTranscription(transcription, null);
UpdatableHelp updatableHelp;
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideOnlyConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.CurrentUserOnlyConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
ConsoleSessionConfiguration consoleSessionConfiguration;
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.SystemWideOnlyConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserOnlyConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
}
[Fact, TestPriority(9)]
public void Utils_GetPolicySetting_BothConfigFilesEmpty()
{
fixture.SetupConfigFile4();
// Both config files are empty
ScriptExecution scriptExecution;
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.SystemWideOnlyConfig);
fixture.CompareScriptExecution(scriptExecution, null);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.CurrentUserOnlyConfig);
fixture.CompareScriptExecution(scriptExecution, null);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareScriptExecution(scriptExecution, null);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareScriptExecution(scriptExecution, null);
ScriptBlockLogging scriptBlockLogging;
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, null);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, null);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, null);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, null);
ModuleLogging moduleLogging;
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareModuleLogging(moduleLogging, null);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareModuleLogging(moduleLogging, null);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareModuleLogging(moduleLogging, null);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareModuleLogging(moduleLogging, null);
ProtectedEventLogging protectedEventLogging;
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, null);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, null);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, null);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, null);
// The CurrentUser config doesn't contain any settings for 'Transcription', 'UpdatableHelp' and 'ConsoleSessionConfiguration'
Transcription transcription;
transcription = Utils.GetPolicySetting<Transcription>(Utils.SystemWideOnlyConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.CurrentUserOnlyConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareTranscription(transcription, null);
UpdatableHelp updatableHelp;
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideOnlyConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.CurrentUserOnlyConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
ConsoleSessionConfiguration consoleSessionConfiguration;
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.SystemWideOnlyConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserOnlyConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
}
[Fact, TestPriority(10)]
public void Utils_GetPolicySetting_BothConfigFilesNotExist()
{
fixture.CleanupConfigFiles();
// Both config files don't exist
ScriptExecution scriptExecution;
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.SystemWideOnlyConfig);
fixture.CompareScriptExecution(scriptExecution, null);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.CurrentUserOnlyConfig);
fixture.CompareScriptExecution(scriptExecution, null);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareScriptExecution(scriptExecution, null);
scriptExecution = Utils.GetPolicySetting<ScriptExecution>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareScriptExecution(scriptExecution, null);
ScriptBlockLogging scriptBlockLogging;
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, null);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, null);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, null);
scriptBlockLogging = Utils.GetPolicySetting<ScriptBlockLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareScriptBlockLogging(scriptBlockLogging, null);
ModuleLogging moduleLogging;
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareModuleLogging(moduleLogging, null);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareModuleLogging(moduleLogging, null);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareModuleLogging(moduleLogging, null);
moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareModuleLogging(moduleLogging, null);
ProtectedEventLogging protectedEventLogging;
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.SystemWideOnlyConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, null);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.CurrentUserOnlyConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, null);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, null);
protectedEventLogging = Utils.GetPolicySetting<ProtectedEventLogging>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareProtectedEventLogging(protectedEventLogging, null);
// The CurrentUser config doesn't contain any settings for 'Transcription', 'UpdatableHelp' and 'ConsoleSessionConfiguration'
Transcription transcription;
transcription = Utils.GetPolicySetting<Transcription>(Utils.SystemWideOnlyConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.CurrentUserOnlyConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareTranscription(transcription, null);
transcription = Utils.GetPolicySetting<Transcription>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareTranscription(transcription, null);
UpdatableHelp updatableHelp;
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideOnlyConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.CurrentUserOnlyConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
updatableHelp = Utils.GetPolicySetting<UpdatableHelp>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareUpdatableHelp(updatableHelp, null);
ConsoleSessionConfiguration consoleSessionConfiguration;
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.SystemWideOnlyConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserOnlyConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.SystemWideThenCurrentUserConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
consoleSessionConfiguration = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserThenSystemWideConfig);
fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Collections.Immutable
{
/// <summary>
/// A node in the AVL tree storing key/value pairs with Int32 keys.
/// </summary>
/// <remarks>
/// This is a trimmed down version of <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/>
/// with <c>TKey</c> fixed to be <see cref="int"/>. This avoids multiple interface-based dispatches while examining
/// each node in the tree during a lookup: an interface call to the comparer's <see cref="IComparer{T}.Compare"/> method,
/// and then an interface call to <see cref="int"/>'s <see cref="IComparable{T}.CompareTo"/> method as part of
/// the <see cref="T:System.Collections.Generic.GenericComparer`1"/>'s <see cref="IComparer{T}.Compare"/> implementation.
/// </remarks>
[DebuggerDisplay("{_key} = {_value}")]
internal sealed partial class SortedInt32KeyNode<TValue> : IBinaryTree
{
/// <summary>
/// The default empty node.
/// </summary>
internal static readonly SortedInt32KeyNode<TValue> EmptyNode = new SortedInt32KeyNode<TValue>();
/// <summary>
/// The Int32 key associated with this node.
/// </summary>
private readonly int _key;
/// <summary>
/// The value associated with this node.
/// </summary>
private readonly TValue _value;
/// <summary>
/// A value indicating whether this node has been frozen (made immutable).
/// </summary>
/// <remarks>
/// Nodes must be frozen before ever being observed by a wrapping collection type
/// to protect collections from further mutations.
/// </remarks>
private bool _frozen;
/// <summary>
/// The depth of the tree beneath this node.
/// </summary>
private byte _height; // AVL tree height <= ~1.44 * log2(numNodes + 2)
/// <summary>
/// The left tree.
/// </summary>
private SortedInt32KeyNode<TValue> _left;
/// <summary>
/// The right tree.
/// </summary>
private SortedInt32KeyNode<TValue> _right;
/// <summary>
/// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is pre-frozen.
/// </summary>
private SortedInt32KeyNode()
{
_frozen = true; // the empty node is *always* frozen.
}
/// <summary>
/// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is not yet frozen.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <param name="frozen">Whether this node is prefrozen.</param>
private SortedInt32KeyNode(int key, TValue value, SortedInt32KeyNode<TValue> left, SortedInt32KeyNode<TValue> right, bool frozen = false)
{
Requires.NotNull(left, nameof(left));
Requires.NotNull(right, nameof(right));
Debug.Assert(!frozen || (left._frozen && right._frozen));
_key = key;
_value = value;
_left = left;
_right = right;
_frozen = frozen;
_height = checked((byte)(1 + Math.Max(left._height, right._height)));
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty { get { return _left == null; } }
/// <summary>
/// Gets the height of the tree beneath this node.
/// </summary>
public int Height { get { return _height; } }
/// <summary>
/// Gets the left branch of this node.
/// </summary>
public SortedInt32KeyNode<TValue> Left { get { return _left; } }
/// <summary>
/// Gets the right branch of this node.
/// </summary>
public SortedInt32KeyNode<TValue> Right { get { return _right; } }
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Left { get { return _left; } }
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Right { get { return _right; } }
/// <summary>
/// Gets the number of elements contained by this node and below.
/// </summary>
int IBinaryTree.Count
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Gets the value represented by the current node.
/// </summary>
public KeyValuePair<int, TValue> Value
{
get { return new KeyValuePair<int, TValue>(_key, _value); }
}
/// <summary>
/// Gets the values.
/// </summary>
internal IEnumerable<TValue> Values
{
get
{
foreach (var pair in this)
{
yield return pair.Value;
}
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
internal SortedInt32KeyNode<TValue> SetItem(int key, TValue value, IEqualityComparer<TValue> valueComparer, out bool replacedExistingValue, out bool mutated)
{
Requires.NotNull(valueComparer, nameof(valueComparer));
return this.SetOrAdd(key, value, valueComparer, true, out replacedExistingValue, out mutated);
}
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
internal SortedInt32KeyNode<TValue> Remove(int key, out bool mutated)
{
return this.RemoveRecursive(key, out mutated);
}
/// <summary>
/// Gets the value or default.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The value.</returns>
[Pure]
internal TValue GetValueOrDefault(int key)
{
var match = this.Search(key);
return match.IsEmpty ? default(TValue) : match._value;
}
/// <summary>
/// Tries to get the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>True if the key was found.</returns>
[Pure]
internal bool TryGetValue(int key, out TValue value)
{
var match = this.Search(key);
if (match.IsEmpty)
{
value = default(TValue);
return false;
}
else
{
value = match._value;
return true;
}
}
/// <summary>
/// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes.
/// </summary>
internal void Freeze(Action<KeyValuePair<int, TValue>> freezeAction = null)
{
// If this node is frozen, all its descendants must already be frozen.
if (!_frozen)
{
freezeAction?.Invoke(new KeyValuePair<int, TValue>(_key, _value));
_left.Freeze(freezeAction);
_right.Freeze(freezeAction);
_frozen = true;
}
}
/// <summary>
/// AVL rotate left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static SortedInt32KeyNode<TValue> RotateLeft(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._right.IsEmpty)
{
return tree;
}
var right = tree._right;
return right.Mutate(left: tree.Mutate(right: right._left));
}
/// <summary>
/// AVL rotate right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static SortedInt32KeyNode<TValue> RotateRight(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._left.IsEmpty)
{
return tree;
}
var left = tree._left;
return left.Mutate(right: tree.Mutate(left: left._right));
}
/// <summary>
/// AVL rotate double-left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static SortedInt32KeyNode<TValue> DoubleLeft(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._right.IsEmpty)
{
return tree;
}
SortedInt32KeyNode<TValue> rotatedRightChild = tree.Mutate(right: RotateRight(tree._right));
return RotateLeft(rotatedRightChild);
}
/// <summary>
/// AVL rotate double-right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static SortedInt32KeyNode<TValue> DoubleRight(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._left.IsEmpty)
{
return tree;
}
SortedInt32KeyNode<TValue> rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left));
return RotateRight(rotatedLeftChild);
}
/// <summary>
/// Returns a value indicating whether the tree is in balance.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns>
[Pure]
private static int Balance(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return tree._right._height - tree._left._height;
}
/// <summary>
/// Determines whether the specified tree is right heavy.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>
/// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>.
/// </returns>
[Pure]
private static bool IsRightHeavy(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) >= 2;
}
/// <summary>
/// Determines whether the specified tree is left heavy.
/// </summary>
[Pure]
private static bool IsLeftHeavy(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) <= -2;
}
/// <summary>
/// Balances the specified tree.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>A balanced tree.</returns>
[Pure]
private static SortedInt32KeyNode<TValue> MakeBalanced(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (IsRightHeavy(tree))
{
return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree);
}
if (IsLeftHeavy(tree))
{
return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree);
}
return tree;
}
/// <summary>
/// Adds the specified key. Callers are expected to have validated arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="overwriteExistingValue">if <c>true</c>, an existing key=value pair will be overwritten with the new one.</param>
/// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
private SortedInt32KeyNode<TValue> SetOrAdd(int key, TValue value, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated)
{
// Arg validation skipped in this private method because it's recursive and the tax
// of revalidating arguments on each recursive call is significant.
// All our callers are therefore required to have done input validation.
replacedExistingValue = false;
if (this.IsEmpty)
{
mutated = true;
return new SortedInt32KeyNode<TValue>(key, value, this, this);
}
else
{
SortedInt32KeyNode<TValue> result = this;
if (key > _key)
{
var newRight = _right.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
else if (key < _key)
{
var newLeft = _left.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
if (valueComparer.Equals(_value, value))
{
mutated = false;
return this;
}
else if (overwriteExistingValue)
{
mutated = true;
replacedExistingValue = true;
result = new SortedInt32KeyNode<TValue>(key, value, _left, _right);
}
else
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key));
}
}
return mutated ? MakeBalanced(result) : result;
}
}
/// <summary>
/// Removes the specified key. Callers are expected to validate arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
private SortedInt32KeyNode<TValue> RemoveRecursive(int key, out bool mutated)
{
if (this.IsEmpty)
{
mutated = false;
return this;
}
else
{
SortedInt32KeyNode<TValue> result = this;
if (key == _key)
{
// We have a match.
mutated = true;
// If this is a leaf, just remove it
// by returning Empty. If we have only one child,
// replace the node with the child.
if (_right.IsEmpty && _left.IsEmpty)
{
result = EmptyNode;
}
else if (_right.IsEmpty && !_left.IsEmpty)
{
result = _left;
}
else if (!_right.IsEmpty && _left.IsEmpty)
{
result = _right;
}
else
{
// We have two children. Remove the next-highest node and replace
// this node with it.
var successor = _right;
while (!successor._left.IsEmpty)
{
successor = successor._left;
}
bool dummyMutated;
var newRight = _right.Remove(successor._key, out dummyMutated);
result = successor.Mutate(left: _left, right: newRight);
}
}
else if (key < _key)
{
var newLeft = _left.Remove(key, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
var newRight = _right.Remove(key, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
return result.IsEmpty ? result : MakeBalanced(result);
}
}
/// <summary>
/// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node
/// with the described changes.
/// </summary>
/// <param name="left">The left branch of the mutated node.</param>
/// <param name="right">The right branch of the mutated node.</param>
/// <returns>The mutated (or created) node.</returns>
private SortedInt32KeyNode<TValue> Mutate(SortedInt32KeyNode<TValue> left = null, SortedInt32KeyNode<TValue> right = null)
{
if (_frozen)
{
return new SortedInt32KeyNode<TValue>(_key, _value, left ?? _left, right ?? _right);
}
else
{
if (left != null)
{
_left = left;
}
if (right != null)
{
_right = right;
}
_height = checked((byte)(1 + Math.Max(_left._height, _right._height)));
return this;
}
}
/// <summary>
/// Searches the specified key. Callers are expected to validate arguments.
/// </summary>
/// <param name="key">The key.</param>
[Pure]
private SortedInt32KeyNode<TValue> Search(int key)
{
if (this.IsEmpty || key == _key)
{
return this;
}
if (key > _key)
{
return _right.Search(key);
}
return _left.Search(key);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Zer0.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
namespace Mosa.FileSystem.VFS
{
/// <summary>
/// Implements the virtual file system service for the kernel.
/// </summary>
/// <remarks>
/// The virtual file system service provides the root '/' naming namespace for
/// other nodes and services.
/// </remarks>
public sealed class VirtualFileSystem : IFileSystem, IFileSystemService
{
#region Data members
/// <summary>
/// The virtual root directory.
/// </summary>
private static DirectoryNode rootDirectory;
/// <summary>
/// Root entry of the virtual file system.
/// </summary>
private static DirectoryEntry rootNode;
#endregion Data members
#region Construction
private VirtualFileSystem()
{
}
/// <summary>
/// Initializes a new instance of the virtual file system.
/// </summary>
public static void Setup()
{
rootDirectory = new DirectoryNode(null);
rootNode = DirectoryEntry.AllocateRoot(rootDirectory);
// FIXME: Add an entry of the virtual file system to /system/filesystems
}
#endregion Construction
#region Static Properties
// FIXME: This is not a good idea and should be removed (using by DirectoryEntry.CurrentDirectory, if no one is set) once
// we have a process structure supporting jails.
/// <summary>
///
/// </summary>
public static DirectoryEntry RootDirectoryEntry
{
get
{
return rootNode;
}
}
#endregion Static Properties
#region Static Methods
/// <summary>
/// Checks if the caller has access to the inode
/// </summary>
/// <param name="path">The resource to check permissions for.</param>
/// <param name="mode"></param>
/// <returns>True if the requested access mode combination is available to the immediate caller. If any one requested access mode is not available, the result is false.</returns>
public static bool Access(string path, AccessMode mode)
{
DirectoryEntry entry = PathResolver.Resolve(rootNode, ref path, PathResolutionFlags.DoNotThrowNotFoundException);
if (null != entry)
{
return AccessCheck.Perform(entry, mode, AccessCheckFlags.NoThrow);
}
return false;
}
/// <summary>
/// Creates a new node in the (virtual) filesystem.
/// </summary>
/// <param name="path">The path to create.</param>
/// <param name="type">The type of the node to create.</param>
/// <param name="settings">Settings used to initialize the node.</param>
/// <param name="access">Requests the specified access modes on the created object.</param>
/// <param name="share">Requests the specified sharing settings on the object.</param>
/// <returns>The created filesystem object.</returns>
/// <remarks>
/// This function creates new nodes in the virtual filesystem. In contrast to *nix this call
/// creates all node types, e.g. files, directories, devices and more. Specific types may
/// require additional settings, which are specified in a settings object passed as the third
/// parameter.
/// </remarks>
public static object Create(string path, VfsNodeType type, object settings, System.IO.FileAccess access, System.IO.FileShare share)
{
// Retrieve the parent directory
DirectoryEntry parent = PathResolver.Resolve(rootNode, ref path, PathResolutionFlags.RetrieveParent);
// Check if the caller has write access in the directory
AccessCheck.Perform(parent, AccessMode.Write, AccessCheckFlags.None);
// Yes, we do have write access. Create the new vfs node
IVfsNode node = parent.Node.Create(path, type, settings);
// FIXME: Assert(null != node);
DirectoryEntry entry = DirectoryEntry.Allocate(parent, path, node);
// FIXME: Fix the permissions for this call. *nix does this using its bitmasks, Win32 through its huge CreateFile API.
return node.Open(access, share);
}
/// <summary>
/// Changes the current directory in the thread execution block.
/// </summary>
/// <param name="path">The path to change to. This path may be relative or absolute.</param>
public static void ChangeDirectory(string path)
{
DirectoryEntry entry = PathResolver.Resolve(rootNode, ref path);
// FIXME: Set the current directory in the thread execution block
}
/// <summary>
/// Deletes the named node from the filesystem.
/// </summary>
/// <param name="path">The path, which identifies a node.</param>
public static void Delete(string path)
{
DirectoryEntry entry = PathResolver.Resolve(rootNode, ref path, PathResolutionFlags.DoNotThrowNotFoundException);
if (null != entry)
{
AccessCheck.Perform(entry, AccessMode.Delete, AccessCheckFlags.None);
//entry.Node.Delete();
entry.Parent.Node.Delete(entry.Node, entry);
entry.Release();
}
}
/// <summary>
/// Mounts a new file system.
/// </summary>
/// <param name="source">The source of the filesystem. This is usually a device name, but can also be another directory.</param>
/// <param name="target">The path including the name of the mount point, where to mount the new filesystem.</param>
public static void Mount(string source, string target)
{
// Retrieve the parent directory of the mount
DirectoryEntry parent = PathResolver.Resolve(rootNode, ref target, PathResolutionFlags.RetrieveParent);
if (parent == null)
throw new System.ArgumentException();
IFileSystem root = FileSystemFactory.CreateFileSystem(source);
if (root == null)
throw new System.ArgumentException();
PathSplitter path = new PathSplitter(target);
DirectoryEntry.Allocate(parent, path.Last, root.Root);
}
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <param name="access"></param>
/// <param name="share"></param>
/// <returns></returns>
public static object Open(string path, System.IO.FileAccess access, System.IO.FileShare share)
{
DirectoryEntry entry = PathResolver.Resolve(rootNode, ref path);
/* HINT:
*
* 1. Do we really need to pass the FileShare flags down to the inode?
* 2. Shouldn't we have some sort of lock deamon governing shared access?
*
* Ansers:
* 1. Yes.
* 2. Yes and no. A lock deamon would only work for local filesystems. For imported
* ones we need to notify the server of the sharing lock anyway, so that the IVfsNode
* (acting as a client to the server) is the best place to do it without giving the
* lock deamon knowledge of all file sharing protocols (afp, smb, ftp, name it.)
* 3. The inode may reject the file sharing requests. We do want to represent devices
* and sync objects in the VFS, which means *they* need to decide if the flags are
* applicable.
*
*/
// FIXME: Perform access checks on the DirectoryEntry/IVfsNode.
AccessMode modeFlags = AccessMode.Exists;
switch (access)
{
case System.IO.FileAccess.Read:
modeFlags = AccessMode.Read;
break;
case System.IO.FileAccess.Write:
modeFlags = AccessMode.Write;
break;
case System.IO.FileAccess.ReadWrite:
modeFlags = AccessMode.Read | AccessMode.Write;
break;
}
AccessCheck.Perform(entry, modeFlags, AccessCheckFlags.None);
return entry.Node.Open(access, share);
}
/// <summary>
///
/// </summary>
/// <param name="old"></param>
/// <param name="newname"></param>
public static void Rename(string old, string newname)
{
// FIXME:
throw new System.NotImplementedException();
}
// <summary>
// Resolves the path evaluating all symbolic links.
// </summary>
// <param name="path">The path to resolve.</param>
// <returns>The absolute path, which is actually represented by the given path.</returns>
// <exception cref="System.IO.FileNotFoundException">A component of the path or a symbolic link in the path do not name an existing file system entry.</exception>
// <exception cref="System.IO.PathTooLongException">The path represented by the given path is too long or symbolic links produced infinite recursion.</exception>
// <exception cref="System.IO.IOException">An I/O exception occurred while resolving the path.</exception>
// <exception cref="System.Security.SecurityException">A fragment of the path could not be traversed due to a denied search permission.</exception>
//public static String ResolvePath(String path)
//{
// DirectoryEntry entry = PathResolver.Resolve(_rootNode, ref path);
// String pathSep = new String(Path.DirectorySeparatorChar, 1);
// String result = String.Concat(pathSep, entry.Name);
// while (!Object.ReferenceEquals(entry, entry.Parent))
// {
// entry = entry.Parent;
// result = String.Concat(pathSep, entry.Name, result);
// }
// return result;
//}
/// <summary>
/// Retrieves a
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static object Stat(string path)
{
// FIXME
// throw new NotImplementedException();
return null;
}
/// <summary>
/// Unmounts the filesystem rooted at the given path.
/// </summary>
/// <param name="path">The path identifying the filesystem to unmount.</param>
/// <remarks>
/// In contrast to Posix this does not have to be the root directory of the filesystem. Any path in the filesystem will unmount the
/// entire tree.
/// </remarks>
/// FIXME: Which exceptions can be thrown.
/// FIXME: How is the current directory handled? What if it is inside the FS tree being unmounted.
/// FIXME: We need to check the FS tree for in use status and throw an InvalidOperationException?
public static void Unmount(string path)
{
// FIXME:
throw new System.NotImplementedException();
}
#endregion Static Methods
#region IFileSystem Members
bool IFileSystem.IsReadOnly { get { return false; } }
IVfsNode IFileSystem.Root
{
get { return VirtualFileSystem.rootDirectory; }
}
#endregion IFileSystem Members
#region IFileSystemService Members
GenericFileSystemSettings IFileSystemService.SettingsType { get { return null; } }
bool IFileSystemService.Mount()
{
// Even though we're a file system, we are not mountable.
return false;
}
bool IFileSystemService.Format(GenericFileSystemSettings settings)
{
// We do not support formatting.
throw new System.NotSupportedException();
}
#endregion IFileSystemService Members
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using ga = Google.Api;
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.ServiceManagement.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedServiceManagerClientTest
{
[xunit::FactAttribute]
public void GetServiceRequestObject()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceRequest request = new GetServiceRequest
{
ServiceName = "service_named5df05d5",
};
ManagedService expectedResponse = new ManagedService
{
ServiceName = "service_named5df05d5",
ProducerProjectId = "producer_project_id18d0012a",
};
mockGrpcClient.Setup(x => x.GetService(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ManagedService response = client.GetService(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServiceRequestObjectAsync()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceRequest request = new GetServiceRequest
{
ServiceName = "service_named5df05d5",
};
ManagedService expectedResponse = new ManagedService
{
ServiceName = "service_named5df05d5",
ProducerProjectId = "producer_project_id18d0012a",
};
mockGrpcClient.Setup(x => x.GetServiceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ManagedService>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ManagedService responseCallSettings = await client.GetServiceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ManagedService responseCancellationToken = await client.GetServiceAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetService()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceRequest request = new GetServiceRequest
{
ServiceName = "service_named5df05d5",
};
ManagedService expectedResponse = new ManagedService
{
ServiceName = "service_named5df05d5",
ProducerProjectId = "producer_project_id18d0012a",
};
mockGrpcClient.Setup(x => x.GetService(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ManagedService response = client.GetService(request.ServiceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServiceAsync()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceRequest request = new GetServiceRequest
{
ServiceName = "service_named5df05d5",
};
ManagedService expectedResponse = new ManagedService
{
ServiceName = "service_named5df05d5",
ProducerProjectId = "producer_project_id18d0012a",
};
mockGrpcClient.Setup(x => x.GetServiceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ManagedService>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ManagedService responseCallSettings = await client.GetServiceAsync(request.ServiceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ManagedService responseCancellationToken = await client.GetServiceAsync(request.ServiceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetServiceConfigRequestObject()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceConfigRequest request = new GetServiceConfigRequest
{
ServiceName = "service_named5df05d5",
ConfigId = "config_id908a73d1",
View = GetServiceConfigRequest.Types.ConfigView.Full,
};
ga::Service expectedResponse = new ga::Service
{
Name = "name1c9368b0",
Title = "title17dbd3d5",
Apis = { new wkt::Api(), },
Types_ = { new wkt::Type(), },
Enums = { new wkt::Enum(), },
Documentation = new ga::Documentation(),
Backend = new ga::Backend(),
Http = new ga::Http(),
Quota = new ga::Quota(),
Authentication = new ga::Authentication(),
Context = new ga::Context(),
Usage = new ga::Usage(),
Endpoints = { new ga::Endpoint(), },
#pragma warning disable CS0612
ConfigVersion = 2430367190U,
#pragma warning restore CS0612
Control = new ga::Control(),
ProducerProjectId = "producer_project_id18d0012a",
Logs =
{
new ga::LogDescriptor(),
},
Metrics =
{
new ga::MetricDescriptor(),
},
MonitoredResources =
{
new ga::MonitoredResourceDescriptor(),
},
Billing = new ga::Billing(),
Logging = new ga::Logging(),
Monitoring = new ga::Monitoring(),
SystemParameters = new ga::SystemParameters(),
Id = "id74b70bb8",
SourceInfo = new ga::SourceInfo(),
};
mockGrpcClient.Setup(x => x.GetServiceConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ga::Service response = client.GetServiceConfig(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServiceConfigRequestObjectAsync()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceConfigRequest request = new GetServiceConfigRequest
{
ServiceName = "service_named5df05d5",
ConfigId = "config_id908a73d1",
View = GetServiceConfigRequest.Types.ConfigView.Full,
};
ga::Service expectedResponse = new ga::Service
{
Name = "name1c9368b0",
Title = "title17dbd3d5",
Apis = { new wkt::Api(), },
Types_ = { new wkt::Type(), },
Enums = { new wkt::Enum(), },
Documentation = new ga::Documentation(),
Backend = new ga::Backend(),
Http = new ga::Http(),
Quota = new ga::Quota(),
Authentication = new ga::Authentication(),
Context = new ga::Context(),
Usage = new ga::Usage(),
Endpoints = { new ga::Endpoint(), },
#pragma warning disable CS0612
ConfigVersion = 2430367190U,
#pragma warning restore CS0612
Control = new ga::Control(),
ProducerProjectId = "producer_project_id18d0012a",
Logs =
{
new ga::LogDescriptor(),
},
Metrics =
{
new ga::MetricDescriptor(),
},
MonitoredResources =
{
new ga::MonitoredResourceDescriptor(),
},
Billing = new ga::Billing(),
Logging = new ga::Logging(),
Monitoring = new ga::Monitoring(),
SystemParameters = new ga::SystemParameters(),
Id = "id74b70bb8",
SourceInfo = new ga::SourceInfo(),
};
mockGrpcClient.Setup(x => x.GetServiceConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::Service>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ga::Service responseCallSettings = await client.GetServiceConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::Service responseCancellationToken = await client.GetServiceConfigAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetServiceConfig()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceConfigRequest request = new GetServiceConfigRequest
{
ServiceName = "service_named5df05d5",
ConfigId = "config_id908a73d1",
View = GetServiceConfigRequest.Types.ConfigView.Full,
};
ga::Service expectedResponse = new ga::Service
{
Name = "name1c9368b0",
Title = "title17dbd3d5",
Apis = { new wkt::Api(), },
Types_ = { new wkt::Type(), },
Enums = { new wkt::Enum(), },
Documentation = new ga::Documentation(),
Backend = new ga::Backend(),
Http = new ga::Http(),
Quota = new ga::Quota(),
Authentication = new ga::Authentication(),
Context = new ga::Context(),
Usage = new ga::Usage(),
Endpoints = { new ga::Endpoint(), },
#pragma warning disable CS0612
ConfigVersion = 2430367190U,
#pragma warning restore CS0612
Control = new ga::Control(),
ProducerProjectId = "producer_project_id18d0012a",
Logs =
{
new ga::LogDescriptor(),
},
Metrics =
{
new ga::MetricDescriptor(),
},
MonitoredResources =
{
new ga::MonitoredResourceDescriptor(),
},
Billing = new ga::Billing(),
Logging = new ga::Logging(),
Monitoring = new ga::Monitoring(),
SystemParameters = new ga::SystemParameters(),
Id = "id74b70bb8",
SourceInfo = new ga::SourceInfo(),
};
mockGrpcClient.Setup(x => x.GetServiceConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ga::Service response = client.GetServiceConfig(request.ServiceName, request.ConfigId, request.View);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServiceConfigAsync()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceConfigRequest request = new GetServiceConfigRequest
{
ServiceName = "service_named5df05d5",
ConfigId = "config_id908a73d1",
View = GetServiceConfigRequest.Types.ConfigView.Full,
};
ga::Service expectedResponse = new ga::Service
{
Name = "name1c9368b0",
Title = "title17dbd3d5",
Apis = { new wkt::Api(), },
Types_ = { new wkt::Type(), },
Enums = { new wkt::Enum(), },
Documentation = new ga::Documentation(),
Backend = new ga::Backend(),
Http = new ga::Http(),
Quota = new ga::Quota(),
Authentication = new ga::Authentication(),
Context = new ga::Context(),
Usage = new ga::Usage(),
Endpoints = { new ga::Endpoint(), },
#pragma warning disable CS0612
ConfigVersion = 2430367190U,
#pragma warning restore CS0612
Control = new ga::Control(),
ProducerProjectId = "producer_project_id18d0012a",
Logs =
{
new ga::LogDescriptor(),
},
Metrics =
{
new ga::MetricDescriptor(),
},
MonitoredResources =
{
new ga::MonitoredResourceDescriptor(),
},
Billing = new ga::Billing(),
Logging = new ga::Logging(),
Monitoring = new ga::Monitoring(),
SystemParameters = new ga::SystemParameters(),
Id = "id74b70bb8",
SourceInfo = new ga::SourceInfo(),
};
mockGrpcClient.Setup(x => x.GetServiceConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::Service>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ga::Service responseCallSettings = await client.GetServiceConfigAsync(request.ServiceName, request.ConfigId, request.View, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::Service responseCancellationToken = await client.GetServiceConfigAsync(request.ServiceName, request.ConfigId, request.View, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateServiceConfigRequestObject()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateServiceConfigRequest request = new CreateServiceConfigRequest
{
ServiceName = "service_named5df05d5",
ServiceConfig = new ga::Service(),
};
ga::Service expectedResponse = new ga::Service
{
Name = "name1c9368b0",
Title = "title17dbd3d5",
Apis = { new wkt::Api(), },
Types_ = { new wkt::Type(), },
Enums = { new wkt::Enum(), },
Documentation = new ga::Documentation(),
Backend = new ga::Backend(),
Http = new ga::Http(),
Quota = new ga::Quota(),
Authentication = new ga::Authentication(),
Context = new ga::Context(),
Usage = new ga::Usage(),
Endpoints = { new ga::Endpoint(), },
#pragma warning disable CS0612
ConfigVersion = 2430367190U,
#pragma warning restore CS0612
Control = new ga::Control(),
ProducerProjectId = "producer_project_id18d0012a",
Logs =
{
new ga::LogDescriptor(),
},
Metrics =
{
new ga::MetricDescriptor(),
},
MonitoredResources =
{
new ga::MonitoredResourceDescriptor(),
},
Billing = new ga::Billing(),
Logging = new ga::Logging(),
Monitoring = new ga::Monitoring(),
SystemParameters = new ga::SystemParameters(),
Id = "id74b70bb8",
SourceInfo = new ga::SourceInfo(),
};
mockGrpcClient.Setup(x => x.CreateServiceConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ga::Service response = client.CreateServiceConfig(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateServiceConfigRequestObjectAsync()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateServiceConfigRequest request = new CreateServiceConfigRequest
{
ServiceName = "service_named5df05d5",
ServiceConfig = new ga::Service(),
};
ga::Service expectedResponse = new ga::Service
{
Name = "name1c9368b0",
Title = "title17dbd3d5",
Apis = { new wkt::Api(), },
Types_ = { new wkt::Type(), },
Enums = { new wkt::Enum(), },
Documentation = new ga::Documentation(),
Backend = new ga::Backend(),
Http = new ga::Http(),
Quota = new ga::Quota(),
Authentication = new ga::Authentication(),
Context = new ga::Context(),
Usage = new ga::Usage(),
Endpoints = { new ga::Endpoint(), },
#pragma warning disable CS0612
ConfigVersion = 2430367190U,
#pragma warning restore CS0612
Control = new ga::Control(),
ProducerProjectId = "producer_project_id18d0012a",
Logs =
{
new ga::LogDescriptor(),
},
Metrics =
{
new ga::MetricDescriptor(),
},
MonitoredResources =
{
new ga::MonitoredResourceDescriptor(),
},
Billing = new ga::Billing(),
Logging = new ga::Logging(),
Monitoring = new ga::Monitoring(),
SystemParameters = new ga::SystemParameters(),
Id = "id74b70bb8",
SourceInfo = new ga::SourceInfo(),
};
mockGrpcClient.Setup(x => x.CreateServiceConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::Service>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ga::Service responseCallSettings = await client.CreateServiceConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::Service responseCancellationToken = await client.CreateServiceConfigAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateServiceConfig()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateServiceConfigRequest request = new CreateServiceConfigRequest
{
ServiceName = "service_named5df05d5",
ServiceConfig = new ga::Service(),
};
ga::Service expectedResponse = new ga::Service
{
Name = "name1c9368b0",
Title = "title17dbd3d5",
Apis = { new wkt::Api(), },
Types_ = { new wkt::Type(), },
Enums = { new wkt::Enum(), },
Documentation = new ga::Documentation(),
Backend = new ga::Backend(),
Http = new ga::Http(),
Quota = new ga::Quota(),
Authentication = new ga::Authentication(),
Context = new ga::Context(),
Usage = new ga::Usage(),
Endpoints = { new ga::Endpoint(), },
#pragma warning disable CS0612
ConfigVersion = 2430367190U,
#pragma warning restore CS0612
Control = new ga::Control(),
ProducerProjectId = "producer_project_id18d0012a",
Logs =
{
new ga::LogDescriptor(),
},
Metrics =
{
new ga::MetricDescriptor(),
},
MonitoredResources =
{
new ga::MonitoredResourceDescriptor(),
},
Billing = new ga::Billing(),
Logging = new ga::Logging(),
Monitoring = new ga::Monitoring(),
SystemParameters = new ga::SystemParameters(),
Id = "id74b70bb8",
SourceInfo = new ga::SourceInfo(),
};
mockGrpcClient.Setup(x => x.CreateServiceConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ga::Service response = client.CreateServiceConfig(request.ServiceName, request.ServiceConfig);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateServiceConfigAsync()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateServiceConfigRequest request = new CreateServiceConfigRequest
{
ServiceName = "service_named5df05d5",
ServiceConfig = new ga::Service(),
};
ga::Service expectedResponse = new ga::Service
{
Name = "name1c9368b0",
Title = "title17dbd3d5",
Apis = { new wkt::Api(), },
Types_ = { new wkt::Type(), },
Enums = { new wkt::Enum(), },
Documentation = new ga::Documentation(),
Backend = new ga::Backend(),
Http = new ga::Http(),
Quota = new ga::Quota(),
Authentication = new ga::Authentication(),
Context = new ga::Context(),
Usage = new ga::Usage(),
Endpoints = { new ga::Endpoint(), },
#pragma warning disable CS0612
ConfigVersion = 2430367190U,
#pragma warning restore CS0612
Control = new ga::Control(),
ProducerProjectId = "producer_project_id18d0012a",
Logs =
{
new ga::LogDescriptor(),
},
Metrics =
{
new ga::MetricDescriptor(),
},
MonitoredResources =
{
new ga::MonitoredResourceDescriptor(),
},
Billing = new ga::Billing(),
Logging = new ga::Logging(),
Monitoring = new ga::Monitoring(),
SystemParameters = new ga::SystemParameters(),
Id = "id74b70bb8",
SourceInfo = new ga::SourceInfo(),
};
mockGrpcClient.Setup(x => x.CreateServiceConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::Service>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
ga::Service responseCallSettings = await client.CreateServiceConfigAsync(request.ServiceName, request.ServiceConfig, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::Service responseCancellationToken = await client.CreateServiceConfigAsync(request.ServiceName, request.ServiceConfig, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetServiceRolloutRequestObject()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceRolloutRequest request = new GetServiceRolloutRequest
{
ServiceName = "service_named5df05d5",
RolloutId = "rollout_id174e7821",
};
Rollout expectedResponse = new Rollout
{
RolloutId = "rollout_id174e7821",
CreateTime = new wkt::Timestamp(),
CreatedBy = "created_by206bd4da",
Status = Rollout.Types.RolloutStatus.Cancelled,
TrafficPercentStrategy = new Rollout.Types.TrafficPercentStrategy(),
ServiceName = "service_named5df05d5",
DeleteServiceStrategy = new Rollout.Types.DeleteServiceStrategy(),
};
mockGrpcClient.Setup(x => x.GetServiceRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
Rollout response = client.GetServiceRollout(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServiceRolloutRequestObjectAsync()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceRolloutRequest request = new GetServiceRolloutRequest
{
ServiceName = "service_named5df05d5",
RolloutId = "rollout_id174e7821",
};
Rollout expectedResponse = new Rollout
{
RolloutId = "rollout_id174e7821",
CreateTime = new wkt::Timestamp(),
CreatedBy = "created_by206bd4da",
Status = Rollout.Types.RolloutStatus.Cancelled,
TrafficPercentStrategy = new Rollout.Types.TrafficPercentStrategy(),
ServiceName = "service_named5df05d5",
DeleteServiceStrategy = new Rollout.Types.DeleteServiceStrategy(),
};
mockGrpcClient.Setup(x => x.GetServiceRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Rollout>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
Rollout responseCallSettings = await client.GetServiceRolloutAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Rollout responseCancellationToken = await client.GetServiceRolloutAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetServiceRollout()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceRolloutRequest request = new GetServiceRolloutRequest
{
ServiceName = "service_named5df05d5",
RolloutId = "rollout_id174e7821",
};
Rollout expectedResponse = new Rollout
{
RolloutId = "rollout_id174e7821",
CreateTime = new wkt::Timestamp(),
CreatedBy = "created_by206bd4da",
Status = Rollout.Types.RolloutStatus.Cancelled,
TrafficPercentStrategy = new Rollout.Types.TrafficPercentStrategy(),
ServiceName = "service_named5df05d5",
DeleteServiceStrategy = new Rollout.Types.DeleteServiceStrategy(),
};
mockGrpcClient.Setup(x => x.GetServiceRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
Rollout response = client.GetServiceRollout(request.ServiceName, request.RolloutId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServiceRolloutAsync()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServiceRolloutRequest request = new GetServiceRolloutRequest
{
ServiceName = "service_named5df05d5",
RolloutId = "rollout_id174e7821",
};
Rollout expectedResponse = new Rollout
{
RolloutId = "rollout_id174e7821",
CreateTime = new wkt::Timestamp(),
CreatedBy = "created_by206bd4da",
Status = Rollout.Types.RolloutStatus.Cancelled,
TrafficPercentStrategy = new Rollout.Types.TrafficPercentStrategy(),
ServiceName = "service_named5df05d5",
DeleteServiceStrategy = new Rollout.Types.DeleteServiceStrategy(),
};
mockGrpcClient.Setup(x => x.GetServiceRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Rollout>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
Rollout responseCallSettings = await client.GetServiceRolloutAsync(request.ServiceName, request.RolloutId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Rollout responseCancellationToken = await client.GetServiceRolloutAsync(request.ServiceName, request.RolloutId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GenerateConfigReportRequestObject()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GenerateConfigReportRequest request = new GenerateConfigReportRequest
{
NewConfig = new wkt::Any(),
OldConfig = new wkt::Any(),
};
GenerateConfigReportResponse expectedResponse = new GenerateConfigReportResponse
{
ServiceName = "service_named5df05d5",
Id = "id74b70bb8",
ChangeReports = { new ChangeReport(), },
Diagnostics = { new Diagnostic(), },
};
mockGrpcClient.Setup(x => x.GenerateConfigReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
GenerateConfigReportResponse response = client.GenerateConfigReport(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GenerateConfigReportRequestObjectAsync()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GenerateConfigReportRequest request = new GenerateConfigReportRequest
{
NewConfig = new wkt::Any(),
OldConfig = new wkt::Any(),
};
GenerateConfigReportResponse expectedResponse = new GenerateConfigReportResponse
{
ServiceName = "service_named5df05d5",
Id = "id74b70bb8",
ChangeReports = { new ChangeReport(), },
Diagnostics = { new Diagnostic(), },
};
mockGrpcClient.Setup(x => x.GenerateConfigReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GenerateConfigReportResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
GenerateConfigReportResponse responseCallSettings = await client.GenerateConfigReportAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GenerateConfigReportResponse responseCancellationToken = await client.GenerateConfigReportAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GenerateConfigReport()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GenerateConfigReportRequest request = new GenerateConfigReportRequest
{
NewConfig = new wkt::Any(),
OldConfig = new wkt::Any(),
};
GenerateConfigReportResponse expectedResponse = new GenerateConfigReportResponse
{
ServiceName = "service_named5df05d5",
Id = "id74b70bb8",
ChangeReports = { new ChangeReport(), },
Diagnostics = { new Diagnostic(), },
};
mockGrpcClient.Setup(x => x.GenerateConfigReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
GenerateConfigReportResponse response = client.GenerateConfigReport(request.NewConfig, request.OldConfig);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GenerateConfigReportAsync()
{
moq::Mock<ServiceManager.ServiceManagerClient> mockGrpcClient = new moq::Mock<ServiceManager.ServiceManagerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GenerateConfigReportRequest request = new GenerateConfigReportRequest
{
NewConfig = new wkt::Any(),
OldConfig = new wkt::Any(),
};
GenerateConfigReportResponse expectedResponse = new GenerateConfigReportResponse
{
ServiceName = "service_named5df05d5",
Id = "id74b70bb8",
ChangeReports = { new ChangeReport(), },
Diagnostics = { new Diagnostic(), },
};
mockGrpcClient.Setup(x => x.GenerateConfigReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GenerateConfigReportResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ServiceManagerClient client = new ServiceManagerClientImpl(mockGrpcClient.Object, null);
GenerateConfigReportResponse responseCallSettings = await client.GenerateConfigReportAsync(request.NewConfig, request.OldConfig, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GenerateConfigReportResponse responseCancellationToken = await client.GenerateConfigReportAsync(request.NewConfig, request.OldConfig, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Web;
using System.Web.Security;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Models;
using umbraco;
using umbraco.cms.businesslogic.web;
using RenderingEngine = Umbraco.Core.RenderingEngine;
namespace Umbraco.Web.Routing
{
/// <summary>
/// Represents a request for one specified Umbraco IPublishedContent to be rendered
/// by one specified template, using one specified Culture and RenderingEngine.
/// </summary>
public class PublishedContentRequest
{
private bool _readonly;
private bool _readonlyUri;
/// <summary>
/// Triggers before the published content request is prepared.
/// </summary>
/// <remarks>When the event triggers, no preparation has been done. It is still possible to
/// modify the request's Uri property, for example to restore its original, public-facing value
/// that might have been modified by an in-between equipement such as a load-balancer.</remarks>
public static event EventHandler<EventArgs> Preparing;
/// <summary>
/// Triggers once the published content request has been prepared, but before it is processed.
/// </summary>
/// <remarks>When the event triggers, preparation is done ie domain, culture, document, template,
/// rendering engine, etc. have been setup. It is then possible to change anything, before
/// the request is actually processed and rendered by Umbraco.</remarks>
public static event EventHandler<EventArgs> Prepared;
// the engine that does all the processing
// because in order to keep things clean and separated,
// the content request is just a data holder
private readonly PublishedContentRequestEngine _engine;
// the cleaned up uri
// the cleaned up Uri has no virtual directory, no trailing slash, no .aspx extension, etc.
private Uri _uri;
/// <summary>
/// Initializes a new instance of the <see cref="PublishedContentRequest"/> class with a specific Uri and routing context.
/// </summary>
/// <param name="uri">The request <c>Uri</c>.</param>
/// <param name="routingContext">A routing context.</param>
/// <param name="getRolesForLogin">A callback method to return the roles for the provided login name when required</param>
/// <param name="routingConfig"></param>
public PublishedContentRequest(Uri uri, RoutingContext routingContext, IWebRoutingSection routingConfig, Func<string, IEnumerable<string>> getRolesForLogin)
{
if (uri == null) throw new ArgumentNullException("uri");
if (routingContext == null) throw new ArgumentNullException("routingContext");
Uri = uri;
RoutingContext = routingContext;
GetRolesForLogin = getRolesForLogin;
_engine = new PublishedContentRequestEngine(
routingConfig,
this);
RenderingEngine = RenderingEngine.Unknown;
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the constructor specifying all dependencies instead")]
public PublishedContentRequest(Uri uri, RoutingContext routingContext)
: this(uri, routingContext, UmbracoConfig.For.UmbracoSettings().WebRouting, s => Roles.Provider.GetRolesForUser(s))
{
}
/// <summary>
/// Gets the engine associated to the request.
/// </summary>
internal PublishedContentRequestEngine Engine { get { return _engine; } }
/// <summary>
/// Prepares the request.
/// </summary>
public void Prepare()
{
_engine.PrepareRequest();
}
/// <summary>
/// Called to configure the request
/// </summary>
/// <remarks>
/// This public method is legacy, Prepare() has been made public now which should be used and ensures the domains are assigned and
/// if a public content item is already assigned Prepare() now ensures that the finders are not executed.
/// </remarks>
[Obsolete("Use Prepare() instead which configures the request and wires up everything correctly")]
public void ConfigureRequest()
{
_engine.ConfigureRequest();
}
/// <summary>
/// Updates the request when there is no template to render the content.
/// </summary>
internal void UpdateOnMissingTemplate()
{
var __readonly = _readonly;
_readonly = false;
_engine.UpdateRequestOnMissingTemplate();
_readonly = __readonly;
}
/// <summary>
/// Triggers the Preparing event.
/// </summary>
internal void OnPreparing()
{
var handler = Preparing;
if (handler != null) handler(this, EventArgs.Empty);
_readonlyUri = true;
}
/// <summary>
/// Triggers the Prepared event.
/// </summary>
internal void OnPrepared()
{
var handler = Prepared;
if (handler != null) handler(this, EventArgs.Empty);
if (HasPublishedContent == false)
Is404 = true; // safety
_readonly = true;
}
/// <summary>
/// Gets or sets the cleaned up Uri used for routing.
/// </summary>
/// <remarks>The cleaned up Uri has no virtual directory, no trailing slash, no .aspx extension, etc.</remarks>
public Uri Uri
{
get
{
return _uri;
}
set
{
if (_readonlyUri)
throw new InvalidOperationException("Cannot modify Uri after Preparing has triggered.");
_uri = value;
}
}
private void EnsureWriteable()
{
if (_readonly)
throw new InvalidOperationException("Cannot modify a PublishedContentRequest once it is read-only.");
}
#region PublishedContent
/// <summary>
/// The requested IPublishedContent, if any, else <c>null</c>.
/// </summary>
private IPublishedContent _publishedContent;
/// <summary>
/// The initial requested IPublishedContent, if any, else <c>null</c>.
/// </summary>
/// <remarks>The initial requested content is the content that was found by the finders,
/// before anything such as 404, redirect... took place.</remarks>
private IPublishedContent _initialPublishedContent;
/// <summary>
/// Gets or sets the requested content.
/// </summary>
/// <remarks>Setting the requested content clears <c>Template</c>.</remarks>
public IPublishedContent PublishedContent
{
get { return _publishedContent; }
set
{
EnsureWriteable();
_publishedContent = value;
IsInternalRedirectPublishedContent = false;
TemplateModel = null;
}
}
/// <summary>
/// Sets the requested content, following an internal redirect.
/// </summary>
/// <param name="content">The requested content.</param>
/// <remarks>Depending on <c>UmbracoSettings.InternalRedirectPreservesTemplate</c>, will
/// preserve or reset the template, if any.</remarks>
public void SetInternalRedirectPublishedContent(IPublishedContent content)
{
if (content == null) throw new ArgumentNullException("content");
EnsureWriteable();
// unless a template has been set already by the finder,
// template should be null at that point.
// IsInternalRedirect if IsInitial, or already IsInternalRedirect
var isInternalRedirect = IsInitialPublishedContent || IsInternalRedirectPublishedContent;
// redirecting to self
if (content.Id == PublishedContent.Id) // neither can be null
{
// no need to set PublishedContent, we're done
IsInternalRedirectPublishedContent = isInternalRedirect;
return;
}
// else
// save
var template = _template;
var renderingEngine = RenderingEngine;
// set published content - this resets the template, and sets IsInternalRedirect to false
PublishedContent = content;
IsInternalRedirectPublishedContent = isInternalRedirect;
// must restore the template if it's an internal redirect & the config option is set
if (isInternalRedirect && UmbracoConfig.For.UmbracoSettings().WebRouting.InternalRedirectPreservesTemplate)
{
// restore
_template = template;
RenderingEngine = renderingEngine;
}
}
/// <summary>
/// Gets the initial requested content.
/// </summary>
/// <remarks>The initial requested content is the content that was found by the finders,
/// before anything such as 404, redirect... took place.</remarks>
public IPublishedContent InitialPublishedContent { get { return _initialPublishedContent; } }
/// <summary>
/// Gets value indicating whether the current published content is the initial one.
/// </summary>
public bool IsInitialPublishedContent
{
get
{
return _initialPublishedContent != null && _initialPublishedContent == _publishedContent;
}
}
/// <summary>
/// Indicates that the current PublishedContent is the initial one.
/// </summary>
public void SetIsInitialPublishedContent()
{
EnsureWriteable();
// note: it can very well be null if the initial content was not found
_initialPublishedContent = _publishedContent;
IsInternalRedirectPublishedContent = false;
}
/// <summary>
/// Gets or sets a value indicating whether the current published content has been obtained
/// from the initial published content following internal redirections exclusively.
/// </summary>
/// <remarks>Used by PublishedContentRequestEngine.FindTemplate() to figure out whether to
/// apply the internal redirect or not, when content is not the initial content.</remarks>
public bool IsInternalRedirectPublishedContent { get; private set; }
/// <summary>
/// Gets a value indicating whether the content request has a content.
/// </summary>
public bool HasPublishedContent
{
get { return PublishedContent != null; }
}
#endregion
#region Template
/// <summary>
/// The template model, if any, else <c>null</c>.
/// </summary>
private ITemplate _template;
/// <summary>
/// Gets or sets the template model to use to display the requested content.
/// </summary>
internal ITemplate TemplateModel
{
get
{
return _template;
}
set
{
_template = value;
RenderingEngine = RenderingEngine.Unknown; // reset
if (_template != null)
RenderingEngine = _engine.FindTemplateRenderingEngine(_template.Alias);
}
}
/// <summary>
/// Gets the alias of the template to use to display the requested content.
/// </summary>
public string TemplateAlias
{
get
{
return _template == null ? null : _template.Alias;
}
}
/// <summary>
/// Tries to set the template to use to display the requested content.
/// </summary>
/// <param name="alias">The alias of the template.</param>
/// <returns>A value indicating whether a valid template with the specified alias was found.</returns>
/// <remarks>
/// <para>Successfully setting the template does refresh <c>RenderingEngine</c>.</para>
/// <para>If setting the template fails, then the previous template (if any) remains in place.</para>
/// </remarks>
public bool TrySetTemplate(string alias)
{
EnsureWriteable();
if (string.IsNullOrWhiteSpace(alias))
{
TemplateModel = null;
return true;
}
// NOTE - can we stil get it with whitespaces in it due to old legacy bugs?
alias = alias.Replace(" ", "");
var model = ApplicationContext.Current.Services.FileService.GetTemplate(alias);
if (model == null)
return false;
TemplateModel = model;
return true;
}
/// <summary>
/// Sets the template to use to display the requested content.
/// </summary>
/// <param name="template">The template.</param>
/// <remarks>Setting the template does refresh <c>RenderingEngine</c>.</remarks>
public void SetTemplate(ITemplate template)
{
EnsureWriteable();
TemplateModel = template;
}
/// <summary>
/// Resets the template.
/// </summary>
/// <remarks>The <c>RenderingEngine</c> becomes unknown.</remarks>
public void ResetTemplate()
{
EnsureWriteable();
TemplateModel = null;
}
/// <summary>
/// Gets a value indicating whether the content request has a template.
/// </summary>
public bool HasTemplate
{
get { return _template != null; }
}
#endregion
#region Domain and Culture
[Obsolete("Do not use this property, use the non-legacy UmbracoDomain property instead")]
public Domain Domain
{
get { return new Domain(UmbracoDomain); }
}
//TODO: Should we publicize the setter now that we are using a non-legacy entity??
/// <summary>
/// Gets or sets the content request's domain.
/// </summary>
public IDomain UmbracoDomain { get; internal set; }
/// <summary>
/// Gets or sets the content request's domain Uri.
/// </summary>
/// <remarks>The <c>Domain</c> may contain "example.com" whereas the <c>Uri</c> will be fully qualified eg "http://example.com/".</remarks>
public Uri DomainUri { get; internal set; }
/// <summary>
/// Gets a value indicating whether the content request has a domain.
/// </summary>
public bool HasDomain
{
get { return UmbracoDomain != null; }
}
private CultureInfo _culture;
/// <summary>
/// Gets or sets the content request's culture.
/// </summary>
public CultureInfo Culture
{
get { return _culture; }
set
{
EnsureWriteable();
_culture = value;
}
}
// note: do we want to have an ordered list of alternate cultures,
// to allow for fallbacks when doing dictionnary lookup and such?
#endregion
#region Rendering
/// <summary>
/// Gets or sets whether the rendering engine is MVC or WebForms.
/// </summary>
public RenderingEngine RenderingEngine { get; internal set; }
#endregion
/// <summary>
/// Gets or sets the current RoutingContext.
/// </summary>
public RoutingContext RoutingContext { get; private set; }
internal Func<string, IEnumerable<string>> GetRolesForLogin { get; private set; }
/// <summary>
/// The "umbraco page" object.
/// </summary>
private page _umbracoPage;
/// <summary>
/// Gets or sets the "umbraco page" object.
/// </summary>
/// <remarks>
/// This value is only used for legacy/webforms code.
/// </remarks>
internal page UmbracoPage
{
get
{
if (_umbracoPage == null)
throw new InvalidOperationException("The UmbracoPage object has not been initialized yet.");
return _umbracoPage;
}
set { _umbracoPage = value; }
}
#region Status
/// <summary>
/// Gets or sets a value indicating whether the requested content could not be found.
/// </summary>
/// <remarks>This is set in the <c>PublishedContentRequestBuilder</c>.</remarks>
public bool Is404 { get; internal set; }
/// <summary>
/// Indicates that the requested content could not be found.
/// </summary>
/// <remarks>This is for public access, in custom content finders or <c>Prepared</c> event handlers,
/// where we want to allow developers to indicate a request is 404 but not to cancel it.</remarks>
public void SetIs404()
{
EnsureWriteable();
Is404 = true;
}
/// <summary>
/// Gets a value indicating whether the content request triggers a redirect (permanent or not).
/// </summary>
public bool IsRedirect { get { return string.IsNullOrWhiteSpace(RedirectUrl) == false; } }
/// <summary>
/// Gets or sets a value indicating whether the redirect is permanent.
/// </summary>
public bool IsRedirectPermanent { get; private set; }
/// <summary>
/// Gets or sets the url to redirect to, when the content request triggers a redirect.
/// </summary>
public string RedirectUrl { get; private set; }
/// <summary>
/// Indicates that the content request should trigger a redirect (302).
/// </summary>
/// <param name="url">The url to redirect to.</param>
/// <remarks>Does not actually perform a redirect, only registers that the response should
/// redirect. Redirect will or will not take place in due time.</remarks>
public void SetRedirect(string url)
{
EnsureWriteable();
RedirectUrl = url;
IsRedirectPermanent = false;
}
/// <summary>
/// Indicates that the content request should trigger a permanent redirect (301).
/// </summary>
/// <param name="url">The url to redirect to.</param>
/// <remarks>Does not actually perform a redirect, only registers that the response should
/// redirect. Redirect will or will not take place in due time.</remarks>
public void SetRedirectPermanent(string url)
{
EnsureWriteable();
RedirectUrl = url;
IsRedirectPermanent = true;
}
/// <summary>
/// Indicates that the content requet should trigger a redirect, with a specified status code.
/// </summary>
/// <param name="url">The url to redirect to.</param>
/// <param name="status">The status code (300-308).</param>
/// <remarks>Does not actually perform a redirect, only registers that the response should
/// redirect. Redirect will or will not take place in due time.</remarks>
public void SetRedirect(string url, int status)
{
EnsureWriteable();
if (status < 300 || status > 308)
throw new ArgumentOutOfRangeException("status", "Valid redirection status codes 300-308.");
RedirectUrl = url;
IsRedirectPermanent = (status == 301 || status == 308);
if (status != 301 && status != 302) // default redirect statuses
ResponseStatusCode = status;
}
/// <summary>
/// Gets or sets the content request http response status code.
/// </summary>
/// <remarks>Does not actually set the http response status code, only registers that the response
/// should use the specified code. The code will or will not be used, in due time.</remarks>
public int ResponseStatusCode { get; private set; }
/// <summary>
/// Gets or sets the content request http response status description.
/// </summary>
/// <remarks>Does not actually set the http response status description, only registers that the response
/// should use the specified description. The description will or will not be used, in due time.</remarks>
public string ResponseStatusDescription { get; private set; }
/// <summary>
/// Sets the http response status code, along with an optional associated description.
/// </summary>
/// <param name="code">The http status code.</param>
/// <param name="description">The description.</param>
/// <remarks>Does not actually set the http response status code and description, only registers that
/// the response should use the specified code and description. The code and description will or will
/// not be used, in due time.</remarks>
public void SetResponseStatus(int code, string description = null)
{
EnsureWriteable();
// .Status is deprecated
// .SubStatusCode is IIS 7+ internal, ignore
ResponseStatusCode = code;
ResponseStatusDescription = description;
}
#endregion
/// <summary>
/// Gets or sets the <c>System.Web.HttpCacheability</c>
/// </summary>
// Note: we used to set a default value here but that would then be the default
// for ALL requests, we shouldn't overwrite it though if people are using [OutputCache] for example
// see: https://our.umbraco.org/forum/using-umbraco-and-getting-started/79715-output-cache-in-umbraco-752
internal HttpCacheability Cacheability { get; set; }
/// <summary>
/// Gets or sets a list of Extensions to append to the Response.Cache object
/// </summary>
private List<string> _cacheExtensions = new List<string>();
internal List<string> CacheExtensions
{
get { return _cacheExtensions; }
set { _cacheExtensions = value; }
}
/// <summary>
/// Gets or sets a dictionary of Headers to append to the Response object
/// </summary>
private Dictionary<string, string> _headers = new Dictionary<string, string>();
internal Dictionary<string, string> Headers
{
get { return _headers; }
set { _headers = value; }
}
}
}
| |
using FluentAssertions;
using Microsoft.Toolkit.HighPerformance.Buffers;
using System;
using System.Buffers;
using System.Linq;
using Xunit;
namespace Secs4Net.UnitTests;
public class ItemUnitTest
{
[Fact]
public void Item_Self_Equals_Should_Be_True()
{
var left =
L(
A("A"),
B(),
F4(),
I4()
);
var right = left;
Assert.True(left == right);
}
[Fact]
public void Item_Self_Not_Equals_Should_Be_False()
{
var left =
L(
A("A"),
B(),
F4(),
I4()
);
var right = left;
Assert.False(left != right);
}
[Fact]
public void Item_Equals_Should_Be_True()
{
var left =
L(
A("A"),
B(),
F4(),
I4()
);
var right =
L(
A("A"),
B(),
F4(),
I4()
);
left.Should().BeEquivalentTo(right);
}
[Fact]
public void Item_Equals_Should_Be_False()
{
var left =
L(
A("A"),
B(),
L(
B(12, 11)),
F4(),
I4()
);
var right =
L(
A("A"),
B(),
L(
B(12, 10)), // diff
F8(), // diff
I4()
);
left.Should().NotBeEquivalentTo(right);
}
[Fact]
public void ItemWithOwner_Can_Compare_With_ItemWithOwner()
{
using var left = I2(CreateMemoryOwner<short>(1, 2, 3));
using var right = I2(CreateMemoryOwner<short>(1, 2, 3));
left.Should().BeEquivalentTo(right);
static MemoryOwner<T> CreateMemoryOwner<T>(T a1, T a2, T a3)
{
var leftOwner = MemoryOwner<T>.Allocate(3);
leftOwner.Span[0] = a1;
leftOwner.Span[1] = a2;
leftOwner.Span[2] = a3;
return leftOwner;
}
}
[Fact]
public void ItemWithOwner_Can_Compare_With_Item()
{
using var left = I2(CreateMemoryOwner<short>(1, 2, 3));
using var right = I2(1, 2, 3);
left.Should().BeEquivalentTo(right);
static MemoryOwner<T> CreateMemoryOwner<T>(T a1, T a2, T a3)
{
var leftOwner = MemoryOwner<T>.Allocate(3);
leftOwner.Span[0] = a1;
leftOwner.Span[1] = a2;
leftOwner.Span[2] = a3;
return leftOwner;
}
}
[Fact]
public void Item_Can_Get_Internal_Values_With_Proper_Method()
{
var str = "I am a string";
using (var stringItem = A(str))
{
stringItem.GetString().Should().Be(str);
stringItem.Count.Should().Be(str.Length);
}
var arr = new short[3] { 2314, 4214, 4221 };
using (var arrayItem = I2(arr))
{
arrayItem.GetMemory<short>().ToArray().Should().BeEquivalentTo(arr);
arrayItem.FirstValue<short>().Should().Be(arr[0]);
arrayItem.FirstValueOrDefault<short>(21).Should().NotBe(21).And.Be(arr[0]);
}
using (var listItem = L(
A(str),
I2(arr),
U2(),
Boolean()))
{
listItem[0].Should().BeEquivalentTo(A(str));
listItem[1].Should().BeEquivalentTo(I2(arr));
Action getEnumerator = () =>
{
foreach (var item in listItem.Items)
{
}
};
getEnumerator.Should().NotThrow();
L(listItem.Items[1..^1]).Should().BeEquivalentTo(L(I2(arr), U2()));
var range = 2..5;
Action sliceOutOfRange = () => _ = listItem.Items[range];
sliceOutOfRange.Should().Throw<ArgumentOutOfRangeException>();
}
}
[Fact]
public void Item_Throw_Not_Supported_Exception_With_Format_Unmatch()
{
using (var stringItem = A("string"))
{
Action stringItemAccessIndexer = () => _ = stringItem[0];
stringItemAccessIndexer.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage("Item", stringItem.Format));
Action stringItemGetEnumerator = () => _ = stringItem.Items;
stringItemGetEnumerator.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage(nameof(Item.Items), stringItem.Format));
Action stringItemFirstValue = () => stringItem.FirstValue<byte>();
stringItemFirstValue.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage(nameof(Item.FirstValue), stringItem.Format));
Action stringItemFirstValueOrDefault = () => stringItem.FirstValueOrDefault<byte>();
stringItemFirstValueOrDefault.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage(nameof(Item.FirstValueOrDefault), stringItem.Format));
Action stringItemGetValues = () => stringItem.GetMemory<char>();
stringItemGetValues.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage(nameof(Item.GetMemory), stringItem.Format));
}
using (var arrayItem = Boolean())
{
Action arrayItemGetString = () => arrayItem.GetString();
arrayItemGetString.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage(nameof(Item.GetString), arrayItem.Format));
Action arrayItemAccessIndexer = () => _ = arrayItem[^1];
arrayItemAccessIndexer.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage("Item", arrayItem.Format));
Action arrayItemGetEnumerator = () => _ = arrayItem.Items;
arrayItemGetEnumerator.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage(nameof(Item.Items), arrayItem.Format));
}
using (var listItem = L())
{
Action listItemGetString = () => listItem.GetString();
listItemGetString.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage(nameof(Item.GetString), listItem.Format));
Action listItemFirstValue = () => listItem.FirstValue<byte>();
listItemFirstValue.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage(nameof(Item.FirstValue), listItem.Format));
Action listItemFirstValueOrDefault = () => listItem.FirstValueOrDefault<byte>();
listItemFirstValueOrDefault.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage(nameof(Item.FirstValueOrDefault), listItem.Format));
Action listItemGetValues = () => listItem.GetMemory<byte>();
listItemGetValues.Should().Throw<NotSupportedException>()
.WithMessage(CreateNotSupportedMessage(nameof(Item.GetMemory), listItem.Format));
}
static string CreateNotSupportedMessage(string memberName, SecsFormat format)
=> $"{memberName} is not supported, since the item's {nameof(Item.Format)} is {format}";
}
[Fact]
public void Item_GetValues_With_Match_Typed()
{
var source = new int[] { 1, 2, 3, 4 };
var itemArray = I4(source).GetMemory<int>().ToArray();
itemArray.Should().BeEquivalentTo(source);
}
[Fact]
public void Item_GetValues_With_Downsize_Typed()
{
var source = new int[] { 1, 2, 3, 4 };
// down size from int to short
var itemArray = I4(source).GetMemory<short>().ToArray();
itemArray.Length.Should().Be(Buffer.ByteLength(source) / sizeof(short));
var expectedArray = new short[itemArray.Length];
Buffer.BlockCopy(source, 0, expectedArray, 0, itemArray.Length * sizeof(short));
itemArray.Should().BeEquivalentTo(expectedArray);
}
[Fact]
public void Item_GetValues_With_Upsize_Typed()
{
var source = new int[] { 1, 2, 3, 4 };
// up size from int to long
var itemArray = I4(source).GetMemory<long>().ToArray();
itemArray.Length.Should().Be(Buffer.ByteLength(source) / sizeof(long));
var expectedArray = new long[itemArray.Length];
Buffer.BlockCopy(source, 0, expectedArray, 0, itemArray.Length * sizeof(long));
itemArray.Should().BeEquivalentTo(expectedArray);
}
[Fact]
public void Item_GetValues_With_Upsize_Typed_But_Unallignment()
{
var source = new int[] { 1, 2, 3, 4, 5 };
// up size from int to long
var itemArray = I4(source).GetMemory<long>().ToArray();
itemArray.Length.Should().Be(Buffer.ByteLength(source) / sizeof(long));
var expectedArray = new long[itemArray.Length];
Buffer.BlockCopy(source, 0, expectedArray, 0, itemArray.Length * sizeof(long));
itemArray.Should().BeEquivalentTo(expectedArray);
}
[Fact]
public void Item_GetValues_ValueArray_Can_Index_Great_Than_Length()
{
var item = I4(1, 2, 3, 4, 5);
// up size from int to long
Action indexGreatThanSpanLength = () =>
{
var itemArray = item.GetMemory<long>().Span;
var value = itemArray[itemArray.Length + 1];
};
indexGreatThanSpanLength.Should().Throw<IndexOutOfRangeException>();
}
[Fact]
public void Item_FirstValue_Should_Throw_Error_If_Is_Empty()
{
var item = I4();
Action action = () => item.FirstValue<int>();
action.Should().Throw<IndexOutOfRangeException>();
}
[Fact]
public void Item_FirstValue_With_Downsize_Typed()
{
var firstSrc = short.MaxValue + 12;
var first = I4(firstSrc).FirstValue<short>();
first.Should().Be(unchecked((short)firstSrc));
}
[Fact]
public void Item_FirstValue_With_Upsize_Typed()
{
var bytes = new byte[] { 128, 212, 231 };
var first = U1(bytes).FirstValue<ushort>();
#if NET
first.Should().Be(BitConverter.ToUInt16(bytes));
#else
first.Should().Be(BitConverter.ToUInt16(bytes, 0));
#endif
}
[Fact]
public void Item_FirstValue_With_Upsize_Typed_Should_Throw_Error_If_Total_Bytes_Less_Than_SizeOf_T()
{
var bytes = new byte[] { 128 };
Action action = () => U1(bytes).FirstValue<ushort>();
action.Should().Throw<IndexOutOfRangeException>();
}
[Fact]
public void Item_FirstValueOrDefault_Should_Not_Throw_Error_If_Is_Empty()
{
var item = I4();
Action action = () => item.FirstValueOrDefault<int>();
action.Should().NotThrow();
Action action2 = () => item.FirstValueOrDefault<bool>();
action2.Should().NotThrow();
item.FirstValueOrDefault(4).Should().Be(4);
}
[Fact]
public void Item_FirstValueOrDefault_With_Upsize_Typed_Should_Return_Default_Value_If_Total_Bytes_Less_Than_SizeOf_T()
{
var bytes = new byte[] { 128 };
ushort defaultValue = 11;
var first = U1(bytes).FirstValueOrDefault(defaultValue);
first.Should().Be(defaultValue);
}
[Fact]
public void Item_Encode_Decode_Should_Be_Equivalent()
{
var item =
L(
L(),
U1(122, 34),
U2(34531, 23123),
U4(2123513, 52451141),
F4(23123.21323f, 2324.221f),
A("A string"),
J("sdsad"),
F8(231.00002321d, 0.2913212312d),
L(
U1(122, 34),
U2(34531, 23123),
U4(2123513, 52451141),
F4(23123.21323f, 2324.221f),
Boolean(true, false, false, true),
B(0x1C, 0x01, 0xFF),
L(
A("A string"),
J("sdsad"),
Boolean(true, false, false, true),
B(0x1C, 0x01, 0xFF)),
F8(231.00002321d, 0.2913212312d)));
var encodedBytes = new ReadOnlySequence<byte>(item.GetEncodedBytes());
var item2 = DecodeFromFullBuffer(ref encodedBytes);
encodedBytes.IsEmpty.Should().BeTrue();
item.Should().BeEquivalentTo(item2);
}
[Fact]
public void Item_With_MemoryOwner_Encode_Decode_Should_Be_Equivalent()
{
var item = U1(Enumerable.Repeat((byte)1, 1025));
var encodedBytes = new ReadOnlySequence<byte>(item.GetEncodedBytes());
using var item2 = DecodeFromFullBuffer(ref encodedBytes);
encodedBytes.IsEmpty.Should().BeTrue();
item.Should().BeEquivalentTo(item2);
}
[Fact]
public void List_Item_Slot_Can_Be_Changed()
{
var item =
L(
U1(122, 34),
U2(34531, 23123),
U4(2123513, 52451141),
F4(23123.21323f, 2324.221f),
Boolean(true, false, false, true),
B(0x1C, 0x01, 0xFF),
F8(231.00002321d, 0.2913212312d));
// be careful this operation
// the original Item will not be managed by any List
// so manually invoke Dispose method if you need.
var oldItem = item[2];
oldItem.Dispose();
item[2] = Boolean(true);
item[2].Should().BeEquivalentTo(Boolean(true));
}
[Fact]
public void Item_FirstValue_Can_Be_Changed()
{
ushort original = 2134;
var item = U2(original);
item.FirstValue<byte>() = 12; // change first byte
var changed = item.FirstValue<ushort>();
Assert.NotEqual(original, changed);
var originalBytes = BitConverter.GetBytes(original);
originalBytes[0] = 12; // change first byte
#if NET
changed.Should().Be(BitConverter.ToUInt16(originalBytes));
#else
changed.Should().Be(BitConverter.ToUInt16(originalBytes, 0));
#endif
}
[Fact]
public void Item_Values_Can_Be_Changed()
{
var original = ushort.MaxValue;
var item = U2(original);
var arr = item.GetMemory<byte>().Span;
arr.Length.Should().Be(2);
arr[0] = 123;
arr[1] = 3;
var changed = item.FirstValue<ushort>();
changed.Should().NotBe(original);
#if NET
changed.Should().Be(BitConverter.ToUInt16(arr));
#else
changed.Should().Be(BitConverter.ToUInt16(arr.ToArray(), 0));
#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 copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Nwc.XmlRpc;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XmlRpcGroupsServicesConnectorModule")]
public class XmlRpcGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_debugEnabled = false;
public const GroupPowers DefaultEveryonePowers
= GroupPowers.AllowSetHome
| GroupPowers.Accountable
| GroupPowers.JoinChat
| GroupPowers.AllowVoiceChat
| GroupPowers.ReceiveNotices
| GroupPowers.StartProposal
| GroupPowers.VoteOnProposal;
// Would this be cleaner as (GroupPowers)ulong.MaxValue?
public const GroupPowers DefaultOwnerPowers
= GroupPowers.Accountable
| GroupPowers.AllowEditLand
| GroupPowers.AllowFly
| GroupPowers.AllowLandmark
| GroupPowers.AllowRez
| GroupPowers.AllowSetHome
| GroupPowers.AllowVoiceChat
| GroupPowers.AssignMember
| GroupPowers.AssignMemberLimited
| GroupPowers.ChangeActions
| GroupPowers.ChangeIdentity
| GroupPowers.ChangeMedia
| GroupPowers.ChangeOptions
| GroupPowers.CreateRole
| GroupPowers.DeedObject
| GroupPowers.DeleteRole
| GroupPowers.Eject
| GroupPowers.FindPlaces
| GroupPowers.Invite
| GroupPowers.JoinChat
| GroupPowers.LandChangeIdentity
| GroupPowers.LandDeed
| GroupPowers.LandDivideJoin
| GroupPowers.LandEdit
| GroupPowers.LandEjectAndFreeze
| GroupPowers.LandGardening
| GroupPowers.LandManageAllowed
| GroupPowers.LandManageBanned
| GroupPowers.LandManagePasses
| GroupPowers.LandOptions
| GroupPowers.LandRelease
| GroupPowers.LandSetSale
| GroupPowers.ModerateChat
| GroupPowers.ObjectManipulate
| GroupPowers.ObjectSetForSale
| GroupPowers.ReceiveNotices
| GroupPowers.RemoveMember
| GroupPowers.ReturnGroupOwned
| GroupPowers.ReturnGroupSet
| GroupPowers.ReturnNonGroup
| GroupPowers.RoleProperties
| GroupPowers.SendNotices
| GroupPowers.SetLandingPoint
| GroupPowers.StartProposal
| GroupPowers.VoteOnProposal;
private bool m_connectorEnabled = false;
private string m_groupsServerURI = string.Empty;
private bool m_disableKeepAlive = false;
private string m_groupReadKey = string.Empty;
private string m_groupWriteKey = string.Empty;
private IUserAccountService m_accountService = null;
private ExpiringCache<string, XmlRpcResponse> m_memoryCache;
private int m_cacheTimeout = 30;
// Used to track which agents are have dropped from a group chat session
// Should be reset per agent, on logon
// TODO: move this to Flotsam XmlRpc Service
// SessionID, List<AgentID>
private Dictionary<UUID, List<UUID>> m_groupsAgentsDroppedFromChatSession = new Dictionary<UUID, List<UUID>>();
private Dictionary<UUID, List<UUID>> m_groupsAgentsInvitedToChatSession = new Dictionary<UUID, List<UUID>>();
#region Region Module interfaceBase Members
public string Name
{
get { return "XmlRpcGroupsServicesConnector"; }
}
// this module is not intended to be replaced, but there should only be 1 of them.
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
// if groups aren't enabled, we're not needed.
// if we're not specified as the connector to use, then we're not wanted
if ((groupsConfig.GetBoolean("Enabled", false) == false)
|| (groupsConfig.GetString("ServicesConnectorModule", "XmlRpcGroupsServicesConnector") != Name))
{
m_connectorEnabled = false;
return;
}
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Initializing {0}", this.Name);
m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty);
if (string.IsNullOrEmpty(m_groupsServerURI))
{
m_log.ErrorFormat("Please specify a valid URL for GroupsServerURI in OpenSim.ini, [Groups]");
m_connectorEnabled = false;
return;
}
m_disableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", false);
m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty);
m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty);
m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30);
if (m_cacheTimeout == 0)
{
m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Disabled.");
}
else
{
m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Timeout set to {0}.", m_cacheTimeout);
}
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false);
// If we got all the config options we need, lets start'er'up
m_memoryCache = new ExpiringCache<string, XmlRpcResponse>();
m_connectorEnabled = true;
}
}
public void Close()
{
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Closing {0}", this.Name);
}
public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (m_connectorEnabled)
{
if (m_accountService == null)
{
m_accountService = scene.UserAccountService;
}
scene.RegisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this)
{
scene.UnregisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene)
{
// TODO: May want to consider listenning for Agent Connections so we can pre-cache group info
// scene.EventManager.OnNewClient += OnNewClient;
}
#endregion
#region ISharedRegionModule Members
public void PostInitialise()
{
// NoOp
}
#endregion
#region IGroupsServicesConnector Members
/// <summary>
/// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role.
/// </summary>
public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
int membershipFee, bool openEnrollment, bool allowPublish,
bool maturePublish, UUID founderID)
{
UUID GroupID = UUID.Random();
UUID OwnerRoleID = UUID.Random();
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
param["Name"] = name;
param["Charter"] = charter;
param["ShowInList"] = showInList == true ? 1 : 0;
param["InsigniaID"] = insigniaID.ToString();
param["MembershipFee"] = membershipFee;
param["OpenEnrollment"] = openEnrollment == true ? 1 : 0;
param["AllowPublish"] = allowPublish == true ? 1 : 0;
param["MaturePublish"] = maturePublish == true ? 1 : 0;
param["FounderID"] = founderID.ToString();
param["EveryonePowers"] = ((ulong)DefaultEveryonePowers).ToString();
param["OwnerRoleID"] = OwnerRoleID.ToString();
param["OwnersPowers"] = ((ulong)DefaultOwnerPowers).ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.createGroup", param);
if (respData.Contains("error"))
{
// UUID is not nullable
return UUID.Zero;
}
return UUID.Parse((string)respData["GroupID"]);
}
public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList,
UUID insigniaID, int membershipFee, bool openEnrollment,
bool allowPublish, bool maturePublish)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["Charter"] = charter;
param["ShowInList"] = showInList == true ? 1 : 0;
param["InsigniaID"] = insigniaID.ToString();
param["MembershipFee"] = membershipFee;
param["OpenEnrollment"] = openEnrollment == true ? 1 : 0;
param["AllowPublish"] = allowPublish == true ? 1 : 0;
param["MaturePublish"] = maturePublish == true ? 1 : 0;
XmlRpcCall(requestingAgentID, "groups.updateGroup", param);
}
public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
param["Name"] = name;
param["Description"] = description;
param["Title"] = title;
param["Powers"] = powers.ToString();
XmlRpcCall(requestingAgentID, "groups.addRoleToGroup", param);
}
public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeRoleFromGroup", param);
}
public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
if (name != null)
{
param["Name"] = name;
}
if (description != null)
{
param["Description"] = description;
}
if (title != null)
{
param["Title"] = title;
}
param["Powers"] = powers.ToString();
XmlRpcCall(requestingAgentID, "groups.updateGroupRole", param);
}
public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID GroupID, string GroupName)
{
Hashtable param = new Hashtable();
if (GroupID != UUID.Zero)
{
param["GroupID"] = GroupID.ToString();
}
if (!string.IsNullOrEmpty(GroupName))
{
param["Name"] = GroupName.ToString();
}
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param);
if (respData.Contains("error"))
{
return null;
}
return GroupProfileHashtableToGroupRecord(respData);
}
public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param);
if (respData.Contains("error"))
{
// GroupProfileData is not nullable
return new GroupProfileData();
}
GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, AgentID, GroupID);
GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData);
MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle;
MemberGroupProfile.PowersMask = MemberInfo.GroupPowers;
return MemberGroupProfile;
}
public void SetAgentActiveGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
XmlRpcCall(requestingAgentID, "groups.setAgentActiveGroup", param);
}
public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["SelectedRoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param);
}
public void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["AcceptNotices"] = AcceptNotices ? "1" : "0";
param["ListInProfile"] = ListInProfile ? "1" : "0";
XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param);
}
public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
param["AgentID"] = agentID.ToString();
param["RoleID"] = roleID.ToString();
param["GroupID"] = groupID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroupInvite", param);
}
public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentToGroupInvite", param);
if (respData.Contains("error"))
{
return null;
}
GroupInviteInfo inviteInfo = new GroupInviteInfo();
inviteInfo.InviteID = inviteID;
inviteInfo.GroupID = UUID.Parse((string)respData["GroupID"]);
inviteInfo.RoleID = UUID.Parse((string)respData["RoleID"]);
inviteInfo.AgentID = UUID.Parse((string)respData["AgentID"]);
return inviteInfo;
}
public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentToGroupInvite", param);
}
public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroup", param);
}
public void RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroup", param);
}
public void AddAgentToGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroupRole", param);
}
public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroupRole", param);
}
public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search)
{
Hashtable param = new Hashtable();
param["Search"] = search;
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.findGroups", param);
List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>();
if (!respData.Contains("error"))
{
Hashtable results = (Hashtable)respData["results"];
foreach (Hashtable groupFind in results.Values)
{
DirGroupsReplyData data = new DirGroupsReplyData();
data.groupID = new UUID((string)groupFind["GroupID"]); ;
data.groupName = (string)groupFind["Name"];
data.members = int.Parse((string)groupFind["Members"]);
// data.searchOrder = order;
findings.Add(data);
}
}
return findings;
}
public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMembership", param);
if (respData.Contains("error"))
{
return null;
}
GroupMembershipData data = HashTableToGroupMembershipData(respData);
return data;
}
public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentActiveMembership", param);
if (respData.Contains("error"))
{
return null;
}
return HashTableToGroupMembershipData(respData);
}
public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMemberships", param);
List<GroupMembershipData> memberships = new List<GroupMembershipData>();
if (!respData.Contains("error"))
{
foreach (object membership in respData.Values)
{
memberships.Add(HashTableToGroupMembershipData((Hashtable)membership));
}
}
return memberships;
}
public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentRoles", param);
List<GroupRolesData> Roles = new List<GroupRolesData>();
if (respData.Contains("error"))
{
return Roles;
}
foreach (Hashtable role in respData.Values)
{
GroupRolesData data = new GroupRolesData();
data.RoleID = new UUID((string)role["RoleID"]);
data.Name = (string)role["Name"];
data.Description = (string)role["Description"];
data.Powers = ulong.Parse((string)role["Powers"]);
data.Title = (string)role["Title"];
Roles.Add(data);
}
return Roles;
}
public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoles", param);
List<GroupRolesData> Roles = new List<GroupRolesData>();
if (respData.Contains("error"))
{
return Roles;
}
foreach (Hashtable role in respData.Values)
{
GroupRolesData data = new GroupRolesData();
data.Description = (string)role["Description"];
data.Members = int.Parse((string)role["Members"]);
data.Name = (string)role["Name"];
data.Powers = ulong.Parse((string)role["Powers"]);
data.RoleID = new UUID((string)role["RoleID"]);
data.Title = (string)role["Title"];
Roles.Add(data);
}
return Roles;
}
public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupMembers", param);
List<GroupMembersData> members = new List<GroupMembersData>();
if (respData.Contains("error"))
{
return members;
}
foreach (Hashtable membership in respData.Values)
{
GroupMembersData data = new GroupMembersData();
data.AcceptNotices = ((string)membership["AcceptNotices"]) == "1";
data.AgentID = new UUID((string)membership["AgentID"]);
data.Contribution = int.Parse((string)membership["Contribution"]);
data.IsOwner = ((string)membership["IsOwner"]) == "1";
data.ListInProfile = ((string)membership["ListInProfile"]) == "1";
data.AgentPowers = ulong.Parse((string)membership["AgentPowers"]);
data.Title = (string)membership["Title"];
members.Add(data);
}
return members;
}
public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoleMembers", param);
List<GroupRoleMembersData> members = new List<GroupRoleMembersData>();
if (!respData.Contains("error"))
{
foreach (Hashtable membership in respData.Values)
{
GroupRoleMembersData data = new GroupRoleMembersData();
data.MemberID = new UUID((string)membership["AgentID"]);
data.RoleID = new UUID((string)membership["RoleID"]);
members.Add(data);
}
}
return members;
}
public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotices", param);
List<GroupNoticeData> values = new List<GroupNoticeData>();
if (!respData.Contains("error"))
{
foreach (Hashtable value in respData.Values)
{
GroupNoticeData data = new GroupNoticeData();
data.NoticeID = UUID.Parse((string)value["NoticeID"]);
data.Timestamp = uint.Parse((string)value["Timestamp"]);
data.FromName = (string)value["FromName"];
data.Subject = (string)value["Subject"];
data.HasAttachment = false;
data.AssetType = 0;
values.Add(data);
}
}
return values;
}
public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID)
{
Hashtable param = new Hashtable();
param["NoticeID"] = noticeID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotice", param);
if (respData.Contains("error"))
{
return null;
}
GroupNoticeInfo data = new GroupNoticeInfo();
data.GroupID = UUID.Parse((string)respData["GroupID"]);
data.Message = (string)respData["Message"];
data.BinaryBucket = Utils.HexStringToBytes((string)respData["BinaryBucket"], true);
data.noticeData.NoticeID = UUID.Parse((string)respData["NoticeID"]);
data.noticeData.Timestamp = uint.Parse((string)respData["Timestamp"]);
data.noticeData.FromName = (string)respData["FromName"];
data.noticeData.Subject = (string)respData["Subject"];
data.noticeData.HasAttachment = false;
data.noticeData.AssetType = 0;
if (data.Message == null)
{
data.Message = string.Empty;
}
return data;
}
public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket)
{
string binBucket = OpenMetaverse.Utils.BytesToHexString(binaryBucket, "");
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["NoticeID"] = noticeID.ToString();
param["FromName"] = fromName;
param["Subject"] = subject;
param["Message"] = message;
param["BinaryBucket"] = binBucket;
param["TimeStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString();
XmlRpcCall(requestingAgentID, "groups.addGroupNotice", param);
}
#endregion
#region GroupSessionTracking
public void ResetAgentGroupChatSessions(UUID agentID)
{
foreach (List<UUID> agentList in m_groupsAgentsDroppedFromChatSession.Values)
{
agentList.Remove(agentID);
}
}
public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
// If we're tracking this group, and we can find them in the tracking, then they've been invited
return m_groupsAgentsInvitedToChatSession.ContainsKey(groupID)
&& m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID);
}
public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID)
{
// If we're tracking drops for this group,
// and we find them, well... then they've dropped
return m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)
&& m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID);
}
public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID)
{
if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
{
// If not in dropped list, add
if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
{
m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID);
}
}
}
public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
// Add Session Status if it doesn't exist for this session
CreateGroupChatSessionTracking(groupID);
// If nessesary, remove from dropped list
if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
{
m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID);
}
}
private void CreateGroupChatSessionTracking(UUID groupID)
{
if (!m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
{
m_groupsAgentsDroppedFromChatSession.Add(groupID, new List<UUID>());
m_groupsAgentsInvitedToChatSession.Add(groupID, new List<UUID>());
}
}
#endregion
#region XmlRpcHashtableMarshalling
private GroupProfileData GroupProfileHashtableToGroupProfileData(Hashtable groupProfile)
{
GroupProfileData group = new GroupProfileData();
group.GroupID = UUID.Parse((string)groupProfile["GroupID"]);
group.Name = (string)groupProfile["Name"];
if (groupProfile["Charter"] != null)
{
group.Charter = (string)groupProfile["Charter"];
}
group.ShowInList = ((string)groupProfile["ShowInList"]) == "1";
group.InsigniaID = UUID.Parse((string)groupProfile["InsigniaID"]);
group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]);
group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1";
group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1";
group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1";
group.FounderID = UUID.Parse((string)groupProfile["FounderID"]);
group.OwnerRole = UUID.Parse((string)groupProfile["OwnerRoleID"]);
group.GroupMembershipCount = int.Parse((string)groupProfile["GroupMembershipCount"]);
group.GroupRolesCount = int.Parse((string)groupProfile["GroupRolesCount"]);
return group;
}
private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile)
{
GroupRecord group = new GroupRecord();
group.GroupID = UUID.Parse((string)groupProfile["GroupID"]);
group.GroupName = groupProfile["Name"].ToString();
if (groupProfile["Charter"] != null)
{
group.Charter = (string)groupProfile["Charter"];
}
group.ShowInList = ((string)groupProfile["ShowInList"]) == "1";
group.GroupPicture = UUID.Parse((string)groupProfile["InsigniaID"]);
group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]);
group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1";
group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1";
group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1";
group.FounderID = UUID.Parse((string)groupProfile["FounderID"]);
group.OwnerRoleID = UUID.Parse((string)groupProfile["OwnerRoleID"]);
return group;
}
private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData)
{
GroupMembershipData data = new GroupMembershipData();
data.AcceptNotices = ((string)respData["AcceptNotices"] == "1");
data.Contribution = int.Parse((string)respData["Contribution"]);
data.ListInProfile = ((string)respData["ListInProfile"] == "1");
data.ActiveRole = new UUID((string)respData["SelectedRoleID"]);
data.GroupTitle = (string)respData["Title"];
data.GroupPowers = ulong.Parse((string)respData["GroupPowers"]);
// Is this group the agent's active group
data.GroupID = new UUID((string)respData["GroupID"]);
UUID ActiveGroup = new UUID((string)respData["ActiveGroupID"]);
data.Active = data.GroupID.Equals(ActiveGroup);
data.AllowPublish = ((string)respData["AllowPublish"] == "1");
if (respData["Charter"] != null)
{
data.Charter = (string)respData["Charter"];
}
data.FounderID = new UUID((string)respData["FounderID"]);
data.GroupID = new UUID((string)respData["GroupID"]);
data.GroupName = (string)respData["GroupName"];
data.GroupPicture = new UUID((string)respData["InsigniaID"]);
data.MaturePublish = ((string)respData["MaturePublish"] == "1");
data.MembershipFee = int.Parse((string)respData["MembershipFee"]);
data.OpenEnrollment = ((string)respData["OpenEnrollment"] == "1");
data.ShowInList = ((string)respData["ShowInList"] == "1");
return data;
}
#endregion
/// <summary>
/// Encapsulate the XmlRpc call to standardize security and error handling.
/// </summary>
private Hashtable XmlRpcCall(UUID requestingAgentID, string function, Hashtable param)
{
XmlRpcResponse resp = null;
string CacheKey = null;
// Only bother with the cache if it isn't disabled.
if (m_cacheTimeout > 0)
{
if (!function.StartsWith("groups.get"))
{
// Any and all updates cause the cache to clear
m_memoryCache.Clear();
}
else
{
StringBuilder sb = new StringBuilder(requestingAgentID + function);
foreach (object key in param.Keys)
{
if (param[key] != null)
{
sb.AppendFormat(",{0}:{1}", key.ToString(), param[key].ToString());
}
}
CacheKey = sb.ToString();
m_memoryCache.TryGetValue(CacheKey, out resp);
}
}
if (resp == null)
{
if (m_debugEnabled)
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Cache miss for key {0}", CacheKey);
string UserService;
UUID SessionID;
GetClientGroupRequestID(requestingAgentID, out UserService, out SessionID);
param.Add("RequestingAgentID", requestingAgentID.ToString());
param.Add("RequestingAgentUserService", UserService);
param.Add("RequestingSessionID", SessionID.ToString());
param.Add("ReadKey", m_groupReadKey);
param.Add("WriteKey", m_groupWriteKey);
IList parameters = new ArrayList();
parameters.Add(param);
ConfigurableKeepAliveXmlRpcRequest req;
req = new ConfigurableKeepAliveXmlRpcRequest(function, parameters, m_disableKeepAlive);
try
{
resp = req.Send(m_groupsServerURI, 10000);
if ((m_cacheTimeout > 0) && (CacheKey != null))
{
m_memoryCache.AddOrUpdate(CacheKey, resp, TimeSpan.FromSeconds(m_cacheTimeout));
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[XMLRPC-GROUPS-CONNECTOR]: An error has occured while attempting to access the XmlRpcGroups server method {0} at {1}",
function, m_groupsServerURI);
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}{1}", e.Message, e.StackTrace);
foreach (string ResponseLine in req.RequestResponse.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} ", ResponseLine);
}
foreach (string key in param.Keys)
{
m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", key, param[key].ToString());
}
Hashtable respData = new Hashtable();
respData.Add("error", e.ToString());
return respData;
}
}
if (resp.Value is Hashtable)
{
Hashtable respData = (Hashtable)resp.Value;
if (respData.Contains("error") && !respData.Contains("succeed"))
{
LogRespDataToConsoleError(requestingAgentID, function, param, respData);
}
return respData;
}
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType().ToString());
if (resp.Value is ArrayList)
{
ArrayList al = (ArrayList)resp.Value;
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Contains {0} elements", al.Count);
foreach (object o in al)
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", o.GetType().ToString(), o.ToString());
}
}
else
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Function returned: {0}", resp.Value.ToString());
}
Hashtable error = new Hashtable();
error.Add("error", "invalid return value");
return error;
}
private void LogRespDataToConsoleError(UUID requestingAgentID, string function, Hashtable param, Hashtable respData)
{
m_log.ErrorFormat(
"[XMLRPC-GROUPS-CONNECTOR]: Error when calling {0} for {1} with params {2}. Response params are {3}",
function, requestingAgentID, Util.PrettyFormatToSingleLine(param), Util.PrettyFormatToSingleLine(respData));
}
/// <summary>
/// Group Request Tokens are an attempt to allow the groups service to authenticate
/// requests.
/// TODO: This broke after the big grid refactor, either find a better way, or discard this
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
private void GetClientGroupRequestID(UUID AgentID, out string UserServiceURL, out UUID SessionID)
{
UserServiceURL = "";
SessionID = UUID.Zero;
// Need to rework this based on changes to User Services
/*
UserAccount userAccount = m_accountService.GetUserAccount(UUID.Zero,AgentID);
if (userAccount == null)
{
// This should be impossible. If I've been passed a reference to a client
// that client should be registered with the UserService. So something
// is horribly wrong somewhere.
m_log.WarnFormat("[GROUPS]: Could not find a UserServiceURL for {0}", AgentID);
}
else if (userProfile is ForeignUserProfileData)
{
// They aren't from around here
ForeignUserProfileData fupd = (ForeignUserProfileData)userProfile;
UserServiceURL = fupd.UserServerURI;
SessionID = fupd.CurrentAgent.SessionID;
}
else
{
// They're a local user, use this:
UserServiceURL = m_commManager.NetworkServersInfo.UserURL;
SessionID = userProfile.CurrentAgent.SessionID;
}
*/
}
}
}
namespace Nwc.XmlRpc
{
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Net;
using System.Text;
using System.Reflection;
/// <summary>Class supporting the request side of an XML-RPC transaction.</summary>
public class ConfigurableKeepAliveXmlRpcRequest : XmlRpcRequest
{
private XmlRpcRequestSerializer _serializer = new XmlRpcRequestSerializer();
private XmlRpcResponseDeserializer _deserializer = new XmlRpcResponseDeserializer();
private bool _disableKeepAlive = true;
public string RequestResponse = String.Empty;
/// <summary>Instantiate an <c>XmlRpcRequest</c> for a specified method and parameters.</summary>
/// <param name="methodName"><c>String</c> designating the <i>object.method</i> on the server the request
/// should be directed to.</param>
/// <param name="parameters"><c>ArrayList</c> of XML-RPC type parameters to invoke the request with.</param>
public ConfigurableKeepAliveXmlRpcRequest(String methodName, IList parameters, bool disableKeepAlive)
{
MethodName = methodName;
_params = parameters;
_disableKeepAlive = disableKeepAlive;
}
/// <summary>Send the request to the server.</summary>
/// <param name="url"><c>String</c> The url of the XML-RPC server.</param>
/// <returns><c>XmlRpcResponse</c> The response generated.</returns>
public XmlRpcResponse Send(String url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (request == null)
throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR,
XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " + url);
request.Method = "POST";
request.ContentType = "text/xml";
request.AllowWriteStreamBuffering = true;
request.KeepAlive = !_disableKeepAlive;
using (Stream stream = request.GetRequestStream())
{
using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.ASCII))
{
_serializer.Serialize(xml, this);
xml.Flush();
}
}
XmlRpcResponse resp;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream s = response.GetResponseStream())
{
using (StreamReader input = new StreamReader(s))
{
string inputXml = input.ReadToEnd();
try
{
resp = (XmlRpcResponse)_deserializer.Deserialize(inputXml);
}
catch (Exception e)
{
RequestResponse = inputXml;
throw e;
}
}
}
}
return resp;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using BitVector = Lucene.Net.Util.BitVector;
using Directory = Lucene.Net.Store.Directory;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IndexInput = Lucene.Net.Store.IndexInput;
namespace Lucene.Net.Index
{
sealed public class SegmentInfo : System.ICloneable
{
internal const int NO = - 1; // e.g. no norms; no deletes;
internal const int YES = 1; // e.g. have norms; have deletes;
internal const int CHECK_DIR = 0; // e.g. must check dir to see if there are norms/deletions
internal const int WITHOUT_GEN = 0; // a file name that has no GEN in it.
public string name; // unique name in dir
public int docCount; // number of docs in seg
public Directory dir; // where segment resides
private bool preLockless; // true if this is a segments file written before
// lock-less commits (2.1)
private long delGen; // current generation of del file; NO if there
// are no deletes; CHECK_DIR if it's a pre-2.1 segment
// (and we must check filesystem); YES or higher if
// there are deletes at generation N
private long[] normGen; // current generation of each field's norm file.
// If this array is null, for lockLess this means no
// separate norms. For preLockLess this means we must
// check filesystem. If this array is not null, its
// values mean: NO says this field has no separate
// norms; CHECK_DIR says it is a preLockLess segment and
// filesystem must be checked; >= YES says this field
// has separate norms with the specified generation
private sbyte isCompoundFile; // NO if it is not; YES if it is; CHECK_DIR if it's
// pre-2.1 (ie, must check file system to see
// if <name>.cfs and <name>.nrm exist)
private bool hasSingleNormFile; // true if this segment maintains norms in a single file;
// false otherwise
// this is currently false for segments populated by DocumentWriter
// and true for newly created merged segments (both
// compound and non compound).
private List<string> files; // cached list of files that this segment uses
// in the Directory
internal long sizeInBytes = - 1; // total byte size of all of our files (computed on demand)
private int docStoreOffset; // if this segment shares stored fields & vectors, this
// offset is where in that file this segment's docs begin
private string docStoreSegment; // name used to derive fields/vectors file we share with
// other segments
private bool docStoreIsCompoundFile; // whether doc store files are stored in compound file (*.cfx)
private int delCount; // How many deleted docs in this segment, or -1 if not yet known
// (if it's an older index)
private bool hasProx; // True if this segment has any fields with omitTf==false
public SegmentInfo(string name, int docCount, Directory dir)
{
this.name = name;
this.docCount = docCount;
this.dir = dir;
delGen = NO;
isCompoundFile = (sbyte) (CHECK_DIR);
preLockless = true;
hasSingleNormFile = false;
docStoreOffset = - 1;
docStoreSegment = name;
docStoreIsCompoundFile = false;
delCount = 0;
hasProx = true;
}
public SegmentInfo(string name, int docCount, Directory dir, bool isCompoundFile, bool hasSingleNormFile)
: this(name, docCount, dir, isCompoundFile, hasSingleNormFile, - 1, null, false, true)
{
}
public SegmentInfo(string name, int docCount, Directory dir, bool isCompoundFile, bool hasSingleNormFile, int docStoreOffset, string docStoreSegment, bool docStoreIsCompoundFile, bool hasProx)
: this(name, docCount, dir)
{
this.isCompoundFile = (sbyte) (isCompoundFile ? YES : NO);
this.hasSingleNormFile = hasSingleNormFile;
preLockless = false;
this.docStoreOffset = docStoreOffset;
this.docStoreSegment = docStoreSegment;
this.docStoreIsCompoundFile = docStoreIsCompoundFile;
this.hasProx = hasProx;
delCount = 0;
System.Diagnostics.Debug.Assert(docStoreOffset == - 1 || docStoreSegment != null);
}
/// <summary> Copy everything from src SegmentInfo into our instance.</summary>
internal void Reset(SegmentInfo src)
{
ClearFiles();
name = src.name;
docCount = src.docCount;
dir = src.dir;
preLockless = src.preLockless;
delGen = src.delGen;
docStoreOffset = src.docStoreOffset;
docStoreIsCompoundFile = src.docStoreIsCompoundFile;
if (src.normGen == null)
{
normGen = null;
}
else
{
normGen = new long[src.normGen.Length];
System.Array.Copy(src.normGen, 0, normGen, 0, src.normGen.Length);
}
isCompoundFile = src.isCompoundFile;
hasSingleNormFile = src.hasSingleNormFile;
delCount = src.delCount;
}
/// <summary> Construct a new SegmentInfo instance by reading a
/// previously saved SegmentInfo from input.
///
/// </summary>
/// <param name="dir">directory to load from
/// </param>
/// <param name="format">format of the segments info file
/// </param>
/// <param name="input">input handle to read segment info from
/// </param>
internal SegmentInfo(Directory dir, int format, IndexInput input)
{
this.dir = dir;
name = input.ReadString();
docCount = input.ReadInt();
if (format <= SegmentInfos.FORMAT_LOCKLESS)
{
delGen = input.ReadLong();
if (format <= SegmentInfos.FORMAT_SHARED_DOC_STORE)
{
docStoreOffset = input.ReadInt();
if (docStoreOffset != - 1)
{
docStoreSegment = input.ReadString();
docStoreIsCompoundFile = (1 == input.ReadByte());
}
else
{
docStoreSegment = name;
docStoreIsCompoundFile = false;
}
}
else
{
docStoreOffset = - 1;
docStoreSegment = name;
docStoreIsCompoundFile = false;
}
if (format <= SegmentInfos.FORMAT_SINGLE_NORM_FILE)
{
hasSingleNormFile = (1 == input.ReadByte());
}
else
{
hasSingleNormFile = false;
}
int numNormGen = input.ReadInt();
if (numNormGen == NO)
{
normGen = null;
}
else
{
normGen = new long[numNormGen];
for (int j = 0; j < numNormGen; j++)
{
normGen[j] = input.ReadLong();
}
}
isCompoundFile = (sbyte) input.ReadByte();
preLockless = (isCompoundFile == CHECK_DIR);
if (format <= SegmentInfos.FORMAT_DEL_COUNT)
{
delCount = input.ReadInt();
System.Diagnostics.Debug.Assert(delCount <= docCount);
}
else
{
delCount = -1;
}
if (format <= SegmentInfos.FORMAT_HAS_PROX)
hasProx = input.ReadByte() == 1;
else
hasProx = true;
}
else
{
delGen = CHECK_DIR;
normGen = null;
isCompoundFile = (sbyte) (CHECK_DIR);
preLockless = true;
hasSingleNormFile = false;
docStoreOffset = - 1;
docStoreIsCompoundFile = false;
docStoreSegment = null;
delCount = -1;
hasProx = true;
}
}
internal void SetNumFields(int numFields)
{
if (normGen == null)
{
// normGen is null if we loaded a pre-2.1 segment
// file, or, if this segments file hasn't had any
// norms set against it yet:
normGen = new long[numFields];
if (preLockless)
{
// Do nothing: thus leaving normGen[k]==CHECK_DIR (==0), so that later we know
// we have to check filesystem for norm files, because this is prelockless.
}
else
{
// This is a FORMAT_LOCKLESS segment, which means
// there are no separate norms:
for (int i = 0; i < numFields; i++)
{
normGen[i] = NO;
}
}
}
}
/// <summary>Returns total size in bytes of all of files used by
/// this segment.
/// </summary>
public /* changed for zoie 1.3.0: internal */ long SizeInBytes()
{
if (sizeInBytes == - 1)
{
List<string> files = Files();
int size = files.Count;
sizeInBytes = 0;
for (int i = 0; i < size; i++)
{
string fileName = files[i];
// We don't count bytes used by a shared doc store
// against this segment:
if (docStoreOffset == - 1 || !IndexFileNames.IsDocStoreFile(fileName))
sizeInBytes += dir.FileLength(fileName);
}
}
return sizeInBytes;
}
public /* changed for zoie 1.3.0: internal */ bool HasDeletions()
{
// Cases:
//
// delGen == NO: this means this segment was written
// by the LOCKLESS code and for certain does not have
// deletions yet
//
// delGen == CHECK_DIR: this means this segment was written by
// pre-LOCKLESS code which means we must check
// directory to see if .del file exists
//
// delGen >= YES: this means this segment was written by
// the LOCKLESS code and for certain has
// deletions
//
if (delGen == NO)
{
return false;
}
else if (delGen >= YES)
{
return true;
}
else
{
return dir.FileExists(GetDelFileName());
}
}
internal void AdvanceDelGen()
{
// delGen 0 is reserved for pre-LOCKLESS format
if (delGen == NO)
{
delGen = YES;
}
else
{
delGen++;
}
ClearFiles();
}
internal void ClearDelGen()
{
delGen = NO;
ClearFiles();
}
public object Clone()
{
SegmentInfo si = new SegmentInfo(name, docCount, dir);
si.isCompoundFile = isCompoundFile;
si.delGen = delGen;
si.delCount = delCount;
si.preLockless = preLockless;
si.hasSingleNormFile = hasSingleNormFile;
if (normGen != null)
{
si.normGen = new long[normGen.Length];
normGen.CopyTo(si.normGen, 0);
}
si.docStoreOffset = docStoreOffset;
si.docStoreSegment = docStoreSegment;
si.docStoreIsCompoundFile = docStoreIsCompoundFile;
si.docCount = docCount;
si.dir = dir;
si.files = files;
si.name = name;
si.sizeInBytes = sizeInBytes;
return si;
}
internal string GetDelFileName()
{
if (delGen == NO)
{
// In this case we know there is no deletion filename
// against this segment
return null;
}
else
{
string retVal = null;
string current = IndexFileNames.FileNameFromGeneration(name, "." + IndexFileNames.DELETES_EXTENSION, delGen);
if (this.dir.FileExists(current))
{
retVal = current;
}
else
{
string backwards = (name + "_" + System.Convert.ToString(delGen, 16) + "." + IndexFileNames.DELETES_EXTENSION);
if (this.dir.FileExists(backwards))
{
// we are dealing with the old name
retVal = backwards;
}
else
{
// no file, creating one, so use the new name
retVal = current;
}
}
return retVal;
}
}
/// <summary> Returns true if this field for this segment has saved a separate norms file (_<segment>_N.sX).
///
/// </summary>
/// <param name="fieldNumber">the field index to check
/// </param>
internal bool HasSeparateNorms(int fieldNumber)
{
if ((normGen == null && preLockless) || (normGen != null && normGen[fieldNumber] == CHECK_DIR))
{
// Must fallback to directory file exists check:
string fileName = name + ".s" + fieldNumber;
return dir.FileExists(fileName);
}
else if (normGen == null || normGen[fieldNumber] == NO)
{
return false;
}
else
{
return true;
}
}
/// <summary> Returns true if any fields in this segment have separate norms.</summary>
public /* changed for zoie 1.3.0: internal */ bool HasSeparateNorms()
{
if (normGen == null)
{
if (!preLockless)
{
// This means we were created w/ LOCKLESS code and no
// norms are written yet:
return false;
}
else
{
// This means this segment was saved with pre-LOCKLESS
// code. So we must fallback to the original
// directory list check:
string[] result = dir.List();
if (result == null)
{
throw new System.IO.IOException("cannot read directory " + dir + ": list() returned null");
}
string pattern;
pattern = name + ".s";
int patternLength = pattern.Length;
for (int i = 0; i < result.Length; i++)
{
if (result[i].StartsWith(pattern) && System.Char.IsDigit(result[i][patternLength]))
return true;
}
return false;
}
}
else
{
// This means this segment was saved with LOCKLESS
// code so we first check whether any normGen's are >= 1
// (meaning they definitely have separate norms):
for (int i = 0; i < normGen.Length; i++)
{
if (normGen[i] >= YES)
{
return true;
}
}
// Next we look for any == 0. These cases were
// pre-LOCKLESS and must be checked in directory:
for (int i = 0; i < normGen.Length; i++)
{
if (normGen[i] == CHECK_DIR)
{
if (HasSeparateNorms(i))
{
return true;
}
}
}
}
return false;
}
/// <summary> Increment the generation count for the norms file for
/// this field.
///
/// </summary>
/// <param name="fieldIndex">field whose norm file will be rewritten
/// </param>
internal void AdvanceNormGen(int fieldIndex)
{
if (normGen[fieldIndex] == NO)
{
normGen[fieldIndex] = YES;
}
else
{
normGen[fieldIndex]++;
}
ClearFiles();
}
/// <summary> Get the file name for the norms file for this field.
///
/// </summary>
/// <param name="number">field index
/// </param>
internal string GetNormFileName(int number)
{
string prefix;
long gen;
if (normGen == null)
{
gen = CHECK_DIR;
}
else
{
gen = normGen[number];
}
if (HasSeparateNorms(number))
{
// case 1: separate norm
prefix = ".s";
return IndexFileNames.FileNameFromGeneration(name, prefix + number, gen);
}
if (hasSingleNormFile)
{
// case 2: lockless (or nrm file exists) - single file for all norms
prefix = "." + IndexFileNames.NORMS_EXTENSION;
return IndexFileNames.FileNameFromGeneration(name, prefix, WITHOUT_GEN);
}
// case 3: norm file for each field
prefix = ".f";
return IndexFileNames.FileNameFromGeneration(name, prefix + number, WITHOUT_GEN);
}
/// <summary> Mark whether this segment is stored as a compound file.
///
/// </summary>
/// <param name="isCompoundFile">true if this is a compound file;
/// else, false
/// </param>
internal void SetUseCompoundFile(bool isCompoundFile)
{
if (isCompoundFile)
{
this.isCompoundFile = (sbyte) (YES);
}
else
{
this.isCompoundFile = (sbyte) (NO);
}
ClearFiles();
}
/// <summary> Returns true if this segment is stored as a compound
/// file; else, false.
/// </summary>
public /* changed for zoie 1.3.0: internal */ bool GetUseCompoundFile()
{
if (isCompoundFile == NO)
{
return false;
}
else if (isCompoundFile == YES)
{
return true;
}
else
{
return dir.FileExists(name + "." + IndexFileNames.COMPOUND_FILE_EXTENSION);
}
}
public /* changed for zoie 1.3.0: internal */ int GetDelCount()
{
if (delCount == -1)
{
if (HasDeletions())
{
string delFileName = GetDelFileName();
delCount = new BitVector(dir, delFileName).Count();
}
else
delCount = 0;
}
System.Diagnostics.Debug.Assert(delCount <= docCount);
return delCount;
}
internal void SetDelCount(int delCount)
{
this.delCount = delCount;
System.Diagnostics.Debug.Assert(delCount <= docCount);
}
internal int GetDocStoreOffset()
{
return docStoreOffset;
}
internal bool GetDocStoreIsCompoundFile()
{
return docStoreIsCompoundFile;
}
internal void SetDocStoreIsCompoundFile(bool v)
{
docStoreIsCompoundFile = v;
ClearFiles();
}
internal string GetDocStoreSegment()
{
return docStoreSegment;
}
internal void SetDocStoreOffset(int offset)
{
docStoreOffset = offset;
ClearFiles();
}
/// <summary> Save this segment's info.</summary>
internal void Write(IndexOutput output)
{
output.WriteString(name);
output.WriteInt(docCount);
output.WriteLong(delGen);
output.WriteInt(docStoreOffset);
if (docStoreOffset != - 1)
{
output.WriteString(docStoreSegment);
output.WriteByte((byte) (docStoreIsCompoundFile ? 1 : 0));
}
output.WriteByte((byte) (hasSingleNormFile ? 1 : 0));
if (normGen == null)
{
output.WriteInt(NO);
}
else
{
output.WriteInt(normGen.Length);
for (int j = 0; j < normGen.Length; j++)
{
output.WriteLong(normGen[j]);
}
}
output.WriteByte((byte)isCompoundFile);
output.WriteInt(delCount);
output.WriteByte((byte)(hasProx ? 1 : 0));
}
internal void SetHasProx(bool hasProx)
{
this.hasProx = hasProx;
ClearFiles();
}
internal bool GetHasProx()
{
return hasProx;
}
private void AddIfExists(System.Collections.Generic.List<string> files, string fileName)
{
if (dir.FileExists(fileName))
files.Add(fileName);
}
/*
* Return all files referenced by this SegmentInfo. The
* returns List is a locally cached List so you should not
* modify it.
*/
public List<string> Files()
{
if (files != null)
{
// Already cached:
return files;
}
files = new List<string>();
bool useCompoundFile = GetUseCompoundFile();
if (useCompoundFile)
{
files.Add(name + "." + IndexFileNames.COMPOUND_FILE_EXTENSION);
}
else
{
string[] exts = IndexFileNames.NON_STORE_INDEX_EXTENSIONS;
for (int i = 0; i < exts.Length; i++)
AddIfExists(files, name + "." + exts[i]);
}
if (docStoreOffset != - 1)
{
// We are sharing doc stores (stored fields, term
// vectors) with other segments
System.Diagnostics.Debug.Assert(docStoreSegment != null);
if (docStoreIsCompoundFile)
{
files.Add(docStoreSegment + "." + IndexFileNames.COMPOUND_FILE_STORE_EXTENSION);
}
else
{
string[] exts = IndexFileNames.STORE_INDEX_EXTENSIONS;
for (int i = 0; i < exts.Length; i++)
AddIfExists(files, docStoreSegment + "." + exts[i]);
}
}
else if (!useCompoundFile)
{
// We are not sharing, and, these files were not
// included in the compound file
string[] exts = IndexFileNames.STORE_INDEX_EXTENSIONS;
for (int i = 0; i < exts.Length; i++)
AddIfExists(files, name + "." + exts[i]);
}
string delFileName = this.GetDelFileName();
if (delFileName != null && (delGen >= YES || dir.FileExists(delFileName)))
{
files.Add(delFileName);
}
// Careful logic for norms files
if (normGen != null)
{
for (int i = 0; i < normGen.Length; i++)
{
long gen = normGen[i];
if (gen >= YES)
{
// Definitely a separate norm file, with generation:
files.Add(IndexFileNames.FileNameFromGeneration(name, "." + IndexFileNames.SEPARATE_NORMS_EXTENSION + i, gen));
}
else if (NO == gen)
{
// No separate norms but maybe plain norms
// in the non compound file case:
if (!hasSingleNormFile && !useCompoundFile)
{
string fileName = name + "." + IndexFileNames.PLAIN_NORMS_EXTENSION + i;
if (dir.FileExists(fileName))
{
files.Add(fileName);
}
}
}
else if (CHECK_DIR == gen)
{
// Pre-2.1: we have to check file existence
string fileName = null;
if (useCompoundFile)
{
fileName = name + "." + IndexFileNames.SEPARATE_NORMS_EXTENSION + i;
}
else if (!hasSingleNormFile)
{
fileName = name + "." + IndexFileNames.PLAIN_NORMS_EXTENSION + i;
}
if (fileName != null && dir.FileExists(fileName))
{
files.Add(fileName);
}
}
}
}
else if (preLockless || (!hasSingleNormFile && !useCompoundFile))
{
// Pre-2.1: we have to scan the dir to find all
// matching _X.sN/_X.fN files for our segment:
string prefix;
if (useCompoundFile)
prefix = name + "." + IndexFileNames.SEPARATE_NORMS_EXTENSION;
else
prefix = name + "." + IndexFileNames.PLAIN_NORMS_EXTENSION;
int prefixLength = prefix.Length;
string[] allFiles = dir.List();
if (allFiles == null)
{
throw new System.IO.IOException("cannot read directory " + dir + ": list() returned null");
}
for (int i = 0; i < allFiles.Length; i++)
{
string fileName = allFiles[i];
if (fileName.Length > prefixLength && System.Char.IsDigit(fileName[prefixLength]) && fileName.StartsWith(prefix))
{
files.Add(fileName);
}
}
}
return files;
}
/* Called whenever any change is made that affects which
* files this segment has. */
private void ClearFiles()
{
files = null;
sizeInBytes = - 1;
}
/// <summary>Used for debugging </summary>
public string SegString(Directory dir)
{
string cfs;
try
{
if (GetUseCompoundFile())
cfs = "c";
else
cfs = "C";
}
catch (System.IO.IOException)
{
cfs = "?";
}
string docStore;
if (docStoreOffset != - 1)
docStore = "->" + docStoreSegment;
else
docStore = "";
return name + ":" + cfs + (this.dir == dir ? "" : "x") + docCount + docStore;
}
/// <summary>We consider another SegmentInfo instance equal if it
/// has the same dir and same name.
/// </summary>
public override bool Equals(object obj)
{
SegmentInfo other;
try
{
other = (SegmentInfo) obj;
}
catch (System.InvalidCastException)
{
return false;
}
return other.dir == dir && other.name.Equals(name);
}
public override int GetHashCode()
{
return dir.GetHashCode() + name.GetHashCode();
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: The core libraries for the DotSpatial project.
//
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/17/2008 11:20:29 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using DotSpatial.NTSExtension;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
public class ShadedRelief : Descriptor, IShadedRelief
{
#region Events
/// <summary>
/// Occurs when the shading for this object has been altered.
/// </summary>
public event EventHandler ShadingChanged;
#endregion
#region Private Variables
float _ambientIntensity;
float _elevationFactor;
float _extrusion;
bool _hasChanged; // set to true when a property changes, and false again when the raster symbolizer calculates the HillShadeMap
bool _isUsed;
private double _lightDirection;
float _lightIntensity;
private double _zenithAngle;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of the ShadedRelief preset for elevation in feet and coordinates in decimal degrees
/// </summary>
public ShadedRelief()
: this(ElevationScenario.ElevationFeet_ProjectionDegrees)
{
}
/// <summary>
/// Creates a new instance of ShadedRelief based on some more common
/// elevation to geographic coordinate system scenarios
/// </summary>
public ShadedRelief(ElevationScenario scenario)
{
// These scenarios just give a quick approximate calc for the elevation factor
switch (scenario)
{
case ElevationScenario.ElevationCentiMeters_ProjectionDegrees:
_elevationFactor = 1F / (160934.4F * 69F);
break;
case ElevationScenario.ElevationCentiMeters_ProjectionFeet:
_elevationFactor = 0.0328084F;
break;
case ElevationScenario.ElevationCentiMeters_ProjectionMeters:
_elevationFactor = 1F / 100F;
break;
case ElevationScenario.ElevationFeet_ProjectionDegrees:
_elevationFactor = 1F / (5280F * 69F);
break;
case ElevationScenario.ElevationFeet_ProjectionFeet:
_elevationFactor = 1F;
break;
case ElevationScenario.ElevationFeet_ProjectionMeters:
_elevationFactor = 1F / 3.28F;
break;
case ElevationScenario.ElevationMeters_ProjectionDegrees:
_elevationFactor = 1F / (1609F * 69F);
break;
case ElevationScenario.ElevationMeters_ProjectionFeet:
_elevationFactor = 1F * 3.28F;
break;
case ElevationScenario.ElevationMeters_ProjectionMeters:
_elevationFactor = 1F;
break;
}
// Light direction is SouthEast at about 45 degrees up
_zenithAngle = 45;
_lightDirection = 45;
_lightIntensity = .7F;
_ambientIntensity = .8F;
_extrusion = 5;
//_elevationFactor = 0.0000027F;
_isUsed = false;
_hasChanged = false;
}
#endregion
#region Methods
/// <summary>
/// Returns a normalized vector in 3 dimensions representing the angle
/// of the light source.
/// </summary>
/// <returns></returns>
public FloatVector3 GetLightDirection()
{
double angle = LightDirection * Math.PI / 180;
double zAngle = ZenithAngle * Math.PI / 180;
double x = Math.Sin(angle) * Math.Cos(zAngle);
double y = Math.Cos(angle) * Math.Cos(zAngle);
double z = Math.Sin(zAngle);
return new FloatVector3((float)x, (float)y, (float)z);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a float specifying how strong the ambient directional light is. This should probably be about 1.
/// </summary>
[Category("Shaded Relief"), Description("Gets or sets a float specifying how strong the ambient directional light is. This should probably be about 1."),
Serialize("AmbientIntensity")]
public float AmbientIntensity
{
get { return _ambientIntensity; }
set
{
_ambientIntensity = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// This is kept separate from extrusion to reduce confusion. This is a conversion factor that will
/// convert the units of elevation into the same units that the latitude and longitude are stored in.
/// To convert feet to decimal degrees is around a factor of .00000274
/// </summary>
[Category("Shaded Relief"), Description("This is kept separate from extrusion to reduce confusion. This is a conversion factor that will convert the units of elevation into the same units that the latitude and longitude are stored in. To convert feet to decimal degrees is around a factor of .00000274"),
Serialize("ElevationFactor")]
public float ElevationFactor
{
get { return _elevationFactor; }
set
{
_elevationFactor = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// A float value expression that modifies the "height" of the apparent shaded relief. A value
/// of 1 should show the mountains at their true elevations, presuming the ElevationFactor is
/// correct. A value of 0 would be totally flat, while 2 would be twice the value.
/// </summary>
[Category("Shaded Relief"), Serialize("Extrusion"),
Description("A float value expression that modifies the height of the apparent shaded relief. A value of 1 should show the mountains at their true elevations, presuming the ElevationFactor is correct. A value of 0 would be totally flat, while 2 would be twice the value.")]
public float Extrusion
{
get { return _extrusion; }
set
{
_extrusion = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets a boolean value indicating whether the ShadedRelief should be used or not.
/// </summary>
[Category("Shaded Relief"), Serialize("IsUsed"),
Description("Gets or sets a boolean value indicating whether the ShadedRelief should be used or not.")]
public bool IsUsed
{
get { return _isUsed; }
set
{
_isUsed = value;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets the zenith angle for the light direction in degrees from 0 (at the horizon) to 90 (straight up).
/// </summary>
[Category("Shaded Relief"), Serialize("ZenithAngle"),
//Editor(typeof(ZenithEditor), typeof(UITypeEditor)),
Description("Gets or sets the zenith angle for the light direction in degrees from 0 (at the horizon) to 90 (straight up).")]
public double ZenithAngle
{
get { return _zenithAngle; }
set
{
_zenithAngle = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets a double that represents the light direction in degrees clockwise from North
/// </summary>
[Category("Shaded Relief"),
//Editor(typeof(AzimuthAngleEditor), typeof(UITypeEditor)), Serialize("LightDirection"),
Description("The azimuth angle in degrees for the light direction. The angle is measured clockwise from North.")]
public double LightDirection
{
get { return _lightDirection; }
set
{
_lightDirection = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// This specifies a float that should probably be around 1, which controls the light intensity.
/// </summary>
[Category("Shaded Relief"), Serialize("LightIntensity"),
Description("This specifies a float that should probably be around 1, which controls the light intensity.")]
public float LightIntensity
{
get { return _lightIntensity; }
set
{
_lightIntensity = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets whether or not the values have been changed on this ShadedRelief more recently than
/// a HillShade map has been calculated from it.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool HasChanged
{
get { return _hasChanged; }
set
{
_hasChanged = value;
OnShadingChanged();
}
}
#endregion
/// <summary>
/// Fires the ShadingChanged event
/// </summary>
protected virtual void OnShadingChanged()
{
if (ShadingChanged != null) ShadingChanged(this, EventArgs.Empty);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
namespace System.Net
{
internal static class SslStreamPal
{
private const string SecurityPackage = "Microsoft Unified Security Protocol Provider";
private const Interop.SspiCli.ContextFlags RequiredFlags =
Interop.SspiCli.ContextFlags.ReplayDetect |
Interop.SspiCli.ContextFlags.SequenceDetect |
Interop.SspiCli.ContextFlags.Confidentiality |
Interop.SspiCli.ContextFlags.AllocateMemory;
private const Interop.SspiCli.ContextFlags ServerRequiredFlags =
RequiredFlags | Interop.SspiCli.ContextFlags.AcceptStream;
public static Exception GetException(SecurityStatusPal status)
{
int win32Code = (int)GetInteropFromSecurityStatusPal(status.ErrorCode);
return new Win32Exception(win32Code);
}
internal const bool StartMutualAuthAsAnonymous = true;
public static void VerifyPackageInfo()
{
SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true);
}
public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool remoteCertRequired)
{
Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags);
int errorCode = SSPIWrapper.AcceptSecurityContext(
GlobalSSPI.SSPISecureChannel,
ref credentialsHandle,
ref context,
ServerRequiredFlags | (remoteCertRequired ? Interop.SspiCli.ContextFlags.MutualAuth : Interop.SspiCli.ContextFlags.Zero),
Interop.SspiCli.Endianness.Native,
inputBuffer,
outputBuffer,
ref unusedAttributes);
return GetSecurityStatusPalFromWin32Int(errorCode);
}
public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer)
{
Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags);
int errorCode = SSPIWrapper.InitializeSecurityContext(
GlobalSSPI.SSPISecureChannel,
ref credentialsHandle,
ref context,
targetName,
RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation,
Interop.SspiCli.Endianness.Native,
inputBuffer,
outputBuffer,
ref unusedAttributes);
return GetSecurityStatusPalFromWin32Int(errorCode);
}
public static SecurityStatusPal InitializeSecurityContext(SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer)
{
Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags);
int errorCode = SSPIWrapper.InitializeSecurityContext(
GlobalSSPI.SSPISecureChannel,
credentialsHandle,
ref context,
targetName,
RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation,
Interop.SspiCli.Endianness.Native,
inputBuffers,
outputBuffer,
ref unusedAttributes);
return GetSecurityStatusPalFromWin32Int(errorCode);
}
public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer)
{
int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer);
Interop.SspiCli.SecureCredential.Flags flags;
Interop.SspiCli.CredentialUse direction;
if (!isServer)
{
direction = Interop.SspiCli.CredentialUse.Outbound;
flags = Interop.SspiCli.SecureCredential.Flags.ValidateManual | Interop.SspiCli.SecureCredential.Flags.NoDefaultCred;
// CoreFX: always opt-in SCH_USE_STRONG_CRYPTO except for SSL3.
if (((protocolFlags & (Interop.SChannel.SP_PROT_TLS1_0 | Interop.SChannel.SP_PROT_TLS1_1 | Interop.SChannel.SP_PROT_TLS1_2)) != 0)
&& (policy != EncryptionPolicy.AllowNoEncryption) && (policy != EncryptionPolicy.NoEncryption))
{
flags |= Interop.SspiCli.SecureCredential.Flags.UseStrongCrypto;
}
}
else
{
direction = Interop.SspiCli.CredentialUse.Inbound;
flags = Interop.SspiCli.SecureCredential.Flags.Zero;
}
Interop.SspiCli.SecureCredential secureCredential = CreateSecureCredential(
Interop.SspiCli.SecureCredential.CurrentVersion,
certificate,
flags,
protocolFlags,
policy);
return AcquireCredentialsHandle(direction, secureCredential);
}
public static SecurityStatusPal EncryptMessage(SafeDeleteContext securityContext, byte[] writeBuffer, int size, int headerSize, int trailerSize, out int resultSize)
{
// Encryption using SCHANNEL requires 4 buffers: header, payload, trailer, empty.
SecurityBuffer[] securityBuffer = new SecurityBuffer[4];
securityBuffer[0] = new SecurityBuffer(writeBuffer, 0, headerSize, SecurityBufferType.Header);
securityBuffer[1] = new SecurityBuffer(writeBuffer, headerSize, size, SecurityBufferType.Data);
securityBuffer[2] = new SecurityBuffer(writeBuffer, headerSize + size, trailerSize, SecurityBufferType.Trailer);
securityBuffer[3] = new SecurityBuffer(null, SecurityBufferType.Empty);
int errorCode = SSPIWrapper.EncryptMessage(GlobalSSPI.SSPISecureChannel, securityContext, securityBuffer, 0);
if (errorCode != 0)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SslStreamPal.Windows: SecureChannel#" + LoggingHash.HashString(securityContext) + "::Encrypt ERROR" + errorCode.ToString("x"));
}
resultSize = 0;
}
else
{
// The full buffer may not be used.
resultSize = securityBuffer[0].size + securityBuffer[1].size + securityBuffer[2].size;
}
return GetSecurityStatusPalFromWin32Int(errorCode);
}
public static SecurityStatusPal DecryptMessage(SafeDeleteContext securityContext, byte[] buffer, ref int offset, ref int count)
{
// Decryption using SCHANNEL requires four buffers.
SecurityBuffer[] decspc = new SecurityBuffer[4];
decspc[0] = new SecurityBuffer(buffer, offset, count, SecurityBufferType.Data);
decspc[1] = new SecurityBuffer(null, SecurityBufferType.Empty);
decspc[2] = new SecurityBuffer(null, SecurityBufferType.Empty);
decspc[3] = new SecurityBuffer(null, SecurityBufferType.Empty);
Interop.SecurityStatus errorCode = (Interop.SecurityStatus)SSPIWrapper.DecryptMessage(
GlobalSSPI.SSPISecureChannel,
securityContext,
decspc,
0);
count = 0;
for (int i = 0; i < decspc.Length; i++)
{
// Successfully decoded data and placed it at the following position in the buffer,
if ((errorCode == Interop.SecurityStatus.OK && decspc[i].type == SecurityBufferType.Data)
// or we failed to decode the data, here is the encoded data.
|| (errorCode != Interop.SecurityStatus.OK && decspc[i].type == SecurityBufferType.Extra))
{
offset = decspc[i].offset;
count = decspc[i].size;
break;
}
}
return new SecurityStatusPal(SecurityStatusPalErrorCodeFromInterop(errorCode));
}
public unsafe static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute)
{
return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute);
}
public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes)
{
streamSizes = SSPIWrapper.QueryContextAttributes(
GlobalSSPI.SSPISecureChannel,
securityContext,
Interop.SspiCli.ContextAttribute.StreamSizes) as StreamSizes;
}
public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo)
{
connectionInfo = SSPIWrapper.QueryContextAttributes(
GlobalSSPI.SSPISecureChannel,
securityContext,
Interop.SspiCli.ContextAttribute.ConnectionInfo) as SslConnectionInfo;
}
private static int GetProtocolFlagsFromSslProtocols(SslProtocols protocols, bool isServer)
{
int protocolFlags = (int)protocols;
if (isServer)
{
protocolFlags &= Interop.SChannel.ServerProtocolMask;
}
else
{
protocolFlags &= Interop.SChannel.ClientProtocolMask;
}
return protocolFlags;
}
private static Interop.SspiCli.SecureCredential CreateSecureCredential(
int version,
X509Certificate certificate,
Interop.SspiCli.SecureCredential.Flags flags,
int protocols, EncryptionPolicy policy)
{
var credential = new Interop.SspiCli.SecureCredential()
{
rootStore = IntPtr.Zero,
phMappers = IntPtr.Zero,
palgSupportedAlgs = IntPtr.Zero,
certContextArray = IntPtr.Zero,
cCreds = 0,
cMappers = 0,
cSupportedAlgs = 0,
dwSessionLifespan = 0,
reserved = 0
};
if (policy == EncryptionPolicy.RequireEncryption)
{
// Prohibit null encryption cipher.
credential.dwMinimumCipherStrength = 0;
credential.dwMaximumCipherStrength = 0;
}
else if (policy == EncryptionPolicy.AllowNoEncryption)
{
// Allow null encryption cipher in addition to other ciphers.
credential.dwMinimumCipherStrength = -1;
credential.dwMaximumCipherStrength = 0;
}
else if (policy == EncryptionPolicy.NoEncryption)
{
// Suppress all encryption and require null encryption cipher only
credential.dwMinimumCipherStrength = -1;
credential.dwMaximumCipherStrength = -1;
}
else
{
throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(policy));
}
credential.version = version;
credential.dwFlags = flags;
credential.grbitEnabledProtocols = protocols;
if (certificate != null)
{
credential.certContextArray = certificate.Handle;
credential.cCreds = 1;
}
return credential;
}
//
// Security: we temporarily reset thread token to open the handle under process account.
//
private static SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiCli.CredentialUse credUsage, Interop.SspiCli.SecureCredential secureCredential)
{
// First try without impersonation, if it fails, then try the process account.
// I.E. We don't know which account the certificate context was created under.
try
{
//
// For app-compat we want to ensure the credential are accessed under >>process<< acount.
//
return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () =>
{
return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential);
});
}
catch
{
return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential);
}
}
private static SecurityStatusPal GetSecurityStatusPalFromWin32Int(int win32SecurityStatus)
{
return new SecurityStatusPal(SecurityStatusPalErrorCodeFromInterop((Interop.SecurityStatus)win32SecurityStatus));
}
private static SecurityStatusPalErrorCode SecurityStatusPalErrorCodeFromInterop(Interop.SecurityStatus win32SecurityStatus)
{
switch (win32SecurityStatus)
{
case Interop.SecurityStatus.OK:
return SecurityStatusPalErrorCode.OK;
case Interop.SecurityStatus.ContinueNeeded:
return SecurityStatusPalErrorCode.ContinueNeeded;
case Interop.SecurityStatus.CompleteNeeded:
return SecurityStatusPalErrorCode.CompleteNeeded;
case Interop.SecurityStatus.CompAndContinue:
return SecurityStatusPalErrorCode.CompAndContinue;
case Interop.SecurityStatus.ContextExpired:
return SecurityStatusPalErrorCode.ContextExpired;
case Interop.SecurityStatus.CredentialsNeeded:
return SecurityStatusPalErrorCode.CredentialsNeeded;
case Interop.SecurityStatus.Renegotiate:
return SecurityStatusPalErrorCode.Renegotiate;
case Interop.SecurityStatus.OutOfMemory:
return SecurityStatusPalErrorCode.OutOfMemory;
case Interop.SecurityStatus.InvalidHandle:
return SecurityStatusPalErrorCode.InvalidHandle;
case Interop.SecurityStatus.Unsupported:
return SecurityStatusPalErrorCode.Unsupported;
case Interop.SecurityStatus.TargetUnknown:
return SecurityStatusPalErrorCode.TargetUnknown;
case Interop.SecurityStatus.InternalError:
return SecurityStatusPalErrorCode.InternalError;
case Interop.SecurityStatus.PackageNotFound:
return SecurityStatusPalErrorCode.PackageNotFound;
case Interop.SecurityStatus.NotOwner:
return SecurityStatusPalErrorCode.NotOwner;
case Interop.SecurityStatus.CannotInstall:
return SecurityStatusPalErrorCode.CannotInstall;
case Interop.SecurityStatus.InvalidToken:
return SecurityStatusPalErrorCode.InvalidToken;
case Interop.SecurityStatus.CannotPack:
return SecurityStatusPalErrorCode.CannotPack;
case Interop.SecurityStatus.QopNotSupported:
return SecurityStatusPalErrorCode.QopNotSupported;
case Interop.SecurityStatus.NoImpersonation:
return SecurityStatusPalErrorCode.NoImpersonation;
case Interop.SecurityStatus.LogonDenied:
return SecurityStatusPalErrorCode.LogonDenied;
case Interop.SecurityStatus.UnknownCredentials:
return SecurityStatusPalErrorCode.UnknownCredentials;
case Interop.SecurityStatus.NoCredentials:
return SecurityStatusPalErrorCode.NoCredentials;
case Interop.SecurityStatus.MessageAltered:
return SecurityStatusPalErrorCode.MessageAltered;
case Interop.SecurityStatus.OutOfSequence:
return SecurityStatusPalErrorCode.OutOfSequence;
case Interop.SecurityStatus.NoAuthenticatingAuthority:
return SecurityStatusPalErrorCode.NoAuthenticatingAuthority;
case Interop.SecurityStatus.IncompleteMessage:
return SecurityStatusPalErrorCode.IncompleteMessage;
case Interop.SecurityStatus.IncompleteCredentials:
return SecurityStatusPalErrorCode.IncompleteCredentials;
case Interop.SecurityStatus.BufferNotEnough:
return SecurityStatusPalErrorCode.BufferNotEnough;
case Interop.SecurityStatus.WrongPrincipal:
return SecurityStatusPalErrorCode.WrongPrincipal;
case Interop.SecurityStatus.TimeSkew:
return SecurityStatusPalErrorCode.TimeSkew;
case Interop.SecurityStatus.UntrustedRoot:
return SecurityStatusPalErrorCode.UntrustedRoot;
case Interop.SecurityStatus.IllegalMessage:
return SecurityStatusPalErrorCode.IllegalMessage;
case Interop.SecurityStatus.CertUnknown:
return SecurityStatusPalErrorCode.CertUnknown;
case Interop.SecurityStatus.CertExpired:
return SecurityStatusPalErrorCode.CertExpired;
case Interop.SecurityStatus.AlgorithmMismatch:
return SecurityStatusPalErrorCode.AlgorithmMismatch;
case Interop.SecurityStatus.SecurityQosFailed:
return SecurityStatusPalErrorCode.SecurityQosFailed;
case Interop.SecurityStatus.SmartcardLogonRequired:
return SecurityStatusPalErrorCode.SmartcardLogonRequired;
case Interop.SecurityStatus.UnsupportedPreauth:
return SecurityStatusPalErrorCode.UnsupportedPreauth;
case Interop.SecurityStatus.BadBinding:
return SecurityStatusPalErrorCode.BadBinding;
default:
Debug.Fail("Unknown Interop.SecurityStatus value: " + win32SecurityStatus);
throw new InternalException();
}
}
private static Interop.SecurityStatus GetInteropFromSecurityStatusPal(SecurityStatusPalErrorCode status)
{
switch (status)
{
case SecurityStatusPalErrorCode.NotSet:
Debug.Fail("SecurityStatus NotSet");
throw new InternalException();
case SecurityStatusPalErrorCode.OK:
return Interop.SecurityStatus.OK;
case SecurityStatusPalErrorCode.ContinueNeeded:
return Interop.SecurityStatus.ContinueNeeded;
case SecurityStatusPalErrorCode.CompleteNeeded:
return Interop.SecurityStatus.CompleteNeeded;
case SecurityStatusPalErrorCode.CompAndContinue:
return Interop.SecurityStatus.CompAndContinue;
case SecurityStatusPalErrorCode.ContextExpired:
return Interop.SecurityStatus.ContextExpired;
case SecurityStatusPalErrorCode.CredentialsNeeded:
return Interop.SecurityStatus.CredentialsNeeded;
case SecurityStatusPalErrorCode.Renegotiate:
return Interop.SecurityStatus.Renegotiate;
case SecurityStatusPalErrorCode.OutOfMemory:
return Interop.SecurityStatus.OutOfMemory;
case SecurityStatusPalErrorCode.InvalidHandle:
return Interop.SecurityStatus.InvalidHandle;
case SecurityStatusPalErrorCode.Unsupported:
return Interop.SecurityStatus.Unsupported;
case SecurityStatusPalErrorCode.TargetUnknown:
return Interop.SecurityStatus.TargetUnknown;
case SecurityStatusPalErrorCode.InternalError:
return Interop.SecurityStatus.InternalError;
case SecurityStatusPalErrorCode.PackageNotFound:
return Interop.SecurityStatus.PackageNotFound;
case SecurityStatusPalErrorCode.NotOwner:
return Interop.SecurityStatus.NotOwner;
case SecurityStatusPalErrorCode.CannotInstall:
return Interop.SecurityStatus.CannotInstall;
case SecurityStatusPalErrorCode.InvalidToken:
return Interop.SecurityStatus.InvalidToken;
case SecurityStatusPalErrorCode.CannotPack:
return Interop.SecurityStatus.CannotPack;
case SecurityStatusPalErrorCode.QopNotSupported:
return Interop.SecurityStatus.QopNotSupported;
case SecurityStatusPalErrorCode.NoImpersonation:
return Interop.SecurityStatus.NoImpersonation;
case SecurityStatusPalErrorCode.LogonDenied:
return Interop.SecurityStatus.LogonDenied;
case SecurityStatusPalErrorCode.UnknownCredentials:
return Interop.SecurityStatus.UnknownCredentials;
case SecurityStatusPalErrorCode.NoCredentials:
return Interop.SecurityStatus.NoCredentials;
case SecurityStatusPalErrorCode.MessageAltered:
return Interop.SecurityStatus.MessageAltered;
case SecurityStatusPalErrorCode.OutOfSequence:
return Interop.SecurityStatus.OutOfSequence;
case SecurityStatusPalErrorCode.NoAuthenticatingAuthority:
return Interop.SecurityStatus.NoAuthenticatingAuthority;
case SecurityStatusPalErrorCode.IncompleteMessage:
return Interop.SecurityStatus.IncompleteMessage;
case SecurityStatusPalErrorCode.IncompleteCredentials:
return Interop.SecurityStatus.IncompleteCredentials;
case SecurityStatusPalErrorCode.BufferNotEnough:
return Interop.SecurityStatus.BufferNotEnough;
case SecurityStatusPalErrorCode.WrongPrincipal:
return Interop.SecurityStatus.WrongPrincipal;
case SecurityStatusPalErrorCode.TimeSkew:
return Interop.SecurityStatus.TimeSkew;
case SecurityStatusPalErrorCode.UntrustedRoot:
return Interop.SecurityStatus.UntrustedRoot;
case SecurityStatusPalErrorCode.IllegalMessage:
return Interop.SecurityStatus.IllegalMessage;
case SecurityStatusPalErrorCode.CertUnknown:
return Interop.SecurityStatus.CertUnknown;
case SecurityStatusPalErrorCode.CertExpired:
return Interop.SecurityStatus.CertExpired;
case SecurityStatusPalErrorCode.AlgorithmMismatch:
return Interop.SecurityStatus.AlgorithmMismatch;
case SecurityStatusPalErrorCode.SecurityQosFailed:
return Interop.SecurityStatus.SecurityQosFailed;
case SecurityStatusPalErrorCode.SmartcardLogonRequired:
return Interop.SecurityStatus.SmartcardLogonRequired;
case SecurityStatusPalErrorCode.UnsupportedPreauth:
return Interop.SecurityStatus.UnsupportedPreauth;
case SecurityStatusPalErrorCode.BadBinding:
return Interop.SecurityStatus.BadBinding;
default:
Debug.Fail("Unknown Interop.SecurityStatus value: " + status);
throw new InternalException();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.Authentication.WsFederation
{
public class WsFederationTest
{
[Fact]
public async Task VerifySchemeDefaults()
{
var services = new ServiceCollection();
services.AddAuthentication().AddWsFederation();
var sp = services.BuildServiceProvider();
var schemeProvider = sp.GetRequiredService<IAuthenticationSchemeProvider>();
var scheme = await schemeProvider.GetSchemeAsync(WsFederationDefaults.AuthenticationScheme);
Assert.NotNull(scheme);
Assert.Equal("WsFederationHandler", scheme.HandlerType.Name);
Assert.Equal(WsFederationDefaults.AuthenticationScheme, scheme.DisplayName);
}
[Fact]
public async Task MissingConfigurationThrows()
{
using var host = new HostBuilder()
.ConfigureWebHost(builder =>
builder.UseTestServer()
.Configure(ConfigureApp)
.ConfigureServices(services =>
{
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddWsFederation();
}))
.Build();
await host.StartAsync();
using var server = host.GetTestServer();
var httpClient = server.CreateClient();
// Verify if the request is redirected to STS with right parameters
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => httpClient.GetAsync("/"));
Assert.Equal("Provide MetadataAddress, Configuration, or ConfigurationManager to WsFederationOptions", exception.Message);
}
[Fact]
public async Task ChallengeRedirects()
{
var httpClient = await CreateClient();
// Verify if the request is redirected to STS with right parameters
var response = await httpClient.GetAsync("/");
Assert.Equal("https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/wsfed", response.Headers.Location.GetLeftPart(System.UriPartial.Path));
var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query);
Assert.Equal("http://Automation1", queryItems["wtrealm"]);
Assert.True(queryItems["wctx"].ToString().Equals(CustomStateDataFormat.ValidStateData), "wctx does not equal ValidStateData");
Assert.Equal(httpClient.BaseAddress + "signin-wsfed", queryItems["wreply"]);
Assert.Equal("wsignin1.0", queryItems["wa"]);
}
[Fact]
public async Task MapWillNotAffectRedirect()
{
var httpClient = await CreateClient();
// Verify if the request is redirected to STS with right parameters
var response = await httpClient.GetAsync("/mapped-challenge");
Assert.Equal("https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/wsfed", response.Headers.Location.GetLeftPart(System.UriPartial.Path));
var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query);
Assert.Equal("http://Automation1", queryItems["wtrealm"]);
Assert.True(queryItems["wctx"].ToString().Equals(CustomStateDataFormat.ValidStateData), "wctx does not equal ValidStateData");
Assert.Equal(httpClient.BaseAddress + "signin-wsfed", queryItems["wreply"]);
Assert.Equal("wsignin1.0", queryItems["wa"]);
}
[Fact]
public async Task PreMappedWillAffectRedirect()
{
var httpClient = await CreateClient();
// Verify if the request is redirected to STS with right parameters
var response = await httpClient.GetAsync("/premapped-challenge");
Assert.Equal("https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/wsfed", response.Headers.Location.GetLeftPart(System.UriPartial.Path));
var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query);
Assert.Equal("http://Automation1", queryItems["wtrealm"]);
Assert.True(queryItems["wctx"].ToString().Equals(CustomStateDataFormat.ValidStateData), "wctx does not equal ValidStateData");
Assert.Equal(httpClient.BaseAddress + "premapped-challenge/signin-wsfed", queryItems["wreply"]);
Assert.Equal("wsignin1.0", queryItems["wa"]);
}
[Fact]
public async Task ValidTokenIsAccepted()
{
var httpClient = await CreateClient();
// Verify if the request is redirected to STS with right parameters
var response = await httpClient.GetAsync("/");
var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query);
var request = new HttpRequestMessage(HttpMethod.Post, queryItems["wreply"]);
CopyCookies(response, request);
request.Content = CreateSignInContent("WsFederation/ValidToken.xml", queryItems["wctx"]);
response = await httpClient.SendAsync(request);
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
request = new HttpRequestMessage(HttpMethod.Get, response.Headers.Location);
CopyCookies(response, request);
response = await httpClient.SendAsync(request);
// Did the request end in the actual resource requested for
Assert.Equal(WsFederationDefaults.AuthenticationScheme, await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task ValidUnsolicitedTokenIsRefused()
{
var httpClient = await CreateClient();
var form = CreateSignInContent("WsFederation/ValidToken.xml", suppressWctx: true);
var exception = await Assert.ThrowsAsync<Exception>(() => httpClient.PostAsync(httpClient.BaseAddress + "signin-wsfed", form));
Assert.Contains("Unsolicited logins are not allowed.", exception.InnerException.Message);
}
[Fact]
public async Task ValidUnsolicitedTokenIsAcceptedWhenAllowed()
{
var httpClient = await CreateClient(allowUnsolicited: true);
var form = CreateSignInContent("WsFederation/ValidToken.xml", suppressWctx: true);
var response = await httpClient.PostAsync(httpClient.BaseAddress + "signin-wsfed", form);
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
var request = new HttpRequestMessage(HttpMethod.Get, response.Headers.Location);
CopyCookies(response, request);
response = await httpClient.SendAsync(request);
// Did the request end in the actual resource requested for
Assert.Equal(WsFederationDefaults.AuthenticationScheme, await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task InvalidTokenIsRejected()
{
var httpClient = await CreateClient();
// Verify if the request is redirected to STS with right parameters
var response = await httpClient.GetAsync("/");
var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query);
var request = new HttpRequestMessage(HttpMethod.Post, queryItems["wreply"]);
CopyCookies(response, request);
request.Content = CreateSignInContent("WsFederation/InvalidToken.xml", queryItems["wctx"]);
response = await httpClient.SendAsync(request);
// Did the request end in the actual resource requested for
Assert.Equal("AuthenticationFailed", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task RemoteSignoutRequestTriggersSignout()
{
var httpClient = await CreateClient();
var response = await httpClient.GetAsync("/signin-wsfed?wa=wsignoutcleanup1.0");
response.EnsureSuccessStatusCode();
var cookie = response.Headers.GetValues(HeaderNames.SetCookie).Single();
Assert.Equal(".AspNetCore.Cookies=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; samesite=lax; httponly", cookie);
Assert.Equal("OnRemoteSignOut", response.Headers.GetValues("EventHeader").Single());
Assert.Equal("", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task EventsResolvedFromDI()
{
using var host = new HostBuilder()
.ConfigureWebHost(builder =>
builder.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<MyWsFedEvents>();
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddWsFederation(options =>
{
options.Wtrealm = "http://Automation1";
options.MetadataAddress = "https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/federationmetadata/2007-06/federationmetadata.xml";
options.BackchannelHttpHandler = new WaadMetadataDocumentHandler();
options.EventsType = typeof(MyWsFedEvents);
});
})
.Configure(app =>
{
app.Run(context => context.ChallengeAsync());
}))
.Build();
await host.StartAsync();
using var server = host.GetTestServer();
var result = await server.CreateClient().GetAsync("");
Assert.Contains("CustomKey=CustomValue", result.Headers.Location.Query);
}
private class MyWsFedEvents : WsFederationEvents
{
public override Task RedirectToIdentityProvider(RedirectContext context)
{
context.ProtocolMessage.SetParameter("CustomKey", "CustomValue");
return base.RedirectToIdentityProvider(context);
}
}
private FormUrlEncodedContent CreateSignInContent(string tokenFile, string wctx = null, bool suppressWctx = false)
{
var kvps = new List<KeyValuePair<string, string>>();
kvps.Add(new KeyValuePair<string, string>("wa", "wsignin1.0"));
kvps.Add(new KeyValuePair<string, string>("wresult", File.ReadAllText(tokenFile)));
if (!string.IsNullOrEmpty(wctx))
{
kvps.Add(new KeyValuePair<string, string>("wctx", wctx));
}
if (suppressWctx)
{
kvps.Add(new KeyValuePair<string, string>("suppressWctx", "true"));
}
return new FormUrlEncodedContent(kvps);
}
private void CopyCookies(HttpResponseMessage response, HttpRequestMessage request)
{
var cookies = SetCookieHeaderValue.ParseList(response.Headers.GetValues(HeaderNames.SetCookie).ToList());
foreach (var cookie in cookies)
{
if (cookie.Value.HasValue)
{
request.Headers.Add(HeaderNames.Cookie, new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
}
}
}
private async Task<HttpClient> CreateClient(bool allowUnsolicited = false)
{
var host = new HostBuilder()
.ConfigureWebHost(builder =>
builder.UseTestServer()
.Configure(ConfigureApp)
.ConfigureServices(services =>
{
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddWsFederation(options =>
{
options.Wtrealm = "http://Automation1";
options.MetadataAddress = "https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/federationmetadata/2007-06/federationmetadata.xml";
options.BackchannelHttpHandler = new WaadMetadataDocumentHandler();
options.StateDataFormat = new CustomStateDataFormat();
options.SecurityTokenHandlers = new List<ISecurityTokenValidator>() { new TestSecurityTokenValidator() };
options.UseTokenLifetime = false;
options.AllowUnsolicitedLogins = allowUnsolicited;
options.Events = new WsFederationEvents()
{
OnMessageReceived = context =>
{
if (!context.ProtocolMessage.Parameters.TryGetValue("suppressWctx", out var suppress))
{
Assert.True(context.ProtocolMessage.Wctx.Equals("customValue"), "wctx is not my custom value");
}
context.HttpContext.Items["MessageReceived"] = true;
return Task.FromResult(0);
},
OnRedirectToIdentityProvider = context =>
{
if (context.ProtocolMessage.IsSignInMessage)
{
// Sign in message
context.ProtocolMessage.Wctx = "customValue";
}
return Task.FromResult(0);
},
OnSecurityTokenReceived = context =>
{
context.HttpContext.Items["SecurityTokenReceived"] = true;
return Task.FromResult(0);
},
OnSecurityTokenValidated = context =>
{
Assert.True((bool)context.HttpContext.Items["MessageReceived"], "MessageReceived notification not invoked");
Assert.True((bool)context.HttpContext.Items["SecurityTokenReceived"], "SecurityTokenReceived notification not invoked");
if (context.Principal != null)
{
var identity = context.Principal.Identities.Single();
identity.AddClaim(new Claim("ReturnEndpoint", "true"));
identity.AddClaim(new Claim("Authenticated", "true"));
identity.AddClaim(new Claim(identity.RoleClaimType, "Guest", ClaimValueTypes.String));
}
return Task.FromResult(0);
},
OnAuthenticationFailed = context =>
{
context.HttpContext.Items["AuthenticationFailed"] = true;
//Change the request url to something different and skip Wsfed. This new url will handle the request and let us know if this notification was invoked.
context.HttpContext.Request.Path = new PathString("/AuthenticationFailed");
context.SkipHandler();
return Task.FromResult(0);
},
OnRemoteSignOut = context =>
{
context.Response.Headers["EventHeader"] = "OnRemoteSignOut";
return Task.FromResult(0);
}
};
});
}))
.Build();
await host.StartAsync();
var server = host.GetTestServer();
return server.CreateClient();
}
private void ConfigureApp(IApplicationBuilder app)
{
app.Map("/PreMapped-Challenge", mapped =>
{
mapped.UseAuthentication();
mapped.Run(async context =>
{
await context.ChallengeAsync(WsFederationDefaults.AuthenticationScheme);
});
});
app.UseAuthentication();
app.Map("/Logout", subApp =>
{
subApp.Run(async context =>
{
if (context.User.Identity.IsAuthenticated)
{
var authProperties = new AuthenticationProperties() { RedirectUri = context.Request.GetEncodedUrl() };
await context.SignOutAsync(WsFederationDefaults.AuthenticationScheme, authProperties);
await context.Response.WriteAsync("Signing out...");
}
else
{
await context.Response.WriteAsync("SignedOut");
}
});
});
app.Map("/AuthenticationFailed", subApp =>
{
subApp.Run(async context =>
{
await context.Response.WriteAsync("AuthenticationFailed");
});
});
app.Map("/signout-wsfed", subApp =>
{
subApp.Run(async context =>
{
await context.Response.WriteAsync("signout-wsfed");
});
});
app.Map("/mapped-challenge", subApp =>
{
subApp.Run(async context =>
{
await context.ChallengeAsync(WsFederationDefaults.AuthenticationScheme);
});
});
app.Run(async context =>
{
var result = context.AuthenticateAsync();
if (context.User == null || !context.User.Identity.IsAuthenticated)
{
await context.ChallengeAsync(WsFederationDefaults.AuthenticationScheme);
await context.Response.WriteAsync("Unauthorized");
}
else
{
var identity = context.User.Identities.Single();
if (identity.NameClaimType == "Name_Failed" && identity.RoleClaimType == "Role_Failed")
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync("SignIn_Failed");
}
else if (!identity.HasClaim("Authenticated", "true") || !identity.HasClaim("ReturnEndpoint", "true") || !identity.HasClaim(identity.RoleClaimType, "Guest"))
{
await context.Response.WriteAsync("Provider not invoked");
return;
}
else
{
await context.Response.WriteAsync(WsFederationDefaults.AuthenticationScheme);
}
}
});
}
private class WaadMetadataDocumentHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var metadata = File.ReadAllText(@"WsFederation/federationmetadata.xml");
var newResponse = new HttpResponseMessage() { Content = new StringContent(metadata, Encoding.UTF8, "text/xml") };
return Task.FromResult<HttpResponseMessage>(newResponse);
}
}
}
}
| |
// 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.IO;
using SharpDX.DXGI;
using SharpDX.IO;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// An unmanaged buffer of pixels.
/// </summary>
public sealed class PixelBuffer
{
private int width;
private int height;
private DXGI.Format format;
private int rowStride;
private int bufferStride;
private readonly IntPtr dataPointer;
private int pixelSize;
/// <summary>
/// True when RowStride == sizeof(pixelformat) * width
/// </summary>
private bool isStrictRowStride;
/// <summary>
/// Initializes a new instance of the <see cref="PixelBuffer" /> struct.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">The format.</param>
/// <param name="rowStride">The row pitch.</param>
/// <param name="bufferStride">The slice pitch.</param>
/// <param name="dataPointer">The pixels.</param>
public PixelBuffer(int width, int height, Format format, int rowStride, int bufferStride, IntPtr dataPointer)
{
if (dataPointer == IntPtr.Zero)
throw new ArgumentException("Pointer cannot be equal to IntPtr.Zero", "dataPointer");
this.width = width;
this.height = height;
this.format = format;
this.rowStride = rowStride;
this.bufferStride = bufferStride;
this.dataPointer = dataPointer;
this.pixelSize = FormatHelper.SizeOfInBytes(this.format);
this.isStrictRowStride = (pixelSize * width) == rowStride;
}
/// <summary>
/// Gets the width.
/// </summary>
/// <value>The width.</value>
public int Width { get { return width; } }
/// <summary>
/// Gets the height.
/// </summary>
/// <value>The height.</value>
public int Height { get { return height; } }
/// <summary>
/// Gets the format (this value can be changed)
/// </summary>
/// <value>The format.</value>
public Format Format
{
get
{
return format;
}
set
{
if (PixelSize != (int)FormatHelper.SizeOfInBytes(value))
{
throw new ArgumentException(string.Format("Format [{0}] doesn't have same pixel size in bytes than current format [{1}]", value, format));
}
format = value;
}
}
/// <summary>
/// Gets the pixel size in bytes.
/// </summary>
/// <value>The pixel size in bytes.</value>
public int PixelSize { get { return this.pixelSize; } }
/// <summary>
/// Gets the row stride in number of bytes.
/// </summary>
/// <value>The row stride in number of bytes.</value>
public int RowStride { get { return this.rowStride; } }
/// <summary>
/// Gets the total size in bytes of this pixel buffer.
/// </summary>
/// <value>The size in bytes of the pixel buffer.</value>
public int BufferStride { get { return this.bufferStride; } }
/// <summary>
/// Gets the pointer to the pixel buffer.
/// </summary>
/// <value>The pointer to the pixel buffer.</value>
public IntPtr DataPointer { get { return this.dataPointer; } }
/// <summary>
/// Copies this pixel buffer to a destination pixel buffer.
/// </summary>
/// <param name="pixelBuffer">The destination pixel buffer.</param>
/// <remarks>
/// The destination pixel buffer must have exactly the same dimensions (width, height) and format than this instance.
/// Destination buffer can have different row stride.
/// </remarks>
public unsafe void CopyTo(PixelBuffer pixelBuffer)
{
// Check that buffers are identical
if (this.Width != pixelBuffer.Width
|| this.Height != pixelBuffer.Height
|| PixelSize != FormatHelper.SizeOfInBytes(pixelBuffer.Format))
{
throw new ArgumentException("Invalid destination pixelBufferArray. Mush have same Width, Height and Format", "pixelBuffer");
}
// If buffers have same size, than we can copy it directly
if (this.BufferStride == pixelBuffer.BufferStride)
{
Utilities.CopyMemory(pixelBuffer.DataPointer, this.DataPointer, this.BufferStride);
}
else
{
var srcPointer = (byte*)this.DataPointer;
var dstPointer = (byte*)pixelBuffer.DataPointer;
var rowStride = Math.Min(RowStride, pixelBuffer.RowStride);
// Copy per scanline
for(int i = 0; i < Height; i++)
{
Utilities.CopyMemory(new IntPtr(dstPointer), new IntPtr(srcPointer), rowStride);
srcPointer += this.RowStride;
dstPointer += pixelBuffer.RowStride;
}
}
}
/// <summary>
/// Saves this pixel buffer to a file.
/// </summary>
/// <param name="fileName">The destination file.</param>
/// <param name="fileType">Specify the output format.</param>
/// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
public void Save(string fileName, ImageFileType fileType)
{
using (var imageStream = new NativeFileStream(fileName, NativeFileMode.Create, NativeFileAccess.Write))
{
Save(imageStream, fileType);
}
}
/// <summary>
/// Saves this pixel buffer to a stream.
/// </summary>
/// <param name="imageStream">The destination stream.</param>
/// <param name="fileType">Specify the output format.</param>
/// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
public void Save(Stream imageStream, ImageFileType fileType)
{
var description = new ImageDescription()
{
Width = this.width,
Height = this.height,
Depth = 1,
ArraySize = 1,
Dimension = TextureDimension.Texture2D,
Format = this.format,
MipLevels = 1,
};
Image.Save(new [] {this}, 1, description, imageStream, fileType);
}
/// <summary>
/// Gets the pixel value at a specified position.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="x">The x-coordinate.</param>
/// <param name="y">The y-coordinate.</param>
/// <returns>The pixel value.</returns>
/// <remarks>
/// Caution, this method doesn't check bounding.
/// </remarks>
public unsafe T GetPixel<T>(int x, int y) where T : struct
{
return Utilities.Read<T>(new IntPtr(((byte*)this.DataPointer + RowStride * y + x * PixelSize)));
}
/// <summary>
/// Gets the pixel value at a specified position.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="x">The x-coordinate.</param>
/// <param name="y">The y-coordinate.</param>
/// <param name="value">The pixel value.</param>
/// <remarks>
/// Caution, this method doesn't check bounding.
/// </remarks>
public unsafe void SetPixel<T>(int x, int y, T value) where T : struct
{
Utilities.Write(new IntPtr((byte*)this.DataPointer + RowStride * y + x * PixelSize), ref value);
}
/// <summary>
/// Gets scanline pixels from the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="yOffset">The y line offset.</param>
/// <returns>Scanline pixels from the buffer</returns>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <see cref="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public T[] GetPixels<T>(int yOffset = 0) where T : struct
{
var sizeOfOutputPixel = Utilities.SizeOf<T>();
var totalSize = Width * Height * pixelSize;
if ((totalSize % sizeOfOutputPixel) != 0)
throw new ArgumentException(string.Format("Invalid sizeof(T), not a multiple of current size [{0}]in bytes ", totalSize));
var buffer = new T[totalSize / sizeOfOutputPixel];
GetPixels(buffer, yOffset);
return buffer;
}
/// <summary>
/// Gets scanline pixels from the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="pixels">An allocated scanline pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <returns>Scanline pixels from the buffer</returns>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <see cref="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public void GetPixels<T>(T[] pixels, int yOffset = 0) where T : struct
{
GetPixels(pixels, yOffset, 0, pixels.Length);
}
/// <summary>
/// Gets scanline pixels from the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="pixels">An allocated scanline pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <param name="pixelIndex">Offset into the destination <see cref="pixels"/> buffer.</param>
/// <param name="pixelCount">Number of pixels to write into the destination <see cref="pixels"/> buffer.</param>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <see cref="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public unsafe void GetPixels<T>(T[] pixels, int yOffset, int pixelIndex, int pixelCount) where T : struct
{
var pixelPointer = (byte*)this.DataPointer + yOffset * rowStride;
if (isStrictRowStride)
{
Utilities.Read(new IntPtr(pixelPointer), pixels, 0, pixelCount);
}
else
{
var sizeOfOutputPixel = Utilities.SizeOf<T>() * pixelCount;
var sizePerWidth = sizeOfOutputPixel / Width;
var remainingPixels = sizeOfOutputPixel % Width;
for(int i = 0; i < sizePerWidth; i++)
{
Utilities.Read(new IntPtr(pixelPointer), pixels, pixelIndex, Width);
pixelPointer += rowStride;
pixelIndex += Width;
}
if (remainingPixels > 0)
{
Utilities.Read(new IntPtr(pixelPointer), pixels, pixelIndex, remainingPixels);
}
}
}
/// <summary>
/// Sets scanline pixels to the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="sourcePixels">Source pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <see cref="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public void SetPixels<T>(T[] sourcePixels, int yOffset = 0) where T : struct
{
SetPixels(sourcePixels, yOffset, 0, sourcePixels.Length);
}
/// <summary>
/// Sets scanline pixels to the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="sourcePixels">Source pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <param name="pixelIndex">Offset into the source <see cref="sourcePixels"/> buffer.</param>
/// <param name="pixelCount">Number of pixels to write into the source <see cref="sourcePixels"/> buffer.</param>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <see cref="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public unsafe void SetPixels<T>(T[] sourcePixels, int yOffset, int pixelIndex, int pixelCount) where T : struct
{
var pixelPointer = (byte*)this.DataPointer + yOffset * rowStride;
if (isStrictRowStride)
{
Utilities.Write(new IntPtr(pixelPointer), sourcePixels, 0, pixelCount);
}
else
{
var sizeOfOutputPixel = Utilities.SizeOf<T>() * pixelCount;
var sizePerWidth = sizeOfOutputPixel / Width;
var remainingPixels = sizeOfOutputPixel % Width;
for (int i = 0; i < sizePerWidth; i++)
{
Utilities.Write(new IntPtr(pixelPointer), sourcePixels, pixelIndex, Width);
pixelPointer += rowStride;
pixelIndex += Width;
}
if (remainingPixels > 0)
{
Utilities.Write(new IntPtr(pixelPointer), sourcePixels, pixelIndex, remainingPixels);
}
}
}
}
}
| |
#pragma warning disable 1591
using Braintree.Exceptions;
using System;
using System.Net;
using System.IO;
#if netcore
using System.Net.Http;
#else
using System.IO.Compression;
#endif
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
namespace Braintree
{
public class BraintreeService : HttpService
{
public string ApiVersion = "6";
public BraintreeService(Configuration configuration) : base(configuration) { }
public XmlNode Get(string URL)
{
return GetXmlResponse(URL, "GET", null, null);
}
public Task<XmlNode> GetAsync(string URL)
{
return GetXmlResponseAsync(URL, "GET", null, null);
}
internal XmlNode Delete(string URL)
{
return GetXmlResponse(URL, "DELETE", null, null);
}
internal Task<XmlNode> DeleteAsync(string URL)
{
return GetXmlResponseAsync(URL, "DELETE", null, null);
}
public XmlNode Post(string URL, Request requestBody)
{
return GetXmlResponse(URL, "POST", requestBody, null);
}
public Task<XmlNode> PostAsync(string URL, Request requestBody)
{
return GetXmlResponseAsync(URL, "POST", requestBody, null);
}
internal XmlNode Post(string URL)
{
return Post(URL, null);
}
internal Task<XmlNode> PostAsync(string URL)
{
return PostAsync(URL, null);
}
public XmlNode PostMultipart(string URL, Request requestBody, FileStream file)
{
return GetXmlResponse(URL, "POST", requestBody, file);
}
public Task<XmlNode> PostMultipartAsync(string URL, Request requestBody, FileStream file)
{
return GetXmlResponseAsync(URL, "POST", requestBody, file);
}
public XmlNode Put(string URL)
{
return Put(URL, null);
}
public Task<XmlNode> PutAsync(string URL)
{
return PutAsync(URL, null);
}
internal XmlNode Put(string URL, Request requestBody)
{
return GetXmlResponse(URL, "PUT", requestBody, null);
}
internal Task<XmlNode> PutAsync(string URL, Request requestBody)
{
return GetXmlResponseAsync(URL, "PUT", requestBody, null);
}
#if netcore
public override void SetRequestHeaders(HttpRequestMessage request)
{
base.SetRequestHeaders(request);
request.Headers.Add("X-ApiVersion", ApiVersion);
request.Headers.Add("Accept", "application/xml");
}
#else
public override void SetRequestHeaders(HttpWebRequest request)
{
base.SetRequestHeaders(request);
request.Headers.Add("X-ApiVersion", ApiVersion);
request.Accept = "application/xml";
}
#endif
private XmlNode GetXmlResponse(string URL, string method, Request requestBody, FileStream file)
{
#if netcore
try
{
var request = GetHttpRequest(Environment.GatewayURL + URL, method);
if (requestBody != null && file == null)
{
var xmlPrefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
var content = xmlPrefix + requestBody.ToXml();
var utf8_string = encoding.GetString(encoding.GetBytes(content));
request.Content = new StringContent(utf8_string, encoding, "application/xml");
request.Content.Headers.ContentLength = System.Text.UTF8Encoding.UTF8.GetByteCount(utf8_string);
}
if (file != null)
{
string formDataBoundary = GenerateMultipartFormBoundary();
Dictionary<string, object> postParameters = requestBody.ToDictionary();
postParameters.Add("file", file);
byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
var ascii_string = Encoding.ASCII.GetString(formData);
request.Content = new StringContent(ascii_string);
request.Content.Headers.Remove("Content-Type");
request.Content.Headers.TryAddWithoutValidation("Content-Type", MultipartFormContentType(formDataBoundary));
request.Content.Headers.ContentLength = System.Text.UTF8Encoding.UTF8.GetByteCount(ascii_string);
}
var response = GetHttpResponse(request);
return StringToXmlNode(response);
}
catch (HttpRequestException e)
{
throw e;
}
#else
var request = GetHttpRequest(Environment.GatewayURL + URL, method);
if (requestBody != null && file == null)
{
var xmlPrefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
byte[] buffer = encoding.GetBytes(xmlPrefix + requestBody.ToXml());
request.ContentType = "application/xml";
request.ContentLength = buffer.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, 0, buffer.Length);
}
}
if (file != null)
{
string formDataBoundary = GenerateMultipartFormBoundary();
request.ContentType = MultipartFormContentType(formDataBoundary);
Dictionary<string, object> postParameters = requestBody.ToDictionary();
postParameters.Add("file", file);
byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
request.ContentLength = formData.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
}
var response = GetHttpResponse(request);
return StringToXmlNode(response);
#endif
}
private async Task<XmlNode> GetXmlResponseAsync(string URL, string method, Request requestBody, FileStream file)
{
#if netcore
try
{
var request = GetHttpRequest(Environment.GatewayURL + URL, method);
if (requestBody != null && file == null)
{
var xmlPrefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
var content = xmlPrefix + requestBody.ToXml();
var utf8_string = encoding.GetString(encoding.GetBytes(content));
request.Content = new StringContent(utf8_string, encoding, "application/xml");
request.Content.Headers.ContentLength = System.Text.UTF8Encoding.UTF8.GetByteCount(utf8_string);
}
if (file != null)
{
string formDataBoundary = GenerateMultipartFormBoundary();
Dictionary<string, object> postParameters = requestBody.ToDictionary();
postParameters.Add("file", file);
byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
var ascii_string = Encoding.ASCII.GetString(formData);
request.Content = new StringContent(ascii_string);
request.Content.Headers.Remove("Content-Type");
request.Content.Headers.TryAddWithoutValidation("Content-Type", MultipartFormContentType(formDataBoundary));
request.Content.Headers.ContentLength = System.Text.UTF8Encoding.UTF8.GetByteCount(ascii_string);
}
var response = await GetHttpResponseAsync(request).ConfigureAwait(false);
return StringToXmlNode(response);
}
catch (HttpRequestException e)
{
throw e;
}
#else
var request = GetHttpRequest(Environment.GatewayURL + URL, method);
if (requestBody != null && file == null)
{
var xmlPrefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
byte[] buffer = encoding.GetBytes(xmlPrefix + requestBody.ToXml());
request.ContentType = "application/xml";
request.ContentLength = buffer.Length;
using (Stream requestStream = await request.GetRequestStreamAsync().ConfigureAwait(false))
{
await requestStream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
}
}
if (file != null)
{
string formDataBoundary = GenerateMultipartFormBoundary();
request.ContentType = MultipartFormContentType(formDataBoundary);
Dictionary<string, object> postParameters = requestBody.ToDictionary();
postParameters.Add("file", file);
byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
request.ContentLength = formData.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
}
var response = await GetHttpResponseAsync(request).ConfigureAwait(false);
return StringToXmlNode(response);
#endif
}
private XmlNode ParseResponseStreamAsXml(Stream stream)
{
string body = ParseResponseStream(stream);
return StringToXmlNode(body);
}
internal XmlNode StringToXmlNode(string xml)
{
if (xml.Trim() == "")
{
return new XmlDocument();
}
else
{
var doc = new XmlDocument();
#if netcore
// XmlResolver property defaults to null
#else
doc.XmlResolver = null;
#endif
doc.LoadXml(xml);
if (doc.ChildNodes.Count == 1) return doc.ChildNodes[0];
return doc.ChildNodes[1];
}
}
public string BaseMerchantURL()
{
return Environment.GatewayURL + MerchantPath();
}
public string MerchantPath()
{
return "/merchants/" + MerchantId;
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// EmailSettings
/// </summary>
[DataContract]
public partial class EmailSettings : IEquatable<EmailSettings>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="EmailSettings" /> class.
/// </summary>
/// <param name="marketingEspDomainUser">marketingEspDomainUser.</param>
/// <param name="marketingEspDomainUuid">marketingEspDomainUuid.</param>
/// <param name="marketingEspFriendlyName">marketingEspFriendlyName.</param>
/// <param name="postcardFromAddress1">postcardFromAddress1.</param>
/// <param name="postcardFromAddress2">postcardFromAddress2.</param>
/// <param name="postcardFromCity">postcardFromCity.</param>
/// <param name="postcardFromName">postcardFromName.</param>
/// <param name="postcardFromPostalCode">postcardFromPostalCode.</param>
/// <param name="postcardFromState">postcardFromState.</param>
/// <param name="transactionalEspDomainUser">transactionalEspDomainUser.</param>
/// <param name="transactionalEspDomainUuid">transactionalEspDomainUuid.</param>
/// <param name="transactionalEspFriendlyName">transactionalEspFriendlyName.</param>
public EmailSettings(string marketingEspDomainUser = default(string), string marketingEspDomainUuid = default(string), string marketingEspFriendlyName = default(string), string postcardFromAddress1 = default(string), string postcardFromAddress2 = default(string), string postcardFromCity = default(string), string postcardFromName = default(string), string postcardFromPostalCode = default(string), string postcardFromState = default(string), string transactionalEspDomainUser = default(string), string transactionalEspDomainUuid = default(string), string transactionalEspFriendlyName = default(string))
{
this.MarketingEspDomainUser = marketingEspDomainUser;
this.MarketingEspDomainUuid = marketingEspDomainUuid;
this.MarketingEspFriendlyName = marketingEspFriendlyName;
this.PostcardFromAddress1 = postcardFromAddress1;
this.PostcardFromAddress2 = postcardFromAddress2;
this.PostcardFromCity = postcardFromCity;
this.PostcardFromName = postcardFromName;
this.PostcardFromPostalCode = postcardFromPostalCode;
this.PostcardFromState = postcardFromState;
this.TransactionalEspDomainUser = transactionalEspDomainUser;
this.TransactionalEspDomainUuid = transactionalEspDomainUuid;
this.TransactionalEspFriendlyName = transactionalEspFriendlyName;
}
/// <summary>
/// Gets or Sets MarketingEspDomainUser
/// </summary>
[DataMember(Name="marketing_esp_domain_user", EmitDefaultValue=false)]
public string MarketingEspDomainUser { get; set; }
/// <summary>
/// Gets or Sets MarketingEspDomainUuid
/// </summary>
[DataMember(Name="marketing_esp_domain_uuid", EmitDefaultValue=false)]
public string MarketingEspDomainUuid { get; set; }
/// <summary>
/// Gets or Sets MarketingEspFriendlyName
/// </summary>
[DataMember(Name="marketing_esp_friendly_name", EmitDefaultValue=false)]
public string MarketingEspFriendlyName { get; set; }
/// <summary>
/// Gets or Sets PostcardFromAddress1
/// </summary>
[DataMember(Name="postcard_from_address1", EmitDefaultValue=false)]
public string PostcardFromAddress1 { get; set; }
/// <summary>
/// Gets or Sets PostcardFromAddress2
/// </summary>
[DataMember(Name="postcard_from_address2", EmitDefaultValue=false)]
public string PostcardFromAddress2 { get; set; }
/// <summary>
/// Gets or Sets PostcardFromCity
/// </summary>
[DataMember(Name="postcard_from_city", EmitDefaultValue=false)]
public string PostcardFromCity { get; set; }
/// <summary>
/// Gets or Sets PostcardFromName
/// </summary>
[DataMember(Name="postcard_from_name", EmitDefaultValue=false)]
public string PostcardFromName { get; set; }
/// <summary>
/// Gets or Sets PostcardFromPostalCode
/// </summary>
[DataMember(Name="postcard_from_postal_code", EmitDefaultValue=false)]
public string PostcardFromPostalCode { get; set; }
/// <summary>
/// Gets or Sets PostcardFromState
/// </summary>
[DataMember(Name="postcard_from_state", EmitDefaultValue=false)]
public string PostcardFromState { get; set; }
/// <summary>
/// Gets or Sets TransactionalEspDomainUser
/// </summary>
[DataMember(Name="transactional_esp_domain_user", EmitDefaultValue=false)]
public string TransactionalEspDomainUser { get; set; }
/// <summary>
/// Gets or Sets TransactionalEspDomainUuid
/// </summary>
[DataMember(Name="transactional_esp_domain_uuid", EmitDefaultValue=false)]
public string TransactionalEspDomainUuid { get; set; }
/// <summary>
/// Gets or Sets TransactionalEspFriendlyName
/// </summary>
[DataMember(Name="transactional_esp_friendly_name", EmitDefaultValue=false)]
public string TransactionalEspFriendlyName { 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 EmailSettings {\n");
sb.Append(" MarketingEspDomainUser: ").Append(MarketingEspDomainUser).Append("\n");
sb.Append(" MarketingEspDomainUuid: ").Append(MarketingEspDomainUuid).Append("\n");
sb.Append(" MarketingEspFriendlyName: ").Append(MarketingEspFriendlyName).Append("\n");
sb.Append(" PostcardFromAddress1: ").Append(PostcardFromAddress1).Append("\n");
sb.Append(" PostcardFromAddress2: ").Append(PostcardFromAddress2).Append("\n");
sb.Append(" PostcardFromCity: ").Append(PostcardFromCity).Append("\n");
sb.Append(" PostcardFromName: ").Append(PostcardFromName).Append("\n");
sb.Append(" PostcardFromPostalCode: ").Append(PostcardFromPostalCode).Append("\n");
sb.Append(" PostcardFromState: ").Append(PostcardFromState).Append("\n");
sb.Append(" TransactionalEspDomainUser: ").Append(TransactionalEspDomainUser).Append("\n");
sb.Append(" TransactionalEspDomainUuid: ").Append(TransactionalEspDomainUuid).Append("\n");
sb.Append(" TransactionalEspFriendlyName: ").Append(TransactionalEspFriendlyName).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as EmailSettings);
}
/// <summary>
/// Returns true if EmailSettings instances are equal
/// </summary>
/// <param name="input">Instance of EmailSettings to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(EmailSettings input)
{
if (input == null)
return false;
return
(
this.MarketingEspDomainUser == input.MarketingEspDomainUser ||
(this.MarketingEspDomainUser != null &&
this.MarketingEspDomainUser.Equals(input.MarketingEspDomainUser))
) &&
(
this.MarketingEspDomainUuid == input.MarketingEspDomainUuid ||
(this.MarketingEspDomainUuid != null &&
this.MarketingEspDomainUuid.Equals(input.MarketingEspDomainUuid))
) &&
(
this.MarketingEspFriendlyName == input.MarketingEspFriendlyName ||
(this.MarketingEspFriendlyName != null &&
this.MarketingEspFriendlyName.Equals(input.MarketingEspFriendlyName))
) &&
(
this.PostcardFromAddress1 == input.PostcardFromAddress1 ||
(this.PostcardFromAddress1 != null &&
this.PostcardFromAddress1.Equals(input.PostcardFromAddress1))
) &&
(
this.PostcardFromAddress2 == input.PostcardFromAddress2 ||
(this.PostcardFromAddress2 != null &&
this.PostcardFromAddress2.Equals(input.PostcardFromAddress2))
) &&
(
this.PostcardFromCity == input.PostcardFromCity ||
(this.PostcardFromCity != null &&
this.PostcardFromCity.Equals(input.PostcardFromCity))
) &&
(
this.PostcardFromName == input.PostcardFromName ||
(this.PostcardFromName != null &&
this.PostcardFromName.Equals(input.PostcardFromName))
) &&
(
this.PostcardFromPostalCode == input.PostcardFromPostalCode ||
(this.PostcardFromPostalCode != null &&
this.PostcardFromPostalCode.Equals(input.PostcardFromPostalCode))
) &&
(
this.PostcardFromState == input.PostcardFromState ||
(this.PostcardFromState != null &&
this.PostcardFromState.Equals(input.PostcardFromState))
) &&
(
this.TransactionalEspDomainUser == input.TransactionalEspDomainUser ||
(this.TransactionalEspDomainUser != null &&
this.TransactionalEspDomainUser.Equals(input.TransactionalEspDomainUser))
) &&
(
this.TransactionalEspDomainUuid == input.TransactionalEspDomainUuid ||
(this.TransactionalEspDomainUuid != null &&
this.TransactionalEspDomainUuid.Equals(input.TransactionalEspDomainUuid))
) &&
(
this.TransactionalEspFriendlyName == input.TransactionalEspFriendlyName ||
(this.TransactionalEspFriendlyName != null &&
this.TransactionalEspFriendlyName.Equals(input.TransactionalEspFriendlyName))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.MarketingEspDomainUser != null)
hashCode = hashCode * 59 + this.MarketingEspDomainUser.GetHashCode();
if (this.MarketingEspDomainUuid != null)
hashCode = hashCode * 59 + this.MarketingEspDomainUuid.GetHashCode();
if (this.MarketingEspFriendlyName != null)
hashCode = hashCode * 59 + this.MarketingEspFriendlyName.GetHashCode();
if (this.PostcardFromAddress1 != null)
hashCode = hashCode * 59 + this.PostcardFromAddress1.GetHashCode();
if (this.PostcardFromAddress2 != null)
hashCode = hashCode * 59 + this.PostcardFromAddress2.GetHashCode();
if (this.PostcardFromCity != null)
hashCode = hashCode * 59 + this.PostcardFromCity.GetHashCode();
if (this.PostcardFromName != null)
hashCode = hashCode * 59 + this.PostcardFromName.GetHashCode();
if (this.PostcardFromPostalCode != null)
hashCode = hashCode * 59 + this.PostcardFromPostalCode.GetHashCode();
if (this.PostcardFromState != null)
hashCode = hashCode * 59 + this.PostcardFromState.GetHashCode();
if (this.TransactionalEspDomainUser != null)
hashCode = hashCode * 59 + this.TransactionalEspDomainUser.GetHashCode();
if (this.TransactionalEspDomainUuid != null)
hashCode = hashCode * 59 + this.TransactionalEspDomainUuid.GetHashCode();
if (this.TransactionalEspFriendlyName != null)
hashCode = hashCode * 59 + this.TransactionalEspFriendlyName.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Network
{
/// <summary>
/// The Windows Azure Network management API provides a RESTful set of web
/// services that interact with Windows Azure Networks service to manage
/// your network resrources. The API has entities that capture the
/// relationship between an end user and the Windows Azure Networks
/// service.
/// </summary>
public partial class NetworkResourceProviderClient : ServiceClient<NetworkResourceProviderClient>, INetworkResourceProviderClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IApplicationGatewayOperations _applicationGateways;
/// <summary>
/// The Network Resource Provider API includes operations managing the
/// application gateways for your subscription.
/// </summary>
public virtual IApplicationGatewayOperations ApplicationGateways
{
get { return this._applicationGateways; }
}
private ILoadBalancerOperations _loadBalancers;
/// <summary>
/// The Network Resource Provider API includes operations for managing
/// the load balancers for your subscription.
/// </summary>
public virtual ILoadBalancerOperations LoadBalancers
{
get { return this._loadBalancers; }
}
private ILocalNetworkGatewayOperations _localNetworkGateways;
/// <summary>
/// The Network Resource Provider API includes operations for managing
/// the Virtual network Gateway for your subscription.
/// </summary>
public virtual ILocalNetworkGatewayOperations LocalNetworkGateways
{
get { return this._localNetworkGateways; }
}
private INetworkInterfaceOperations _networkInterfaces;
/// <summary>
/// The Network Resource Provider API includes operations for managing
/// the subnets for your subscription.
/// </summary>
public virtual INetworkInterfaceOperations NetworkInterfaces
{
get { return this._networkInterfaces; }
}
private INetworkSecurityGroupOperations _networkSecurityGroups;
/// <summary>
/// The Network Resource Provider API includes operations for managing
/// the NetworkSecurityGroups for your subscription.
/// </summary>
public virtual INetworkSecurityGroupOperations NetworkSecurityGroups
{
get { return this._networkSecurityGroups; }
}
private IPublicIpAddressOperations _publicIpAddresses;
/// <summary>
/// The Network Resource Provider API includes operations for managing
/// the PublicIPAddress for your subscription.
/// </summary>
public virtual IPublicIpAddressOperations PublicIpAddresses
{
get { return this._publicIpAddresses; }
}
private ISecurityRuleOperations _securityRules;
/// <summary>
/// The Network Resource Provider API includes operations for managing
/// the SecurityRules for your subscription.
/// </summary>
public virtual ISecurityRuleOperations SecurityRules
{
get { return this._securityRules; }
}
private ISubnetOperations _subnets;
/// <summary>
/// The Network Resource Provider API includes operations for managing
/// the subnets for your subscription.
/// </summary>
public virtual ISubnetOperations Subnets
{
get { return this._subnets; }
}
private IUsageOperations _usages;
/// <summary>
/// Operations for listing usage.
/// </summary>
public virtual IUsageOperations Usages
{
get { return this._usages; }
}
private IVirtualNetworkGatewayConnectionOperations _virtualNetworkGatewayConnections;
/// <summary>
/// The Network Resource Provider API includes operations for managing
/// the Virtual network Gateway for your subscription.
/// </summary>
public virtual IVirtualNetworkGatewayConnectionOperations VirtualNetworkGatewayConnections
{
get { return this._virtualNetworkGatewayConnections; }
}
private IVirtualNetworkGatewayOperations _virtualNetworkGateways;
/// <summary>
/// The Network Resource Provider API includes operations for managing
/// the Virtual network Gateway for your subscription.
/// </summary>
public virtual IVirtualNetworkGatewayOperations VirtualNetworkGateways
{
get { return this._virtualNetworkGateways; }
}
private IVirtualNetworkOperations _virtualNetworks;
/// <summary>
/// The Network Resource Provider API includes operations for managing
/// the Virtual Networks for your subscription.
/// </summary>
public virtual IVirtualNetworkOperations VirtualNetworks
{
get { return this._virtualNetworks; }
}
/// <summary>
/// Initializes a new instance of the NetworkResourceProviderClient
/// class.
/// </summary>
public NetworkResourceProviderClient()
: base()
{
this._applicationGateways = new ApplicationGatewayOperations(this);
this._loadBalancers = new LoadBalancerOperations(this);
this._localNetworkGateways = new LocalNetworkGatewayOperations(this);
this._networkInterfaces = new NetworkInterfaceOperations(this);
this._networkSecurityGroups = new NetworkSecurityGroupOperations(this);
this._publicIpAddresses = new PublicIpAddressOperations(this);
this._securityRules = new SecurityRuleOperations(this);
this._subnets = new SubnetOperations(this);
this._usages = new UsageOperations(this);
this._virtualNetworkGatewayConnections = new VirtualNetworkGatewayConnectionOperations(this);
this._virtualNetworkGateways = new VirtualNetworkGatewayOperations(this);
this._virtualNetworks = new VirtualNetworkOperations(this);
this._apiVersion = "2015-05-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the NetworkResourceProviderClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public NetworkResourceProviderClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the NetworkResourceProviderClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public NetworkResourceProviderClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the NetworkResourceProviderClient
/// class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public NetworkResourceProviderClient(HttpClient httpClient)
: base(httpClient)
{
this._applicationGateways = new ApplicationGatewayOperations(this);
this._loadBalancers = new LoadBalancerOperations(this);
this._localNetworkGateways = new LocalNetworkGatewayOperations(this);
this._networkInterfaces = new NetworkInterfaceOperations(this);
this._networkSecurityGroups = new NetworkSecurityGroupOperations(this);
this._publicIpAddresses = new PublicIpAddressOperations(this);
this._securityRules = new SecurityRuleOperations(this);
this._subnets = new SubnetOperations(this);
this._usages = new UsageOperations(this);
this._virtualNetworkGatewayConnections = new VirtualNetworkGatewayConnectionOperations(this);
this._virtualNetworkGateways = new VirtualNetworkGatewayOperations(this);
this._virtualNetworks = new VirtualNetworkOperations(this);
this._apiVersion = "2015-05-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the NetworkResourceProviderClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public NetworkResourceProviderClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the NetworkResourceProviderClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public NetworkResourceProviderClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// NetworkResourceProviderClient instance
/// </summary>
/// <param name='client'>
/// Instance of NetworkResourceProviderClient to clone to
/// </param>
protected override void Clone(ServiceClient<NetworkResourceProviderClient> client)
{
base.Clone(client);
if (client is NetworkResourceProviderClient)
{
NetworkResourceProviderClient clonedClient = ((NetworkResourceProviderClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// Checks whether a domain name in the cloudapp.net zone is available
/// for use.
/// </summary>
/// <param name='location'>
/// Required. The location of the domain name
/// </param>
/// <param name='domainNameLabel'>
/// Required. The domain name to be verified. It must conform to the
/// following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for CheckDnsNameAvailability Api servive call
/// </returns>
public async Task<DnsNameAvailabilityResponse> CheckDnsNameAvailabilityAsync(string location, string domainNameLabel, CancellationToken cancellationToken)
{
// Validate
if (location == null)
{
throw new ArgumentNullException("location");
}
if (domainNameLabel == null)
{
throw new ArgumentNullException("domainNameLabel");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("domainNameLabel", domainNameLabel);
TracingAdapter.Enter(invocationId, this, "CheckDnsNameAvailabilityAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + "Microsoft.Network";
url = url + "/locations/";
url = url + Uri.EscapeDataString(location);
url = url + "/CheckDnsNameAvailability";
List<string> queryParameters = new List<string>();
queryParameters.Add("domainNameLabel=" + Uri.EscapeDataString(domainNameLabel));
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DnsNameAvailabilityResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DnsNameAvailabilityResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken availableValue = responseDoc["available"];
if (availableValue != null && availableValue.Type != JTokenType.Null)
{
bool availableInstance = ((bool)availableValue);
result.DnsNameAvailability = availableInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='azureAsyncOperation'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<AzureAsyncOperationResponse> GetLongRunningOperationStatusAsync(string azureAsyncOperation, CancellationToken cancellationToken)
{
// Validate
if (azureAsyncOperation == null)
{
throw new ArgumentNullException("azureAsyncOperation");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("azureAsyncOperation", azureAsyncOperation);
TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + azureAsyncOperation;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-05-01-preview");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureAsyncOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AzureAsyncOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
result.Status = statusInstance;
}
JToken errorValue = responseDoc["error"];
if (errorValue != null && errorValue.Type != JTokenType.Null)
{
Error errorInstance = new Error();
result.Error = errorInstance;
JToken codeValue = errorValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = errorValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = errorValue["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
JToken detailsArray = errorValue["details"];
if (detailsArray != null && detailsArray.Type != JTokenType.Null)
{
foreach (JToken detailsValue in ((JArray)detailsArray))
{
ErrorDetails errorDetailsInstance = new ErrorDetails();
errorInstance.Details.Add(errorDetailsInstance);
JToken codeValue2 = detailsValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
errorDetailsInstance.Code = codeInstance2;
}
JToken targetValue2 = detailsValue["target"];
if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
{
string targetInstance2 = ((string)targetValue2);
errorDetailsInstance.Target = targetInstance2;
}
JToken messageValue2 = detailsValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
errorDetailsInstance.Message = messageInstance2;
}
}
}
JToken innerErrorValue = errorValue["innerError"];
if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null)
{
string innerErrorInstance = ((string)innerErrorValue);
errorInstance.InnerError = innerErrorInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Management.Infrastructure;
namespace Microsoft.PowerShell.Commands
{
using Extensions;
internal static class CIMHelper
{
internal static class ClassNames
{
internal const string OperatingSystem = "Win32_OperatingSystem";
internal const string PageFileUsage = "Win32_PageFileUsage";
internal const string Bios = "Win32_BIOS";
internal const string BaseBoard = "Win32_BaseBoard";
internal const string ComputerSystem = "Win32_ComputerSystem";
internal const string Keyboard = "Win32_Keyboard";
internal const string DeviceGuard = "Win32_DeviceGuard";
internal const string HotFix = "Win32_QuickFixEngineering";
internal const string MicrosoftNetworkAdapter = "MSFT_NetAdapter";
internal const string NetworkAdapter = "Win32_NetworkAdapter";
internal const string NetworkAdapterConfiguration = "Win32_NetworkAdapterConfiguration";
internal const string Processor = "Win32_Processor";
internal const string PhysicalMemory = "Win32_PhysicalMemory";
internal const string TimeZone = "Win32_TimeZone";
}
internal const string DefaultNamespace = @"root\cimv2";
internal const string DeviceGuardNamespace = @"root\Microsoft\Windows\DeviceGuard";
internal const string MicrosoftNetworkAdapterNamespace = "root/StandardCimv2";
internal const string DefaultQueryDialect = "WQL";
/// <summary>
/// Create a WQL query string to retrieve all properties from
/// the specified WMI class.
/// </summary>
/// <param name="from">A string containing the WMI class name.</param>
/// <returns>
/// A string containing the WQL query string
/// </returns>
internal static string WqlQueryAll(string from)
{
return "SELECT * from " + from;
}
/// <summary>
/// Retrieve a new object of type T, whose properties and fields are
/// populated from an instance of the named WMI class. If the CIM
/// query results in multiple instances, only the first instance is
/// returned.
/// </summary>
/// <typeparam name="T">
/// The type of the object to be created. Must be a default-constructable
/// reference type.
/// </typeparam>
/// <param name="session">
/// The CIM session to be queried.
/// </param>
/// <param name="nameSpace">
/// A string containing the namespace to run the query against
/// </param>
/// <param name="wmiClassName">
/// A string containing the name of the WMI class from which to populate
/// the resultant object.
/// </param>
/// <returns>
/// A new object of type T if successful, null otherwise.
/// </returns>
/// <remarks>
/// This method matches property and field names of type T with identically
/// named properties in the WMI class instance. The WMI property is converted
/// to the type of T's property or field.
/// </remarks>
internal static T GetFirst<T>(CimSession session, string nameSpace, string wmiClassName) where T : class, new()
{
if (string.IsNullOrEmpty(wmiClassName))
throw new ArgumentException("String argument may not be null or empty", nameof(wmiClassName));
try
{
var type = typeof(T);
const BindingFlags binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
T rv = new();
using (var instance = session.QueryFirstInstance(nameSpace, CIMHelper.WqlQueryAll(wmiClassName)))
{
SetObjectDataMembers(rv, binding, instance);
}
return rv;
}
catch (Exception /*ex*/)
{
// on any error fall through to the null return below
}
return null;
}
/// <summary>
/// Retrieve an array of new objects of type T, whose properties and fields are
/// populated from an instance of the specified WMI class on the specified CIM
/// session.
/// </summary>
/// <typeparam name="T">
/// The type of the object to be created. Must be a default-constructable
/// reference type.
/// </typeparam>
/// <param name="session">
/// The CIM session to be queried.
/// </param>
/// <param name="nameSpace">
/// A string containing the namespace to run the query against
/// </param>
/// <param name="wmiClassName">
/// A string containing the name of the WMI class from which to populate
/// the resultant array elements.
/// </param>
/// <returns>
/// An array of new objects of type T if successful, null otherwise.
/// </returns>
/// <remarks>
/// This method matches property and field names of type T with identically
/// named properties in the WMI class instance. The WMI property is converted
/// to the type of T's property or field.
/// </remarks>
internal static T[] GetAll<T>(CimSession session, string nameSpace, string wmiClassName) where T : class, new()
{
if (string.IsNullOrEmpty(wmiClassName))
throw new ArgumentException("String argument may not be null or empty", nameof(wmiClassName));
var rv = new List<T>();
try
{
var instances = session.QueryInstances(nameSpace, CIMHelper.WqlQueryAll(wmiClassName));
if (instances != null)
{
var type = typeof(T);
const BindingFlags binding = BindingFlags.Public | BindingFlags.Instance;
foreach (var instance in instances)
{
T objT = new();
using (instance)
{
SetObjectDataMembers(objT, binding, instance);
}
rv.Add(objT);
}
}
}
catch (Exception /*ex*/)
{
// on any error we'll just fall through to the return below
}
return rv.ToArray();
}
/// <summary>
/// Retrieve an array of new objects of type T, whose properties and fields are
/// populated from an instance of the specified WMI class on the specified CIM
/// session.
/// </summary>
/// <typeparam name="T">
/// The type of the object to be created. Must be a default-constructable
/// reference type.
/// </typeparam>
/// <param name="session">
/// The CIM session to be queried.
/// </param>
/// <param name="wmiClassName">
/// A string containing the name of the WMI class from which to populate
/// the resultant array elements.
/// </param>
/// <returns>
/// An array of new objects of type T if successful, null otherwise.
/// </returns>
/// <remarks>
/// This method matches property and field names of type T with identically
/// named properties in the WMI class instance. The WMI property is converted
/// to the type of T's property or field.
/// </remarks>
internal static T[] GetAll<T>(CimSession session, string wmiClassName) where T : class, new()
{
return GetAll<T>(session, DefaultNamespace, wmiClassName);
}
internal static void SetObjectDataMember(object obj, BindingFlags binding, CimProperty cimProperty)
{
var type = obj.GetType();
var pi = type.GetProperty(cimProperty.Name, binding);
if (pi != null && pi.CanWrite)
{
pi.SetValue(obj, cimProperty.Value, null);
}
else
{
var fi = type.GetField(cimProperty.Name, binding);
if (fi != null && !fi.IsInitOnly)
{
fi.SetValue(obj, cimProperty.Value);
}
}
}
internal static void SetObjectDataMembers(object obj, BindingFlags binding, CimInstance instance)
{
foreach (var wmiProp in instance.CimInstanceProperties)
SetObjectDataMember(obj, binding, wmiProp);
}
/// <summary>
/// Escape any backslash (\) characters in a path with an additional
/// backslash, allowing the path to be used within a WMI query.
/// </summary>
/// <param name="path">
/// A string that may contain backslash characters.
/// </param>
/// <returns>
/// A new string in which any backslash characters have been "escaped"
/// by prefacing then with an additional backslash
/// </returns>
internal static string EscapePath(string path)
{
return string.Join(@"\\", path.Split('\\'));
}
}
}
namespace Extensions
{
using Microsoft.PowerShell.Commands;
internal static class CIMExtensions
{
/// <summary>
/// An "overload" of the
/// <see cref="Microsoft.Management.Infrastructure.CimSession"/>.QueryInstances
/// method that takes only the namespace and query string as a parameters.
/// </summary>
/// <param name="session">The CimSession to be queried.</param>
/// <param name="nameSpace">A string containing the namespace to run the query against.</param>
/// <param name="query">A string containing the query to be run.</param>
/// <returns>
/// An IEnumerable interface that can be used to enumerate the instances
/// </returns>
internal static IEnumerable<CimInstance> QueryInstances(this CimSession session, string nameSpace, string query)
{
return session.QueryInstances(nameSpace, CIMHelper.DefaultQueryDialect, query);
}
/// <summary>
/// Execute a CIM query and return only the first instance in the result.
/// </summary>
/// <param name="session">The CimSession to be queried.</param>
/// <param name="nameSpace">A string containing the namespace to run the query against.</param>
/// <param name="query">A string containing the query to be run.</param>
/// <returns>
/// A <see cref="Microsoft.Management.Infrastructure.CimInstance"/> object
/// representing the first instance in a query result if successful, null
/// otherwise.
/// </returns>
internal static CimInstance QueryFirstInstance(this CimSession session, string nameSpace, string query)
{
try
{
var instances = session.QueryInstances(nameSpace, query);
var enumerator = instances.GetEnumerator();
if (enumerator.MoveNext())
return enumerator.Current;
}
catch (Exception /*ex*/)
{
// on any error, fall through to the null return below
}
return null;
}
/// <summary>
/// Execute a CIM query and return only the first instance in the result.
/// </summary>
/// <param name="session">The CimSession to be queried.</param>
/// <param name="query">A string containing the query to be run.</param>
/// <returns>
/// A <see cref="Microsoft.Management.Infrastructure.CimInstance"/> object
/// representing the first instance in a query result if successful, null
/// otherwise.
/// </returns>
internal static CimInstance QueryFirstInstance(this CimSession session, string query)
{
return session.QueryFirstInstance(CIMHelper.DefaultNamespace, query);
}
internal static T GetFirst<T>(this CimSession session, string wmiClassName) where T : class, new()
{
return session.GetFirst<T>(CIMHelper.DefaultNamespace, wmiClassName);
}
internal static T GetFirst<T>(this CimSession session, string wmiNamespace, string wmiClassName) where T : class, new()
{
return CIMHelper.GetFirst<T>(session, wmiNamespace, wmiClassName);
}
internal static T[] GetAll<T>(this CimSession session, string wmiClassName) where T : class, new()
{
return Microsoft.PowerShell.Commands.CIMHelper.GetAll<T>(session, wmiClassName);
}
internal static T[] GetAll<T>(this CimSession session, string wmiNamespace, string wmiClassName) where T : class, new()
{
return Microsoft.PowerShell.Commands.CIMHelper.GetAll<T>(session, wmiNamespace, wmiClassName);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Transactions;
using Microsoft.SqlServer.Server;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class TvpTest
{
private const string TvpName = "@tvp";
private static readonly IList<SteAttributeKey> BoundariesTestKeys = new List<SteAttributeKey>(
new SteAttributeKey[] {
SteAttributeKey.SqlDbType,
SteAttributeKey.MultiValued,
SteAttributeKey.MaxLength,
SteAttributeKey.Precision,
SteAttributeKey.Scale,
SteAttributeKey.LocaleId,
SteAttributeKey.CompareOptions,
SteAttributeKey.TypeName,
SteAttributeKey.Type,
SteAttributeKey.Fields,
SteAttributeKey.Value
}).AsReadOnly();
// data value and server consts
private string _connStr;
[ActiveIssue(27858, TestPlatforms.AnyUnix)]
[CheckConnStrSetupFact]
public void TestMain()
{
Assert.True(RunTestCoreAndCompareWithBaseline());
}
public TvpTest()
{
_connStr = DataTestUtility.TcpConnStr;
}
private void RunTest()
{
Console.WriteLine("Starting test \'TvpTest\'");
StreamInputParam.Run(_connStr);
ColumnBoundariesTest();
QueryHintsTest();
SqlVariantParam.SendAllSqlTypesInsideVariant(_connStr);
DateTimeVariantTest.TestAllDateTimeWithDataTypeAndVariant(_connStr);
OutputParameter.Run(_connStr);
}
private bool RunTestCoreAndCompareWithBaseline()
{
string outputPath = "SqlParameterTest.out";
#if DEBUG
string baselinePath = "SqlParameterTest_DebugMode.bsl";
#else
string baselinePath = "SqlParameterTest_ReleaseMode.bsl";
#endif
var fstream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read);
var swriter = new StreamWriter(fstream, Encoding.UTF8);
// Convert all string writes of '\n' to '\r\n' so output files can be 'text' not 'binary'
var twriter = new CarriageReturnLineFeedReplacer(swriter);
Console.SetOut(twriter); // "redirect" Console.Out
// Run Test
RunTest();
Console.Out.Flush();
Console.Out.Dispose();
// Recover the standard output stream
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
// Compare output file
var comparisonResult = FindDiffFromBaseline(baselinePath, outputPath);
if (string.IsNullOrEmpty(comparisonResult))
{
return true;
}
Console.WriteLine("Test Failed!");
Console.WriteLine("Please compare baseline : {0} with output :{1}", Path.GetFullPath(baselinePath), Path.GetFullPath(outputPath));
Console.WriteLine("Comparison Results : ");
Console.WriteLine(comparisonResult);
return false;
}
private string FindDiffFromBaseline(string baselinePath, string outputPath)
{
var expectedLines = File.ReadAllLines(baselinePath);
var outputLines = File.ReadAllLines(outputPath);
var comparisonSb = new StringBuilder();
// Start compare results
var expectedLength = expectedLines.Length;
var outputLength = outputLines.Length;
var findDiffLength = Math.Min(expectedLength, outputLength);
// Find diff for each lines
for (var lineNo = 0; lineNo < findDiffLength; lineNo++)
{
if (!expectedLines[lineNo].Equals(outputLines[lineNo]))
{
comparisonSb.AppendFormat("** DIFF at line {0} \n", lineNo);
comparisonSb.AppendFormat("A : {0} \n", outputLines[lineNo]);
comparisonSb.AppendFormat("E : {0} \n", expectedLines[lineNo]);
}
}
var startIndex = findDiffLength - 1;
if (startIndex < 0)
startIndex = 0;
if (findDiffLength < expectedLength)
{
comparisonSb.AppendFormat("** MISSING \n");
for (var lineNo = startIndex; lineNo < expectedLength; lineNo++)
{
comparisonSb.AppendFormat("{0} : {1}", lineNo, expectedLines[lineNo]);
}
}
if (findDiffLength < outputLength)
{
comparisonSb.AppendFormat("** EXTRA \n");
for (var lineNo = startIndex; lineNo < outputLength; lineNo++)
{
comparisonSb.AppendFormat("{0} : {1}", lineNo, outputLines[lineNo]);
}
}
return comparisonSb.ToString();
}
private sealed class CarriageReturnLineFeedReplacer : TextWriter
{
private TextWriter _output;
private int _lineFeedCount;
private bool _hasCarriageReturn;
internal CarriageReturnLineFeedReplacer(TextWriter output)
{
if (output == null)
throw new ArgumentNullException(nameof(output));
_output = output;
}
public int LineFeedCount
{
get { return _lineFeedCount; }
}
public override Encoding Encoding
{
get { return _output.Encoding; }
}
public override IFormatProvider FormatProvider
{
get { return _output.FormatProvider; }
}
public override string NewLine
{
get { return _output.NewLine; }
set { _output.NewLine = value; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)_output).Dispose();
}
_output = null;
}
public override void Flush()
{
_output.Flush();
}
public override void Write(char value)
{
if ('\n' == value)
{
_lineFeedCount++;
if (!_hasCarriageReturn)
{ // X'\n'Y -> X'\r\n'Y
_output.Write('\r');
}
}
_hasCarriageReturn = '\r' == value;
_output.Write(value);
}
}
#region Main test methods
private void ColumnBoundariesTest()
{
IEnumerator<StePermutation> boundsMD = SteStructuredTypeBoundaries.AllColumnTypesExceptUdts.GetEnumerator(
BoundariesTestKeys);
TestTVPPermutations(SteStructuredTypeBoundaries.AllColumnTypesExceptUdts, false);
//Console.WriteLine("+++++++++++ UDT TVP tests ++++++++++++++");
//TestTVPPermutations(SteStructuredTypeBoundaries.UdtsOnly, true);
}
private void TestTVPPermutations(SteStructuredTypeBoundaries bounds, bool runOnlyDataRecordTest)
{
IEnumerator<StePermutation> boundsMD = bounds.GetEnumerator(BoundariesTestKeys);
object[][] baseValues = SteStructuredTypeBoundaries.GetSeparateValues(boundsMD);
IList<DataTable> dtList = GenerateDataTables(baseValues);
TransactionOptions opts = new TransactionOptions();
opts.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
// for each unique pattern of metadata
int iter = 0;
while (boundsMD.MoveNext())
{
Console.WriteLine("+++++++ Iteration {0} ++++++++", iter);
StePermutation tvpPerm = boundsMD.Current;
// Set up base command
SqlCommand cmd;
SqlParameter param;
cmd = new SqlCommand(GetProcName(tvpPerm));
cmd.CommandType = CommandType.StoredProcedure;
param = cmd.Parameters.Add(TvpName, SqlDbType.Structured);
param.TypeName = GetTypeName(tvpPerm);
// set up the server
try
{
CreateServerObjects(tvpPerm);
}
catch (SqlException se)
{
Console.WriteLine("SqlException creating objects: {0}", se.Number);
DropServerObjects(tvpPerm);
iter++;
continue;
}
// Send list of SqlDataRecords as value
Console.WriteLine("------IEnumerable<SqlDataRecord>---------");
try
{
param.Value = CreateListOfRecords(tvpPerm, baseValues);
ExecuteAndVerify(cmd, tvpPerm, baseValues, null);
}
catch (ArgumentException ae)
{
// some argument exceptions expected and should be swallowed
Console.WriteLine("Argument exception in value setup: {0}", ae.Message);
}
if (!runOnlyDataRecordTest)
{
// send DbDataReader
Console.WriteLine("------DbDataReader---------");
try
{
param.Value = new TvpRestartableReader(CreateListOfRecords(tvpPerm, baseValues));
ExecuteAndVerify(cmd, tvpPerm, baseValues, null);
}
catch (ArgumentException ae)
{
// some argument exceptions expected and should be swallowed
Console.WriteLine("Argument exception in value setup: {0}", ae.Message);
}
// send datasets
Console.WriteLine("------DataTables---------");
foreach (DataTable d in dtList)
{
param.Value = d;
ExecuteAndVerify(cmd, tvpPerm, null, d);
}
}
// And clean up
DropServerObjects(tvpPerm);
iter++;
}
}
public void QueryHintsTest()
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
Guid randomizer = Guid.NewGuid();
string typeName = string.Format("dbo.[QHint_{0}]", randomizer);
string procName = string.Format("dbo.[QHint_Proc_{0}]", randomizer);
string createTypeSql = string.Format(
"CREATE TYPE {0} AS TABLE("
+ " c1 Int DEFAULT -1,"
+ " c2 NVarChar(40) DEFAULT N'DEFUALT',"
+ " c3 DateTime DEFAULT '1/1/2006',"
+ " c4 Int DEFAULT -1)",
typeName);
string createProcSql = string.Format(
"CREATE PROC {0}(@tvp {1} READONLY) AS SELECT TOP(2) * FROM @tvp ORDER BY c1", procName, typeName);
string dropSql = string.Format("DROP PROC {0}; DROP TYPE {1}", procName, typeName);
try
{
SqlCommand cmd = new SqlCommand(createTypeSql, conn);
cmd.ExecuteNonQuery();
cmd.CommandText = createProcSql;
cmd.ExecuteNonQuery();
cmd.CommandText = procName;
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = cmd.Parameters.Add("@tvp", SqlDbType.Structured);
SqlMetaData[] columnMetadata;
List<SqlDataRecord> rows = new List<SqlDataRecord>();
SqlDataRecord record;
Console.WriteLine("------- Sort order + uniqueness #1: simple -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Ascending, 0),
new SqlMetaData("", SqlDbType.NVarChar, 40, false, true, SortOrder.Descending, 1),
new SqlMetaData("", SqlDbType.DateTime, false, true, SortOrder.Ascending, 2),
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Descending, 3),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(0, "Z-value", DateTime.Parse("03/01/2000"), 5);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "Y-value", DateTime.Parse("02/01/2000"), 6);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "X-value", DateTime.Parse("01/01/2000"), 7);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "X-value", DateTime.Parse("04/01/2000"), 8);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "X-value", DateTime.Parse("04/01/2000"), 4);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- Sort order + uniqueness #2: mixed order -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Descending, 3),
new SqlMetaData("", SqlDbType.NVarChar, 40, false, true, SortOrder.Descending, 0),
new SqlMetaData("", SqlDbType.DateTime, false, true, SortOrder.Ascending, 2),
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Ascending, 1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- default column #1: outer subset -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.NVarChar, 40, false, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.DateTime, false, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- default column #1: middle subset -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, false, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.NVarChar, 40, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.DateTime, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.Int, false, false, SortOrder.Unspecified, -1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- default column #1: all -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.NVarChar, 40, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.DateTime, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
SqlCommand cmd = new SqlCommand(dropSql, conn);
cmd.ExecuteNonQuery();
}
}
}
#endregion
#region Utility Methods
private bool AllowableDifference(string source, object result, StePermutation metadata)
{
object value;
bool returnValue = false;
// turn result into a string
string resultStr = null;
if (result.GetType() == typeof(string))
{
resultStr = (string)result;
}
else if (result.GetType() == typeof(char[]))
{
resultStr = new string((char[])result);
}
else if (result.GetType() == typeof(SqlChars))
{
resultStr = new string(((SqlChars)result).Value);
}
if (resultStr != null)
{
if (source.Equals(resultStr))
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.MaxLength, out value) && value != SteTypeBoundaries.s_doNotUseMarker)
{
int maxLength = (int)value;
if (maxLength < source.Length &&
source.Substring(0, maxLength).Equals(resultStr))
{
returnValue = true;
}
// Check for length extension due to fixed-length type
else if (maxLength > source.Length &&
resultStr.Length == maxLength &&
metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
value != SteTypeBoundaries.s_doNotUseMarker &&
(SqlDbType.Char == ((SqlDbType)value) ||
SqlDbType.NChar == ((SqlDbType)value)))
{
returnValue = true;
}
}
}
return returnValue;
}
private bool AllowableDifference(byte[] source, object result, StePermutation metadata)
{
object value;
bool returnValue = false;
// turn result into byte array
byte[] resultBytes = null;
if (result.GetType() == typeof(byte[]))
{
resultBytes = (byte[])result;
}
else if (result.GetType() == typeof(SqlBytes))
{
resultBytes = ((SqlBytes)result).Value;
}
if (resultBytes != null)
{
if (source.Equals(resultBytes) || resultBytes.Length == source.Length)
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.MaxLength, out value) && value != SteTypeBoundaries.s_doNotUseMarker)
{
int maxLength = (int)value;
// allowable max-length adjustments
if (maxLength == resultBytes.Length)
{ // a bit optimistic, but what the heck.
// truncation
if (maxLength <= source.Length)
{
returnValue = true;
}
// Check for length extension due to fixed-length type
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) && value != SteTypeBoundaries.s_doNotUseMarker &&
(SqlDbType.Binary == ((SqlDbType)value)))
{
returnValue = true;
}
}
}
}
return returnValue;
}
private bool AllowableDifference(SqlDecimal source, object result, StePermutation metadata)
{
object value;
object value2;
bool returnValue = false;
// turn result into SqlDecimal
SqlDecimal resultValue = SqlDecimal.Null;
if (result.GetType() == typeof(SqlDecimal))
{
resultValue = (SqlDecimal)result;
}
else if (result.GetType() == typeof(decimal))
{
resultValue = new SqlDecimal((decimal)result);
}
else if (result.GetType() == typeof(SqlMoney))
{
resultValue = new SqlDecimal(((SqlMoney)result).Value);
}
if (!resultValue.IsNull)
{
if (source.Equals(resultValue))
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
(SqlDbType.SmallMoney == (SqlDbType)value ||
SqlDbType.Money == (SqlDbType)value))
{
// Some server conversions seem to lose the decimal places
// TODO: Investigate and validate that this is acceptable!
SqlDecimal tmp = SqlDecimal.ConvertToPrecScale(source, source.Precision, 0);
if (tmp.Equals(resultValue))
{
returnValue = true;
}
else
{
tmp = SqlDecimal.ConvertToPrecScale(resultValue, resultValue.Precision, 0);
returnValue = tmp.Equals(source);
}
}
// check if value was altered by precision/scale conversion
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
SqlDbType.Decimal == (SqlDbType)value)
{
if (metadata.TryGetValue(SteAttributeKey.Scale, out value) &&
metadata.TryGetValue(SteAttributeKey.Precision, out value2) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
SteTypeBoundaries.s_doNotUseMarker != value2)
{
SqlDecimal tmp = SqlDecimal.ConvertToPrecScale(source, (byte)value2, (byte)value);
returnValue = tmp.Equals(resultValue);
}
// check if value was changed to 1 by the restartable reader
// due to exceeding size limits of System.Decimal
if (resultValue == (SqlDecimal)1M)
{
try
{
decimal dummy = source.Value;
}
catch (OverflowException)
{
returnValue = true;
}
}
}
}
return returnValue;
}
private bool CompareValue(object result, object source, StePermutation metadata)
{
bool isMatch = false;
if (!IsNull(source))
{
if (!IsNull(result))
{
if (source.Equals(result) || result.Equals(source))
{
isMatch = true;
}
else
{
switch (Type.GetTypeCode(source.GetType()))
{
case TypeCode.String:
isMatch = AllowableDifference((string)source, result, metadata);
break;
case TypeCode.Object:
{
if (source is char[])
{
source = new string((char[])source);
isMatch = AllowableDifference((string)source, result, metadata);
}
else if (source is byte[])
{
isMatch = AllowableDifference((byte[])source, result, metadata);
}
else if (source is SqlBytes)
{
isMatch = AllowableDifference(((SqlBytes)source).Value, result, metadata);
}
else if (source is SqlChars)
{
source = new string(((SqlChars)source).Value);
isMatch = AllowableDifference((string)source, result, metadata);
}
else if (source is SqlInt64 && result is long)
{
isMatch = result.Equals(((SqlInt64)source).Value);
}
else if (source is SqlInt32 && result is int)
{
isMatch = result.Equals(((SqlInt32)source).Value);
}
else if (source is SqlInt16 && result is short)
{
isMatch = result.Equals(((SqlInt16)source).Value);
}
else if (source is SqlSingle && result is float)
{
isMatch = result.Equals(((SqlSingle)source).Value);
}
else if (source is SqlDouble && result is double)
{
isMatch = result.Equals(((SqlDouble)source).Value);
}
else if (source is SqlDateTime && result is DateTime)
{
isMatch = result.Equals(((SqlDateTime)source).Value);
}
else if (source is SqlMoney)
{
isMatch = AllowableDifference(new SqlDecimal(((SqlMoney)source).Value), result, metadata);
}
else if (source is SqlDecimal)
{
isMatch = AllowableDifference((SqlDecimal)source, result, metadata);
}
}
break;
case TypeCode.Decimal:
if (result is SqlDecimal || result is decimal || result is SqlMoney)
{
isMatch = AllowableDifference(new SqlDecimal((decimal)source), result, metadata);
}
break;
default:
break;
}
}
}
}
else
{
if (IsNull(result))
{
isMatch = true;
}
}
if (!isMatch)
{
ReportMismatch(source, result, metadata);
}
return isMatch;
}
private IList<SqlDataRecord> CreateListOfRecords(StePermutation tvpPerm, object[][] baseValues)
{
IList<StePermutation> fields = GetFields(tvpPerm);
SqlMetaData[] fieldMetadata = new SqlMetaData[fields.Count];
int i = 0;
foreach (StePermutation perm in fields)
{
fieldMetadata[i] = PermToSqlMetaData(perm);
i++;
}
List<SqlDataRecord> records = new List<SqlDataRecord>(baseValues.Length);
for (int rowOrd = 0; rowOrd < baseValues.Length; rowOrd++)
{
object[] row = baseValues[rowOrd];
SqlDataRecord rec = new SqlDataRecord(fieldMetadata);
records.Add(rec); // Call SetValue *after* Add to ensure record is put in list
for (int colOrd = 0; colOrd < row.Length; colOrd++)
{
// Set value in try-catch to prevent some errors from aborting run.
try
{
rec.SetValue(colOrd, row[colOrd]);
}
catch (OverflowException oe)
{
Console.WriteLine("Failed Row[{0}]Col[{1}] = {2}: {3}", rowOrd, colOrd, row[colOrd], oe.Message);
}
catch (ArgumentException ae)
{
Console.WriteLine("Failed Row[{0}]Col[{1}] = {2}: {3}", rowOrd, colOrd, row[colOrd], ae.Message);
}
}
}
return records;
}
private DataTable CreateNewTable(object[] row, ref Type[] lastRowTypes)
{
DataTable dt = new DataTable();
for (int i = 0; i < row.Length; i++)
{
object value = row[i];
Type t;
if ((null == value || DBNull.Value == value))
{
if (lastRowTypes[i] == null)
{
return null;
}
else
{
t = lastRowTypes[i];
}
}
else
{
t = value.GetType();
}
dt.Columns.Add(new DataColumn("Col" + i + "_" + t.Name, t));
lastRowTypes[i] = t;
}
return dt;
}
// create table type and proc that uses that type at the server
private void CreateServerObjects(StePermutation tvpPerm)
{
// Create the table type tsql
StringBuilder tsql = new StringBuilder();
tsql.Append("CREATE TYPE ");
tsql.Append(GetTypeName(tvpPerm));
tsql.Append(" AS TABLE(");
bool addSeparator = false;
int colOrdinal = 1;
foreach (StePermutation perm in GetFields(tvpPerm))
{
if (addSeparator)
{
tsql.Append(", ");
}
else
{
addSeparator = true;
}
// column name
tsql.Append("column");
tsql.Append(colOrdinal);
tsql.Append(" ");
// column type
SqlDbType dbType = (SqlDbType)perm[SteAttributeKey.SqlDbType];
switch (dbType)
{
case SqlDbType.BigInt:
tsql.Append("Bigint");
break;
case SqlDbType.Binary:
tsql.Append("Binary(");
object maxLenObj = perm[SteAttributeKey.MaxLength];
int maxLen;
if (maxLenObj == SteTypeBoundaries.s_doNotUseMarker)
{
maxLen = 8000;
}
else
{
maxLen = (int)maxLenObj;
}
tsql.Append(maxLen);
tsql.Append(")");
break;
case SqlDbType.Bit:
tsql.Append("Bit");
break;
case SqlDbType.Char:
tsql.Append("Char(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.DateTime:
tsql.Append("DateTime");
break;
case SqlDbType.Decimal:
tsql.Append("Decimal(");
tsql.Append(perm[SteAttributeKey.Precision]);
tsql.Append(", ");
tsql.Append(perm[SteAttributeKey.Scale]);
tsql.Append(")");
break;
case SqlDbType.Float:
tsql.Append("Float");
break;
case SqlDbType.Image:
tsql.Append("Image");
break;
case SqlDbType.Int:
tsql.Append("Int");
break;
case SqlDbType.Money:
tsql.Append("Money");
break;
case SqlDbType.NChar:
tsql.Append("NChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.NText:
tsql.Append("NText");
break;
case SqlDbType.NVarChar:
tsql.Append("NVarChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.Real:
tsql.Append("Real");
break;
case SqlDbType.UniqueIdentifier:
tsql.Append("UniqueIdentifier");
break;
case SqlDbType.SmallDateTime:
tsql.Append("SmallDateTime");
break;
case SqlDbType.SmallInt:
tsql.Append("SmallInt");
break;
case SqlDbType.SmallMoney:
tsql.Append("SmallMoney");
break;
case SqlDbType.Text:
tsql.Append("Text");
break;
case SqlDbType.Timestamp:
tsql.Append("Timestamp");
break;
case SqlDbType.TinyInt:
tsql.Append("TinyInt");
break;
case SqlDbType.VarBinary:
tsql.Append("VarBinary(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.VarChar:
tsql.Append("VarChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.Variant:
tsql.Append("Variant");
break;
case SqlDbType.Xml:
tsql.Append("Xml");
break;
case SqlDbType.Udt:
string typeName = (string)perm[SteAttributeKey.TypeName];
tsql.Append(typeName);
break;
case SqlDbType.Structured:
throw new NotSupportedException("Not supported");
}
colOrdinal++;
}
tsql.Append(")");
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
// execute it to create the type
SqlCommand cmd = new SqlCommand(tsql.ToString(), conn);
cmd.ExecuteNonQuery();
// and create the proc that uses the type
cmd.CommandText = string.Format("CREATE PROC {0}(@tvp {1} READONLY) AS SELECT * FROM @tvp order by {2}",
GetProcName(tvpPerm), GetTypeName(tvpPerm), colOrdinal - 1);
cmd.ExecuteNonQuery();
}
}
private bool DoesRowMatchMetadata(object[] row, DataTable table)
{
bool result = true;
if (row.Length != table.Columns.Count)
{
result = false;
}
else
{
for (int i = 0; i < row.Length; i++)
{
if (null != row[i] && DBNull.Value != row[i] && row[i].GetType() != table.Columns[i].DataType)
{
result = false;
}
}
}
return result;
}
private void DropServerObjects(StePermutation tvpPerm)
{
string dropText = "DROP PROC " + GetProcName(tvpPerm) + "; DROP TYPE " + GetTypeName(tvpPerm);
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(dropText, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine("SqlException dropping objects: {0}", e.Number);
}
}
}
private void ExecuteAndVerify(SqlCommand cmd, StePermutation tvpPerm, object[][] objValues, DataTable dtValues)
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
cmd.Connection = conn;
// cmd.Transaction = conn.BeginTransaction();
// and run the command
try
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
VerifyColumnBoundaries(rdr, GetFields(tvpPerm), objValues, dtValues);
}
}
catch (SqlException se)
{
Console.WriteLine("SqlException. Error Code: {0}", se.Number);
}
catch (InvalidOperationException ioe)
{
Console.WriteLine("InvalidOp: {0}", ioe.Message);
}
catch (ArgumentException ae)
{
Console.WriteLine("ArgumentException: {0}", ae.Message);
}
// And clean up. If an error is thrown, the connection being recycled
// will roll back the transaction
if (null != cmd.Transaction)
{
// cmd.Transaction.Rollback();
}
}
}
private IList<DataTable> GenerateDataTables(object[][] values)
{
List<DataTable> dtList = new List<DataTable>();
Type[] valueTypes = new Type[values[0].Length];
foreach (object[] row in values)
{
DataTable targetTable = null;
if (0 < dtList.Count)
{
// shortcut for matching last table (most common scenario)
if (DoesRowMatchMetadata(row, dtList[dtList.Count - 1]))
{
targetTable = dtList[dtList.Count - 1];
}
else
{
foreach (DataTable candidate in dtList)
{
if (DoesRowMatchMetadata(row, candidate))
{
targetTable = candidate;
break;
}
}
}
}
if (null == targetTable)
{
targetTable = CreateNewTable(row, ref valueTypes);
if (null != targetTable)
{
dtList.Add(targetTable);
}
}
if (null != targetTable)
{
targetTable.Rows.Add(row);
}
}
return dtList;
}
private IList<StePermutation> GetFields(StePermutation tvpPerm)
{
return (IList<StePermutation>)tvpPerm[SteAttributeKey.Fields];
}
private string GetProcName(StePermutation tvpPerm)
{
return "dbo.[Proc_" + (string)tvpPerm[SteAttributeKey.TypeName] + "]";
}
private string GetTypeName(StePermutation tvpPerm)
{
return "dbo.[" + (string)tvpPerm[SteAttributeKey.TypeName] + "]";
}
private bool IsNull(object value)
{
return null == value ||
DBNull.Value == value ||
(value is INullable &&
((INullable)value).IsNull);
}
private SqlMetaData PermToSqlMetaData(StePermutation perm)
{
object attr;
SqlDbType sqlDbType;
int maxLength = 0;
byte precision = 0;
byte scale = 0;
string typeName = null;
Type type = null;
long localeId = 0;
SqlCompareOptions opts = SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth;
if (perm.TryGetValue(SteAttributeKey.SqlDbType, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
sqlDbType = (SqlDbType)attr;
}
else
{
throw new InvalidOperationException("PermToSqlMetaData: No SqlDbType available!");
}
if (perm.TryGetValue(SteAttributeKey.MaxLength, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
maxLength = (int)attr;
}
if (perm.TryGetValue(SteAttributeKey.Precision, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
precision = (byte)attr;
}
if (perm.TryGetValue(SteAttributeKey.Scale, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
scale = (byte)attr;
}
if (perm.TryGetValue(SteAttributeKey.LocaleId, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
localeId = (int)attr;
}
if (perm.TryGetValue(SteAttributeKey.CompareOptions, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
opts = (SqlCompareOptions)attr;
}
if (perm.TryGetValue(SteAttributeKey.TypeName, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
typeName = (string)attr;
}
if (perm.TryGetValue(SteAttributeKey.Type, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
type = (Type)attr;
}
//if (SqlDbType.Udt == sqlDbType)
//{
// return new SqlMetaData("", sqlDbType, type, typeName);
//}
//else
//{
return new SqlMetaData("", sqlDbType, maxLength, precision, scale, localeId, opts, type);
//}
}
private void ReportMismatch(object source, object result, StePermutation perm)
{
if (null == source)
{
source = "(null)";
}
if (null == result)
{
result = "(null)";
}
Console.WriteLine("Mismatch: Source = {0}, result = {1}, metadata={2}", source, result, perm.ToString());
}
private void VerifyColumnBoundaries(SqlDataReader rdr, IList<StePermutation> fieldMetaData, object[][] values, DataTable dt)
{
int rowOrd = 0;
int matches = 0;
while (rdr.Read())
{
for (int columnOrd = 0; columnOrd < rdr.FieldCount; columnOrd++)
{
object value;
// Special case to handle decimal values that may be too large for GetValue
if (!rdr.IsDBNull(columnOrd) && rdr.GetFieldType(columnOrd) == typeof(decimal))
{
value = rdr.GetSqlValue(columnOrd);
}
else
{
value = rdr.GetValue(columnOrd);
}
if (null != values)
{
if (CompareValue(value, values[rowOrd][columnOrd], fieldMetaData[columnOrd]))
{
matches++;
}
else
{
Console.WriteLine(" Row={0}, Column={1}", rowOrd, columnOrd);
}
}
else
{
if (CompareValue(value, dt.Rows[rowOrd][columnOrd], fieldMetaData[columnOrd]))
{
matches++;
}
else
{
Console.WriteLine(" Row={0}, Column={1}", rowOrd, columnOrd);
}
}
}
rowOrd++;
}
Console.WriteLine("Matches = {0}", matches);
}
private void WriteReader(SqlDataReader rdr)
{
int colCount = rdr.FieldCount;
do
{
Console.WriteLine("-------------");
while (rdr.Read())
{
for (int i = 0; i < colCount; i++)
{
Console.Write("{0} ", rdr.GetValue(i));
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("-------------");
}
while (rdr.NextResult());
}
private void DumpSqlParam(SqlParameter param)
{
Console.WriteLine("Parameter {0}", param.ParameterName);
Console.WriteLine(" IsNullable: {0}", param.IsNullable);
Console.WriteLine(" LocaleId: {0}", param.LocaleId);
Console.WriteLine(" Offset: {0}", param.Offset);
Console.WriteLine(" CompareInfo: {0}", param.CompareInfo);
Console.WriteLine(" DbType: {0}", param.DbType);
Console.WriteLine(" Direction: {0}", param.Direction);
Console.WriteLine(" Precision: {0}", param.Precision);
Console.WriteLine(" Scale: {0}", param.Scale);
Console.WriteLine(" Size: {0}", param.Size);
Console.WriteLine(" SqlDbType: {0}", param.SqlDbType);
Console.WriteLine(" TypeName: {0}", param.TypeName);
//Console.WriteLine(" UdtTypeName: {0}", param.UdtTypeName);
Console.WriteLine(" XmlSchemaCollectionDatabase: {0}", param.XmlSchemaCollectionDatabase);
Console.WriteLine(" XmlSchemaCollectionName: {0}", param.XmlSchemaCollectionName);
Console.WriteLine(" XmlSchemaCollectionSchema: {0}", param.XmlSchemaCollectionOwningSchema);
}
#endregion
}
internal class TvpRestartableReader : DbDataReader
{
private IList<SqlDataRecord> _sourceData;
int _currentRow;
internal TvpRestartableReader(IList<SqlDataRecord> source) : base()
{
_sourceData = source;
Restart();
}
public void Restart()
{
_currentRow = -1;
}
override public int Depth
{
get { return 0; }
}
override public int FieldCount
{
get { return _sourceData[_currentRow].FieldCount; }
}
override public bool HasRows
{
get { return _sourceData.Count > 0; }
}
override public bool IsClosed
{
get { return false; }
}
override public int RecordsAffected
{
get { return 0; }
}
override public object this[int ordinal]
{
get { return GetValue(ordinal); }
}
override public object this[string name]
{
get { return GetValue(GetOrdinal(name)); }
}
override public void Close()
{
_currentRow = _sourceData.Count;
}
override public string GetDataTypeName(int ordinal)
{
return _sourceData[_currentRow].GetDataTypeName(ordinal);
}
override public IEnumerator GetEnumerator()
{
return _sourceData.GetEnumerator();
}
override public Type GetFieldType(int ordinal)
{
return _sourceData[_currentRow].GetFieldType(ordinal);
}
override public string GetName(int ordinal)
{
return _sourceData[_currentRow].GetName(ordinal);
}
override public int GetOrdinal(string name)
{
return _sourceData[_currentRow].GetOrdinal(name);
}
override public DataTable GetSchemaTable()
{
SqlDataRecord rec = _sourceData[0];
DataTable schemaTable = new DataTable();
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnName, typeof(string)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnOrdinal, typeof(int)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnSize, typeof(int)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NumericPrecision, typeof(short)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NumericScale, typeof(short)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.DataType, typeof(System.Type)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.ProviderSpecificDataType, typeof(System.Type)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NonVersionedProviderType, typeof(int)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ProviderType, typeof(int)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsLong, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.AllowDBNull, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsReadOnly, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsRowVersion, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsUnique, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsKey, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsHidden, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.BaseCatalogName, typeof(string)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseSchemaName, typeof(string)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseTableName, typeof(string)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseColumnName, typeof(string)));
for (int i = 0; i < rec.FieldCount; i++)
{
DataRow row = schemaTable.NewRow();
SqlMetaData md = rec.GetSqlMetaData(i);
row[SchemaTableColumn.ColumnName] = md.Name;
row[SchemaTableColumn.ColumnOrdinal] = i;
row[SchemaTableColumn.ColumnSize] = md.MaxLength;
row[SchemaTableColumn.NumericPrecision] = md.Precision;
row[SchemaTableColumn.NumericScale] = md.Scale;
row[SchemaTableColumn.DataType] = rec.GetFieldType(i);
row[SchemaTableOptionalColumn.ProviderSpecificDataType] = rec.GetFieldType(i);
row[SchemaTableColumn.NonVersionedProviderType] = (int)md.SqlDbType;
row[SchemaTableColumn.ProviderType] = (int)md.SqlDbType;
row[SchemaTableColumn.IsLong] = md.MaxLength == SqlMetaData.Max || md.MaxLength > 8000;
row[SchemaTableColumn.AllowDBNull] = true;
row[SchemaTableOptionalColumn.IsReadOnly] = true;
row[SchemaTableOptionalColumn.IsRowVersion] = md.SqlDbType == SqlDbType.Timestamp;
row[SchemaTableColumn.IsUnique] = false;
row[SchemaTableColumn.IsKey] = false;
row[SchemaTableOptionalColumn.IsAutoIncrement] = false;
row[SchemaTableOptionalColumn.IsHidden] = false;
row[SchemaTableOptionalColumn.BaseCatalogName] = null;
row[SchemaTableColumn.BaseSchemaName] = null;
row[SchemaTableColumn.BaseTableName] = null;
row[SchemaTableColumn.BaseColumnName] = md.Name;
schemaTable.Rows.Add(row);
}
return schemaTable;
}
override public bool GetBoolean(int ordinal)
{
return _sourceData[_currentRow].GetBoolean(ordinal);
}
override public byte GetByte(int ordinal)
{
return _sourceData[_currentRow].GetByte(ordinal);
}
override public long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
{
return _sourceData[_currentRow].GetBytes(ordinal, dataOffset, buffer, bufferOffset, length);
}
override public char GetChar(int ordinal)
{
return _sourceData[_currentRow].GetChar(ordinal);
}
override public long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
{
return _sourceData[_currentRow].GetChars(ordinal, dataOffset, buffer, bufferOffset, length);
}
override public DateTime GetDateTime(int ordinal)
{
return _sourceData[_currentRow].GetDateTime(ordinal);
}
override public decimal GetDecimal(int ordinal)
{
// DataRecord may have illegal values for Decimal...
decimal result;
try
{
result = _sourceData[_currentRow].GetDecimal(ordinal);
}
catch (OverflowException)
{
result = (decimal)1;
}
return result;
}
override public double GetDouble(int ordinal)
{
return _sourceData[_currentRow].GetDouble(ordinal);
}
override public float GetFloat(int ordinal)
{
return _sourceData[_currentRow].GetFloat(ordinal);
}
override public Guid GetGuid(int ordinal)
{
return _sourceData[_currentRow].GetGuid(ordinal);
}
override public short GetInt16(int ordinal)
{
return _sourceData[_currentRow].GetInt16(ordinal);
}
override public int GetInt32(int ordinal)
{
return _sourceData[_currentRow].GetInt32(ordinal);
}
override public long GetInt64(int ordinal)
{
return _sourceData[_currentRow].GetInt64(ordinal);
}
override public string GetString(int ordinal)
{
return _sourceData[_currentRow].GetString(ordinal);
}
override public object GetValue(int ordinal)
{
return _sourceData[_currentRow].GetValue(ordinal);
}
override public int GetValues(object[] values)
{
return _sourceData[_currentRow].GetValues(values);
}
override public bool IsDBNull(int ordinal)
{
return _sourceData[_currentRow].IsDBNull(ordinal);
}
override public bool NextResult()
{
Close();
return false;
}
override public bool Read()
{
_currentRow++;
return _currentRow < _sourceData.Count;
}
}
}
| |
using System;
//
//Module : AAPLANETPERIHELIONAPHELION.CPP
//Purpose: Implementation for the algorithms which obtain the dates of Perihelion and Aphelion of the planets
//Created: PJN / 29-12-2003
//History: None
//
//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com)
//
//All rights reserved.
//
//Copyright / Usage Details:
//
//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
//when your product is released in binary form. You are allowed to modify the source code in any way you want
//except you cannot modify the copyright details at the top of each module. If you want to distribute source
//code with your application, then you are only allowed to distribute versions released by the author. This is
//to maintain a single distribution point for the source code.
//
//
///////////////////////////////// Includes ////////////////////////////////////
/////////////////////// Classes ///////////////////////////////////////////////
public class CAAPlanetPerihelionAphelion
{
//Static methods
///////////////////////////////// Implementation //////////////////////////////
public static int MercuryK(double Year)
{
return (int)(4.15201*(Year - 2000.12));
}
public static double MercuryPerihelion(int k)
{
return 2451590.257 + 87.96934963 *k;
}
public static double MercuryAphelion(int k)
{
double kdash = k + 0.5;
return 2451590.257 + 87.96934963 *kdash;
}
public static int VenusK(double Year)
{
return (int)(1.62549*(Year - 2000.53));
}
public static double VenusPerihelion(int k)
{
double kdash = k;
double ksquared = kdash * kdash;
return 2451738.233 + 224.7008188 *kdash - 0.0000000327 *ksquared;
}
public static double VenusAphelion(int k)
{
double kdash = k + 0.5;
double ksquared = kdash * kdash;
return 2451738.233 + 224.7008188 *kdash - 0.0000000327 *ksquared;
}
public static int EarthK(double Year)
{
return (int)(0.99997*(Year - 2000.01));
}
public static double EarthPerihelion(int k)
{
return EarthPerihelion(k, false);
}
//C++ TO C# CONVERTER NOTE: C# does not allow default values for parameters. Overloaded methods are inserted above.
//ORIGINAL LINE: static double EarthPerihelion(int k, bool bBarycentric = false)
public static double EarthPerihelion(int k, bool bBarycentric)
{
double kdash = k;
double ksquared = kdash * kdash;
double JD = 2451547.507 + 365.2596358 *kdash + 0.0000000156 *ksquared;
if (!bBarycentric)
{
//Apply the corrections
double A1 = CAACoordinateTransformation.MapTo0To360Range(328.41 + 132.788585 *k);
A1 = CAACoordinateTransformation.DegreesToRadians(A1);
double A2 = CAACoordinateTransformation.MapTo0To360Range(316.13 + 584.903153 *k);
A2 = CAACoordinateTransformation.DegreesToRadians(A2);
double A3 = CAACoordinateTransformation.MapTo0To360Range(346.20 + 450.380738 *k);
A3 = CAACoordinateTransformation.DegreesToRadians(A3);
double A4 = CAACoordinateTransformation.MapTo0To360Range(136.95 + 659.306737 *k);
A4 = CAACoordinateTransformation.DegreesToRadians(A4);
double A5 = CAACoordinateTransformation.MapTo0To360Range(249.52 + 329.653368 *k);
A5 = CAACoordinateTransformation.DegreesToRadians(A5);
JD += 1.278 *Math.Sin(A1);
JD -= 0.055 *Math.Sin(A2);
JD -= 0.091 *Math.Sin(A3);
JD -= 0.056 *Math.Sin(A4);
JD -= 0.045 *Math.Sin(A5);
}
return JD;
}
public static double EarthAphelion(int k)
{
return EarthAphelion(k, false);
}
//C++ TO C# CONVERTER NOTE: C# does not allow default values for parameters. Overloaded methods are inserted above.
//ORIGINAL LINE: static double EarthAphelion(int k, bool bBarycentric = false)
public static double EarthAphelion(int k, bool bBarycentric)
{
double kdash = k + 0.5;
double ksquared = kdash * kdash;
double JD = 2451547.507 + 365.2596358 *kdash + 0.0000000156 *ksquared;
if (!bBarycentric)
{
//Apply the corrections
double A1 = CAACoordinateTransformation.MapTo0To360Range(328.41 + 132.788585 *k);
A1 = CAACoordinateTransformation.DegreesToRadians(A1);
double A2 = CAACoordinateTransformation.MapTo0To360Range(316.13 + 584.903153 *k);
A2 = CAACoordinateTransformation.DegreesToRadians(A2);
double A3 = CAACoordinateTransformation.MapTo0To360Range(346.20 + 450.380738 *k);
A3 = CAACoordinateTransformation.DegreesToRadians(A3);
double A4 = CAACoordinateTransformation.MapTo0To360Range(136.95 + 659.306737 *k);
A4 = CAACoordinateTransformation.DegreesToRadians(A4);
double A5 = CAACoordinateTransformation.MapTo0To360Range(249.52 + 329.653368 *k);
A5 = CAACoordinateTransformation.DegreesToRadians(A5);
JD -= 1.352 *Math.Sin(A1);
JD += 0.061 *Math.Sin(A2);
JD += 0.062 *Math.Sin(A3);
JD += 0.029 *Math.Sin(A4);
JD += 0.031 *Math.Sin(A5);
}
return JD;
}
public static int MarsK(double Year)
{
return (int)(0.53166*(Year - 2001.78));
}
public static double MarsPerihelion(int k)
{
double kdash = k;
double ksquared = kdash * kdash;
return 2452195.026 + 686.9957857 *kdash - 0.0000001187 *ksquared;
}
public static double MarsAphelion(int k)
{
double kdash = k + 0.5;
double ksquared = kdash * kdash;
return 2452195.026 + 686.9957857 *kdash - 0.0000001187 *ksquared;
}
public static int JupiterK(double Year)
{
return (int)(0.08430*(Year - 2011.20));
}
public static double JupiterPerihelion(int k)
{
double kdash = k;
double ksquared = kdash * kdash;
return 2455636.936 + 4332.897065 *kdash + 0.0001367 *ksquared;
}
public static double JupiterAphelion(int k)
{
double kdash = k + 0.5;
double ksquared = kdash * kdash;
return 2455636.936 + 4332.897065 *kdash + 0.0001367 *ksquared;
}
public static int SaturnK(double Year)
{
return (int)(0.03393*(Year - 2003.52));
}
public static double SaturnPerihelion(int k)
{
double kdash = k;
double ksquared = kdash * kdash;
return 2452830.12 + 10764.21676 *kdash + 0.000827 *ksquared;
}
public static double SaturnAphelion(int k)
{
double kdash = k + 0.5;
double ksquared = kdash * kdash;
return 2452830.12 + 10764.21676 *kdash + 0.000827 *ksquared;
}
public static int UranusK(double Year)
{
return (int)(0.01190*(Year - 2051.1));
}
public static double UranusPerihelion(int k)
{
double kdash = k;
double ksquared = kdash * kdash;
return 2470213.5 + 30694.8767 *kdash - 0.00541 *ksquared;
}
public static double UranusAphelion(int k)
{
double kdash = k + 0.5;
double ksquared = kdash * kdash;
return 2470213.5 + 30694.8767 *kdash - 0.00541 *ksquared;
}
public static int NeptuneK(double Year)
{
return (int)(0.00607*(Year - 2047.5));
}
public static double NeptunePerihelion(int k)
{
double kdash = k;
double ksquared = kdash * kdash;
return 2468895.1 + 60190.33 *kdash + 0.03429 *ksquared;
}
public static double NeptuneAphelion(int k)
{
double kdash = k + 0.5;
double ksquared = kdash * kdash;
return 2468895.1 + 60190.33 *kdash + 0.03429 *ksquared;
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using Eto.Drawing;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
using CoreImage;
#elif OSX
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
using MonoMac.CoreImage;
using MonoMac;
#if Mac64
using CGSize = MonoMac.Foundation.NSSize;
using CGRect = MonoMac.Foundation.NSRect;
using CGPoint = MonoMac.Foundation.NSPoint;
using nfloat = System.Double;
using nint = System.Int64;
using nuint = System.UInt64;
#else
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
#endif
#endif
#if OSX
using Eto.Mac.Forms;
#if XAMMAC2
using GraphicsBase = Eto.Mac.Forms.MacBase<CoreGraphics.CGContext, Eto.Drawing.Graphics, Eto.Drawing.Graphics.ICallback>;
#else
using GraphicsBase = Eto.Mac.Forms.MacBase<MonoMac.CoreGraphics.CGContext, Eto.Drawing.Graphics, Eto.Drawing.Graphics.ICallback>;
#endif
namespace Eto.Mac.Drawing
#elif IOS
using Eto.iOS.Forms;
using Eto.Mac;
using CoreGraphics;
using UIKit;
using Foundation;
using NSView = UIKit.UIView;
using GraphicsBase = Eto.WidgetHandler<CoreGraphics.CGContext, Eto.Drawing.Graphics, Eto.Drawing.Graphics.ICallback>;
namespace Eto.iOS.Drawing
#endif
{
#if OSX
public static class GraphicsExtensions
{
[DllImport(Constants.AppKitLibrary, EntryPoint = "NSSetFocusRingStyle")]
public extern static void SetFocusRingStyle(NSFocusRingPlacement placement);
}
#endif
/// <summary>
/// Handler for the <see cref="Graphics.IHandler"/>
/// </summary>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public class GraphicsHandler : GraphicsBase, Graphics.IHandler
{
#if OSX
NSGraphicsContext graphicsContext;
bool disposeContext;
readonly NSView view;
#endif
float height;
bool isOffset;
CGRect? clipBounds;
IGraphicsPath clipPath;
readonly Stack<CGAffineTransform> transforms = new Stack<CGAffineTransform>();
CGAffineTransform currentTransform = CGAffineTransform.MakeIdentity();
static readonly CGColorSpace patternColorSpace = CGColorSpace.CreatePattern(null);
public NSView DisplayView { get; private set; }
static readonly object PixelOffsetMode_Key = new object();
public PixelOffsetMode PixelOffsetMode
{
get { return Widget != null ? Widget.Properties.Get<PixelOffsetMode>(PixelOffsetMode_Key) : default(PixelOffsetMode); }
set { Widget.Properties.Set(PixelOffsetMode_Key, value); }
}
void SetOffset(bool fill)
{
var requiresOffset = !fill && PixelOffsetMode == PixelOffsetMode.None;
if (requiresOffset != isOffset)
{
RewindAll();
isOffset = requiresOffset;
ApplyAll();
}
}
public GraphicsHandler()
{
}
#if OSX
public GraphicsHandler(NSView view)
{
this.view = view;
graphicsContext = NSGraphicsContext.FromWindow(view.Window);
graphicsContext = graphicsContext.IsFlipped ? graphicsContext : NSGraphicsContext.FromGraphicsPort(graphicsContext.GraphicsPortHandle, true);
disposeContext = true;
Control = graphicsContext.GraphicsPort;
view.PostsFrameChangedNotifications = true;
AddObserver(NSView.FrameChangedNotification, FrameDidChange, view);
// if control is in a scrollview, we need to trap when it's scrolled as well
var parent = view.Superview;
while (parent != null)
{
var scroll = parent as NSScrollView;
if (scroll != null)
{
scroll.ContentView.PostsBoundsChangedNotifications = true;
AddObserver(NSView.BoundsChangedNotification, FrameDidChange, scroll.ContentView);
}
parent = parent.Superview;
}
SetDefaults();
InitializeContext(view.IsFlipped);
}
static void FrameDidChange(ObserverActionEventArgs e)
{
var h = e.Handler as GraphicsHandler;
if (h != null && h.Control != null)
{
h.RewindAll();
h.Control.RestoreState();
h.InitializeContext(h.view.IsFlipped);
}
}
public GraphicsHandler(NSView view, NSGraphicsContext graphicsContext, float height, bool flipped)
{
DisplayView = view;
this.height = height;
this.graphicsContext = flipped != graphicsContext.IsFlipped ? graphicsContext : NSGraphicsContext.FromGraphicsPort(graphicsContext.GraphicsPortHandle, true);
Control = this.graphicsContext.GraphicsPort;
SetDefaults();
InitializeContext(!flipped);
}
#elif IOS
public GraphicsHandler(NSView view, CGContext context, nfloat height)
{
this.DisplayView = view;
this.height = (float)height;
this.Control = context;
SetDefaults();
InitializeContext(false);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endif
protected override bool DisposeControl { get { return false; } }
public bool IsRetained { get { return false; } }
static readonly object AntiAlias_Key = new object();
public bool AntiAlias
{
get { return Widget.Properties.Get<bool>(AntiAlias_Key, true); }
set { Widget.Properties.Set(AntiAlias_Key, value, () => Control.SetShouldAntialias(value)); }
}
static readonly object PointsPerPixel_Key = new object();
public float PointsPerPixel
{
get { return Widget.Properties.Get<float>(PointsPerPixel_Key, 1f); }
private set { Widget.Properties.Set(PointsPerPixel_Key, value); }
}
public ImageInterpolation ImageInterpolation
{
get { return Control.InterpolationQuality.ToEto(); }
set { Control.InterpolationQuality = value.ToCG(); }
}
public void CreateFromImage(Bitmap image)
{
var handler = image.Handler as BitmapHandler;
#if OSX
var rep = handler.Control.Representations().OfType<NSBitmapImageRep>().FirstOrDefault();
graphicsContext = NSGraphicsContext.FromBitmap(rep);
graphicsContext = graphicsContext.IsFlipped ? graphicsContext : NSGraphicsContext.FromGraphicsPort(graphicsContext.GraphicsPortHandle, true);
disposeContext = true;
Control = graphicsContext.GraphicsPort;
PointsPerPixel = (float)(rep.PixelsWide / handler.Control.Size.Width);
#elif IOS
var cgimage = handler.Control.CGImage;
Control = new CGBitmapContext(handler.Data.MutableBytes, cgimage.Width, cgimage.Height, cgimage.BitsPerComponent, cgimage.BytesPerRow, cgimage.ColorSpace, cgimage.BitmapInfo);
PointsPerPixel = (float)(cgimage.Width / handler.Control.Size.Width);
#endif
height = image.Size.Height;
SetDefaults();
InitializeContext(true);
}
public void Reset()
{
// unwind all SaveState's
RewindAll();
// initial save state
Control.RestoreState();
}
public void Flush()
{
#if OSX
graphicsContext.FlushGraphics();
#endif
}
#if OSX
public float ViewHeight
{
get { return (float)(view != null ? view.Bounds.Height : height); }
}
#elif IOS
public float ViewHeight
{
get { return height; }
}
#endif
void SetDefaults()
{
Control.InterpolationQuality = CGInterpolationQuality.Default;
Control.SetAllowsSubpixelPositioning(false);
}
#if OSX
CGSize? phase;
public void SetPhase()
{
if (DisplayView == null)
return;
if (phase == null)
{
// find parent with layer, or goes up to window if none are found
var layerView = DisplayView;
while (layerView.Superview != null && layerView.Layer == null)
layerView = layerView.Superview;
// convert bottom-left point relative to layer or window
var pos = DisplayView.ConvertPointToView(CGPoint.Empty, layerView);
// phase should be based on position of control within closest layer or window.
phase = new CGSize(pos.X, pos.Y);
}
Control.SetPatternPhase(phase.Value);
}
#endif
void InitializeContext(bool viewFlipped)
{
Control.SaveState();
#if OSX
// os x has different flipped states (depending on layers, etc), so compensate to make 0,0 at the top-left
if (view != null)
{
// we have a view (drawing directly to the screen), so adjust to where it is
Control.ClipToRect(view.ConvertRectToView(view.VisibleRect(), null));
var pos = view.ConvertPointToView(CGPoint.Empty, null);
if (!viewFlipped)
pos.Y += view.Frame.Height;
Control.ConcatCTM(new CGAffineTransform(1, 0, 0, -1, (float)pos.X, (float)pos.Y));
}
else
{
// drawing to a bitmap or during a drawRect operation
if (viewFlipped)
Control.ConcatCTM(new CGAffineTransform(1, 0, 0, -1, 0, ViewHeight));
}
phase = null;
#elif IOS
if (viewFlipped)
{
// on ios, we flip the context if we're drawing on a bitmap otherwise we don't need to
Control.ConcatCTM(new CGAffineTransform(1, 0, 0, -1, 0, ViewHeight));
}
#endif
ApplyAll();
}
void StartDrawing()
{
#if OSX
NSGraphicsContext.GlobalSaveGraphicsState();
NSGraphicsContext.CurrentContext = graphicsContext;
#elif IOS
UIGraphics.PushContext(Control);
#endif
Control.SaveState();
}
void EndDrawing()
{
Control.RestoreState();
#if OSX
NSGraphicsContext.GlobalRestoreGraphicsState();
#elif IOS
UIGraphics.PopContext();
#endif
}
public void DrawLine(Pen pen, float startx, float starty, float endx, float endy)
{
SetOffset(false);
StartDrawing();
pen.Apply(this);
Control.StrokeLineSegments(new []
{
new CGPoint(startx, starty),
new CGPoint(endx, endy)
});
EndDrawing();
}
public void DrawRectangle(Pen pen, float x, float y, float width, float height)
{
SetOffset(false);
StartDrawing();
var rect = new CGRect(x, y, width, height);
pen.Apply(this);
Control.StrokeRect(rect);
EndDrawing();
}
public void FillRectangle(Brush brush, float x, float y, float width, float height)
{
SetOffset(true);
StartDrawing();
var rect = new CGRect(x, y, width, height);
Control.AddRect(rect);
Control.Clip();
brush.Draw(this, rect.ToEto());
EndDrawing();
}
public void DrawEllipse(Pen pen, float x, float y, float width, float height)
{
SetOffset(false);
StartDrawing();
var rect = new CGRect(x, y, width, height);
pen.Apply(this);
Control.StrokeEllipseInRect(rect);
EndDrawing();
}
public void FillEllipse(Brush brush, float x, float y, float width, float height)
{
SetOffset(true);
StartDrawing();
/* if (width == 1 || height == 1)
{
DrawLine(color, x, y, x+width-1, y+height-1);
return;
}*/
var rect = new CGRect(x, y, width, height);
Control.AddEllipseInRect(rect);
Control.Clip();
brush.Draw(this, rect.ToEto());
EndDrawing();
}
public void DrawArc(Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle)
{
SetOffset(false);
StartDrawing();
var rect = new CGRect(x, y, width, height);
pen.Apply(this);
var yscale = rect.Height / rect.Width;
var centerY = rect.GetMidY();
var centerX = rect.GetMidX();
Control.ConcatCTM(new CGAffineTransform(1.0f, 0, 0, yscale, 0, centerY - centerY * yscale));
Control.AddArc(centerX, centerY, rect.Width / 2, CGConversions.DegreesToRadians(startAngle), CGConversions.DegreesToRadians(startAngle + sweepAngle), sweepAngle < 0);
Control.StrokePath();
EndDrawing();
}
public void FillPie(Brush brush, float x, float y, float width, float height, float startAngle, float sweepAngle)
{
SetOffset(true);
StartDrawing();
var rect = new CGRect(x, y, width, height);
Control.SaveState();
var yscale = rect.Height / rect.Width;
var centerY = rect.GetMidY();
var centerX = rect.GetMidX();
Control.ConcatCTM(new CGAffineTransform(1.0f, 0, 0, yscale, 0, centerY - centerY * yscale));
Control.MoveTo(centerX, centerY);
Control.AddArc(centerX, centerY, rect.Width / 2, CGConversions.DegreesToRadians(startAngle), CGConversions.DegreesToRadians(startAngle + sweepAngle), sweepAngle < 0);
Control.AddLineToPoint(centerX, centerY);
Control.ClosePath();
Control.RestoreState();
Control.Clip();
brush.Draw(this, rect.ToEto());
EndDrawing();
}
public void FillPath(Brush brush, IGraphicsPath path)
{
SetOffset(true);
StartDrawing();
Control.BeginPath();
Control.AddPath(path.ToCG());
Control.ClosePath();
switch (path.FillMode)
{
case FillMode.Alternate:
Control.EOClip();
break;
case FillMode.Winding:
Control.Clip();
break;
default:
throw new NotSupportedException();
}
brush.Draw(this, path.Bounds);
EndDrawing();
}
public void DrawPath(Pen pen, IGraphicsPath path)
{
SetOffset(false);
StartDrawing();
pen.Apply(this);
Control.BeginPath();
Control.AddPath(path.ToCG());
Control.StrokePath();
EndDrawing();
}
public void DrawImage(Image image, float x, float y)
{
SetOffset(true);
StartDrawing();
var handler = (IImageHandler)image.Handler;
handler.DrawImage(this, x, y);
EndDrawing();
}
public void DrawImage(Image image, float x, float y, float width, float height)
{
SetOffset(true);
StartDrawing();
var handler = (IImageHandler)image.Handler;
handler.DrawImage(this, x, y, width, height);
EndDrawing();
}
public void DrawImage(Image image, RectangleF source, RectangleF destination)
{
SetOffset(true);
StartDrawing();
var handler = (IImageHandler)image.Handler;
handler.DrawImage(this, source, destination);
EndDrawing();
}
public void DrawText(Font font, SolidBrush brush, float x, float y, string text)
{
SetOffset(true);
if (string.IsNullOrEmpty(text))
return;
StartDrawing();
FontExtensions.DrawString(text, new PointF(x, y), brush.Color, font);
EndDrawing();
}
public SizeF MeasureString(Font font, string text)
{
StartDrawing();
var size = FontExtensions.MeasureString(text, font);
EndDrawing();
return size;
}
#if OSX
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (disposeContext && graphicsContext != null)
graphicsContext.FlushGraphics();
Reset();
if (disposeContext && graphicsContext != null)
graphicsContext.Dispose();
}
base.Dispose(disposing);
}
#endif
public void TranslateTransform(float offsetX, float offsetY)
{
Control.TranslateCTM(offsetX, offsetY);
currentTransform = CGAffineTransform.Multiply(CGAffineTransform.MakeTranslation(offsetX, offsetY), currentTransform);
}
public void RotateTransform(float angle)
{
angle = (float)CGConversions.DegreesToRadians(angle);
Control.RotateCTM(angle);
currentTransform = CGAffineTransform.Multiply(CGAffineTransform.MakeRotation(angle), currentTransform);
}
public void ScaleTransform(float scaleX, float scaleY)
{
Control.ScaleCTM(scaleX, scaleY);
currentTransform = CGAffineTransform.Multiply(CGAffineTransform.MakeScale(scaleX, scaleY), currentTransform);
}
public void MultiplyTransform(IMatrix matrix)
{
var m = matrix.ToCG();
Control.ConcatCTM(m);
currentTransform = CGAffineTransform.Multiply(m, currentTransform);
}
public void SaveTransform()
{
transforms.Push(currentTransform);
}
public void RestoreTransform()
{
if (transforms.Count <= 0)
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "No saved transform"));
RewindTransform();
currentTransform = transforms.Pop();
ApplyTransform();
}
public IMatrix CurrentTransform
{
get { return currentTransform.ToEto(); }
}
public RectangleF ClipBounds
{
get { return Control.GetClipBoundingBox().ToEto(); }
}
public void SetClip(RectangleF rectangle)
{
RewindTransform();
RewindClip();
clipPath = null;
clipBounds = currentTransform.TransformRect(rectangle.ToNS());
ApplyClip();
ApplyTransform();
}
public void SetClip(IGraphicsPath path)
{
RewindTransform();
RewindClip();
clipBounds = null;
clipPath = path.Clone();
clipPath.Transform(currentTransform.ToEto());
ApplyClip();
ApplyTransform();
}
void ApplyClip()
{
if (clipPath != null)
{
Control.SaveState();
Control.AddPath(clipPath.ToCG());
switch (clipPath.FillMode)
{
case FillMode.Alternate:
Control.EOClip();
break;
case FillMode.Winding:
Control.Clip();
break;
default:
throw new NotSupportedException();
}
}
else if (clipBounds != null)
{
Control.SaveState();
Control.ClipToRect(clipBounds.Value);
}
}
void RewindClip()
{
if (clipBounds != null || clipPath != null)
{
Control.RestoreState();
}
}
void RewindTransform()
{
Control.RestoreState();
}
void ApplyTransform()
{
Control.SaveState();
Control.ConcatCTM(currentTransform);
}
void RewindAll()
{
RewindTransform();
RewindClip();
if (isOffset)
{
Control.RestoreState();
}
}
void ApplyAll()
{
if (isOffset)
{
Control.SaveState();
Control.TranslateCTM(0.5f, 0.5f);
}
ApplyClip();
ApplyTransform();
}
public void ResetClip()
{
RewindTransform();
RewindClip();
clipBounds = null;
clipPath = null;
ApplyTransform();
}
public void Clear(SolidBrush brush)
{
var rect = Control.GetClipBoundingBox();
Control.ClearRect(rect);
if (brush != null)
FillRectangle(brush, (float)rect.X, (float)rect.Y, (float)rect.Width, (float)rect.Height);
}
public void SetFillColorSpace()
{
Control.SetFillColorSpace(patternColorSpace);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for RoutesOperations.
/// </summary>
public static partial class RoutesOperationsExtensions
{
/// <summary>
/// Deletes the specified route from a route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
public static void Delete(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName)
{
operations.DeleteAsync(resourceGroupName, routeTableName, routeName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified route from a route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified route from a route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
public static Route Get(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName)
{
return operations.GetAsync(resourceGroupName, routeTableName, routeName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified route from a route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Route> GetAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a route in the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Parameters supplied to the create or update route operation.
/// </param>
public static Route CreateOrUpdate(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, routeTableName, routeName, routeParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a route in the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Parameters supplied to the create or update route operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Route> CreateOrUpdateAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all routes in a route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
public static IPage<Route> List(this IRoutesOperations operations, string resourceGroupName, string routeTableName)
{
return operations.ListAsync(resourceGroupName, routeTableName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all routes in a route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Route>> ListAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified route from a route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
public static void BeginDelete(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName)
{
operations.BeginDeleteAsync(resourceGroupName, routeTableName, routeName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified route from a route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a route in the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Parameters supplied to the create or update route operation.
/// </param>
public static Route BeginCreateOrUpdate(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, routeTableName, routeName, routeParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a route in the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Parameters supplied to the create or update route operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Route> BeginCreateOrUpdateAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all routes in a route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Route> ListNext(this IRoutesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all routes in a route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Route>> ListNextAsync(this IRoutesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using Microsoft.Graphics.Canvas.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WinIRC.Ui;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WinIRC
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class DisplaySettingsView : BaseSettingsPage
{
public DisplaySettingsView()
{
this.InitializeComponent();
Title = "Appearance";
LoadSettings();
}
public List<string> Fonts
{
get
{
return CanvasTextFormat.GetSystemFontFamilies().OrderBy(f => f).ToList();
}
}
private void LoadSettings()
{
FontCombo.ItemsSource = Fonts;
if (Config.Contains(Config.DarkTheme))
{
this.Theme.IsOn = Config.GetBoolean(Config.DarkTheme);
}
else
{
Config.SetBoolean(Config.DarkTheme, true);
this.Theme.IsOn = true;
}
if (Config.Contains(Config.Blurred))
{
this.BlurredBack.IsOn = Config.GetBoolean(Config.Blurred);
}
else
{
Config.SetBoolean(Config.Blurred, true);
this.BlurredBack.IsOn = true;
}
if (Config.Contains(Config.FontFamily))
{
this.FontCombo.SelectedValue = Config.GetString(Config.FontFamily);
}
else
{
Config.SetString(Config.FontFamily, "Segoe UI");
this.FontCombo.SelectedValue = "Segoe UI";
}
if (Config.Contains(Config.FontSize))
{
this.FontSize.Value = Config.GetInt(Config.FontSize, 14);
}
else
{
Config.SetInt(Config.FontSize, 14);
this.FontSize.Value = 14;
}
if (Config.Contains(Config.ReducedPadding))
{
this.Padding.IsOn = Config.GetBoolean(Config.ReducedPadding);
}
else
{
Config.SetBoolean(Config.ReducedPadding, false);
this.Padding.IsOn = false;
}
if (Config.Contains(Config.HideStatusBar))
{
this.HideStatusBar.IsOn = Config.GetBoolean(Config.HideStatusBar);
}
else
{
Config.SetBoolean(Config.HideStatusBar, false);
this.HideStatusBar.IsOn = false;
}
if (Config.Contains(Config.IgnoreJoinLeave))
{
this.IgnoreJoinLeave.IsOn = Config.GetBoolean(Config.IgnoreJoinLeave);
}
else
{
Config.SetBoolean(Config.IgnoreJoinLeave, false);
this.IgnoreJoinLeave.IsOn = false;
}
if (Config.Contains(Config.ShowMetadata))
{
this.LinkMetadata.IsOn = Config.GetBoolean(Config.ShowMetadata);
}
else
{
Config.SetBoolean(Config.ShowMetadata, true);
this.LinkMetadata.IsOn = true;
}
if (Config.Contains(Config.ModernChat))
{
this.ModernChatStyle.IsOn = Config.GetBoolean(Config.ModernChat);
}
else
{
Config.SetBoolean(Config.ModernChat, false);
this.ModernChatStyle.IsOn = false;
}
this.SettingsLoaded = true;
}
private async void theme_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetBoolean(Config.DarkTheme, Theme.IsOn);
(Application.Current as App).SetTheme();
base.UpdateUi();
}
private void FontCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetString(Config.FontFamily, FontCombo.SelectedValue as string);
base.UpdateUi();
}
private void Padding_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetBoolean(Config.ReducedPadding, Padding.IsOn);
base.UpdateUi();
}
private void HideStatusBar_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetBoolean(Config.HideStatusBar, HideStatusBar.IsOn);
base.UpdateUi();
}
private void IgnoreJoinLeave_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetBoolean(Config.IgnoreJoinLeave, IgnoreJoinLeave.IsOn);
base.UpdateUi();
}
private void BlurredBack_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetBoolean(Config.Blurred, BlurredBack.IsOn);
base.UpdateUi();
}
private void LinkMetadata_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetBoolean(Config.ShowMetadata, LinkMetadata.IsOn);
base.UpdateUi();
}
private void FontSize_LosingFocus(UIElement sender, LosingFocusEventArgs args)
{
if (!SettingsLoaded)
return;
Config.SetInt(Config.FontSize, (int)FontSize.Value);
base.UpdateUi();
}
private void ModernChatStyle_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetBoolean(Config.ModernChat, ModernChatStyle.IsOn);
base.UpdateUi();
}
}
public class FontClass
{
public FontFamily FontFamily { get; set; }
public string FontFamilyValue { get; set; }
}
}
| |
//
// AudioSessions.cs:
//
// Authors:
// Miguel de Icaza (miguel@novell.com)
//
// Copyright 2009 Novell, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
using OSStatus = System.Int32;
using AudioQueueParameterID = System.UInt32;
using AudioQueueParameterValue = System.Single;
using AudioQueueRef = System.IntPtr;
using AudioQueueTimelineRef = System.IntPtr;
namespace MonoMac.AudioToolbox {
public class AudioSessionException : Exception {
static string Lookup (int k)
{
switch ((AudioSessionErrors)k){
case AudioSessionErrors.NotInitialized:
return "AudioSession.Initialize has not been called";
case AudioSessionErrors.AlreadyInitialized:
return "You called AudioSession.Initialize more than once";
case AudioSessionErrors.InitializationError:
return "There was an error during the AudioSession.initialization";
case AudioSessionErrors.UnsupportedPropertyError:
return "The audio session property is not supported";
case AudioSessionErrors.BadPropertySizeError:
return "The size of the audio property was not correct";
case AudioSessionErrors.NotActiveError:
return "Application Audio Session is not active";
case AudioSessionErrors.NoHardwareError:
return "The device has no Audio Input capability";
case AudioSessionErrors.IncompatibleCategory:
return "The specified AudioSession.Category can not be used with this audio operation";
case AudioSessionErrors.NoCategorySet:
return "This operation requries AudioSession.Category to be explicitly set";
}
return String.Format ("Unknown error code: 0x{0:x}", k);
}
internal AudioSessionException (int k) : base (Lookup (k))
{
}
}
public class AudioSessionPropertyEventArgs :EventArgs {
public AudioSessionPropertyEventArgs (AudioSessionProperty prop, int size, IntPtr data)
{
this.Property = prop;
this.Size = size;
this.Data = data;
}
public AudioSessionProperty Property { get; set; }
public int Size { get; set; }
public IntPtr Data { get; set; }
}
public static class AudioSession {
static bool initialized;
public static event EventHandler Interrupted;
public static event EventHandler Resumed;
[DllImport (Constants.AudioToolboxLibrary)]
extern static OSStatus AudioSessionInitialize(IntPtr cfRunLoop, IntPtr cfstr_runMode, InterruptionListener listener, IntPtr userData);
public static void Initialize ()
{
Initialize (null, null);
}
public static void Initialize (CFRunLoop runLoop, string runMode)
{
if (initialized)
return;
CFString s = runMode == null ? null : new CFString (runMode);
int k = AudioSessionInitialize (runLoop == null ? IntPtr.Zero : runLoop.Handle, s == null ? IntPtr.Zero : s.Handle, Interruption, IntPtr.Zero);
if (k != 0)
throw new AudioSessionException (k);
initialized = true;
}
delegate void InterruptionListener (IntPtr userData, uint state);
[MonoPInvokeCallback (typeof (InterruptionListener))]
static void Interruption (IntPtr userData, uint state)
{
EventHandler h;
h = (state == 1) ? Interrupted : Resumed;
if (h != null)
h (null, EventArgs.Empty);
}
[DllImport (Constants.AudioToolboxLibrary)]
extern static OSStatus AudioSessionSetActive (int active);
public static void SetActive (bool active)
{
int k = AudioSessionSetActive (active ? 1 : 0);
if (k != 0)
throw new AudioSessionException (k);
}
[DllImport (Constants.AudioToolboxLibrary)]
extern static OSStatus AudioSessionGetProperty(AudioSessionProperty id, ref int size, IntPtr data);
[DllImport (Constants.AudioToolboxLibrary)]
extern static OSStatus AudioSessionSetProperty (AudioSessionProperty id, int size, IntPtr data);
[DllImport (Constants.AudioToolboxLibrary)]
extern static OSStatus AudioSessionGetPropertySize (AudioSessionProperty id, out int size);
static double GetDouble (AudioSessionProperty property)
{
unsafe {
double val = 0;
int size = 8;
int k = AudioSessionGetProperty (property, ref size, (IntPtr) (&val));
if (k != 0)
throw new AudioSessionException (k);
return val;
}
}
static float GetFloat (AudioSessionProperty property)
{
unsafe {
float val = 0;
int size = 4;
int k = AudioSessionGetProperty (property, ref size, (IntPtr) (&val));
if (k != 0)
throw new AudioSessionException (k);
return val;
}
}
static int GetInt (AudioSessionProperty property)
{
unsafe {
int val = 0;
int size = 4;
int k = AudioSessionGetProperty (property, ref size, (IntPtr) (&val));
if (k != 0)
throw new AudioSessionException (k);
return val;
}
}
static void SetDouble (AudioSessionProperty property, double val)
{
unsafe {
int k = AudioSessionSetProperty (property, 8, (IntPtr) (&val));
if (k != 0)
throw new AudioSessionException (k);
}
}
static void SetInt (AudioSessionProperty property, int val)
{
unsafe {
int k = AudioSessionSetProperty (property, 4, (IntPtr) (&val));
if (k != 0)
throw new AudioSessionException (k);
}
}
static void SetFloat (AudioSessionProperty property, float val)
{
unsafe {
int k = AudioSessionSetProperty (property, 4, (IntPtr) (&val));
if (k != 0)
throw new AudioSessionException (k);
}
}
static public double PreferredHardwareSampleRate {
get {
return GetDouble (AudioSessionProperty.PreferredHardwareSampleRate);
}
set {
SetDouble (AudioSessionProperty.PreferredHardwareSampleRate, value);
}
}
static public float PreferredHardwareIOBufferDuration {
get {
return GetFloat (AudioSessionProperty.PreferredHardwareIOBufferDuration);
}
set {
SetFloat (AudioSessionProperty.PreferredHardwareIOBufferDuration, value);
}
}
static public AudioSessionCategory Category {
get {
return (AudioSessionCategory) GetInt (AudioSessionProperty.AudioCategory);
}
set {
SetInt (AudioSessionProperty.AudioCategory, (int) value);
}
}
[Since (4,0)]
public static AudioSessionInterruptionType InterruptionType {
get {
return (AudioSessionInterruptionType) GetInt (AudioSessionProperty.InterruptionType);
}
}
static public string AudioRoute {
get {
return CFString.FetchString ((IntPtr) GetInt (AudioSessionProperty.AudioRoute));
}
}
static public double CurrentHardwareSampleRate {
get {
return GetDouble (AudioSessionProperty.CurrentHardwareSampleRate);
}
}
static public int CurrentHardwareInputNumberChannels {
get {
return GetInt (AudioSessionProperty.CurrentHardwareInputNumberChannels);
}
}
static public int CurrentHardwareOutputNumberChannels {
get {
return GetInt (AudioSessionProperty.CurrentHardwareOutputNumberChannels);
}
}
static public float CurrentHardwareOutputVolume {
get {
return GetFloat (AudioSessionProperty.CurrentHardwareOutputVolume);
}
}
static public float CurrentHardwareInputLatency {
get {
return GetFloat (AudioSessionProperty.CurrentHardwareInputLatency);
}
}
static public float CurrentHardwareOutputLatency {
get {
return GetFloat (AudioSessionProperty.CurrentHardwareOutputLatency);
}
}
static public float CurrentHardwareIOBufferDuration {
get {
return GetFloat (AudioSessionProperty.CurrentHardwareIOBufferDuration);
}
}
static public bool OtherAudioIsPlaying {
get {
return GetInt (AudioSessionProperty.OtherAudioIsPlaying) != 0;
}
}
static public AudioSessionRoutingOverride RoutingOverride {
set {
SetInt (AudioSessionProperty.OverrideAudioRoute, (int) value);
}
}
static public bool AudioInputAvailable {
get {
return GetInt (AudioSessionProperty.AudioInputAvailable) != 0;
}
}
static public bool AudioShouldDuck {
get {
return GetInt (AudioSessionProperty.OtherMixableAudioShouldDuck) != 0;
}
set {
SetInt (AudioSessionProperty.OtherMixableAudioShouldDuck, value ? 1 : 0);
}
}
static public bool OverrideCategoryMixWithOthers {
get {
return GetInt (AudioSessionProperty.OverrideCategoryMixWithOthers) != 0;
}
set {
SetInt (AudioSessionProperty.OverrideCategoryMixWithOthers, value ? 1 : 0);
}
}
delegate void _PropertyListener (IntPtr userData, AudioSessionProperty prop, int size, IntPtr data);
public delegate void PropertyListener (AudioSessionProperty prop, int size, IntPtr data);
[MonoPInvokeCallback (typeof (_PropertyListener))]
static void Listener (IntPtr userData, AudioSessionProperty prop, int size, IntPtr data)
{
ArrayList a = (ArrayList) listeners [prop];
if (a == null){
// Should never happen
return;
}
foreach (PropertyListener pl in a){
pl (prop, size, data);
}
}
[DllImport (Constants.AudioToolboxLibrary)]
extern static OSStatus AudioSessionAddPropertyListener(AudioSessionProperty id, _PropertyListener inProc, IntPtr userData);
static Hashtable listeners;
public static void AddListener (AudioSessionProperty property, PropertyListener listener)
{
if (listener == null)
throw new ArgumentNullException ("listener");
if (listeners == null)
listeners = new Hashtable ();
ArrayList a = (ArrayList) listeners [property];
if (a == null)
listeners [property] = a = new ArrayList ();
a.Add (listener);
if (a.Count == 1)
AudioSessionAddPropertyListener (property, Listener, IntPtr.Zero);
}
public static void RemoveListener (AudioSessionProperty property, PropertyListener listener)
{
if (listener == null)
throw new ArgumentNullException ("listener");
ArrayList a = (ArrayList) listeners [property];
if (a == null)
return;
a.Remove (listener);
if (a.Count == 0)
listeners [property] = null;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Shell;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
using VSConstants = Microsoft.VisualStudio.VSConstants;
using Microsoft.Samples.VisualStudio.IronPythonInference;
using IronPython.Compiler;
namespace Microsoft.Samples.VisualStudio.IronPythonLanguageService {
/// <summary>
/// This is a specialized version of the LibraryNode that handles the IronPython's
/// items. The main difference from the generic one is that it supports navigation
/// to the location inside the source code where the element is defined.
/// </summary>
internal class PythonLibraryNode : LibraryNode {
private IVsHierarchy ownerHierarchy;
private uint fileId;
private TextSpan sourceSpan;
private string fileMoniker;
internal PythonLibraryNode(ScopeNode scope, string namePrefix, IVsHierarchy hierarchy, uint itemId) :
base(scope.Name) {
if (scope is FunctionNode) {
this.NodeType = LibraryNodeType.Members;
} else if (scope is ClassNode) {
this.NodeType = LibraryNodeType.Classes;
this.Name = string.Format(CultureInfo.InvariantCulture, "{0}{1}", namePrefix, scope.Name);
}
this.ownerHierarchy = hierarchy;
this.fileId = itemId;
// Now check if we have all the information to navigate to the source location.
if ((null != ownerHierarchy) && (VSConstants.VSITEMID_NIL != fileId)) {
if ((0 != Location.Compare(Location.None, scope.Start)) && (0 != Location.Compare(Location.None, scope.End))) {
sourceSpan = new TextSpan();
sourceSpan.iStartIndex = scope.Start.Column;
if (scope.Start.Line > 0) {
sourceSpan.iStartLine = scope.Start.Line - 1;
}
sourceSpan.iEndIndex = scope.End.Column;
if (scope.End.Line > 0) {
sourceSpan.iEndLine = scope.End.Line - 1;
}
this.CanGoToSource = true;
}
}
}
internal PythonLibraryNode(PythonLibraryNode node) :
base(node) {
this.fileId = node.fileId;
this.ownerHierarchy = node.ownerHierarchy;
this.fileMoniker = node.fileMoniker;
}
protected override uint CategoryField(LIB_CATEGORY category) {
switch (category) {
case (LIB_CATEGORY)_LIB_CATEGORY2.LC_MEMBERINHERITANCE:
if (this.NodeType == LibraryNodeType.Members) {
return (uint)_LIBCAT_MEMBERINHERITANCE.LCMI_IMMEDIATE;
}
break;
}
return base.CategoryField(category);
}
protected override LibraryNode Clone() {
return new PythonLibraryNode(this);
}
protected override void GotoSource(VSOBJGOTOSRCTYPE gotoType) {
// We do not support the "Goto Reference"
if (VSOBJGOTOSRCTYPE.GS_REFERENCE == gotoType) {
return;
}
// There is no difference between definition and declaration, so here we
// don't check for the other flags.
IVsWindowFrame frame = null;
IntPtr documentData = FindDocDataFromRDT();
try {
// Now we can try to open the editor. We assume that the owner hierarchy is
// a project and we want to use its OpenItem method.
IVsProject3 project = ownerHierarchy as IVsProject3;
if (null == project) {
return;
}
Guid viewGuid = VSConstants.LOGVIEWID_Code;
ErrorHandler.ThrowOnFailure(project.OpenItem(fileId, ref viewGuid, documentData, out frame));
} finally {
if (IntPtr.Zero != documentData) {
Marshal.Release(documentData);
documentData = IntPtr.Zero;
}
}
// Make sure that the document window is visible.
ErrorHandler.ThrowOnFailure(frame.Show());
// Get the code window from the window frame.
object docView;
ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out docView));
IVsCodeWindow codeWindow = docView as IVsCodeWindow;
if (null == codeWindow) {
object docData;
ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData));
codeWindow = docData as IVsCodeWindow;
if (null == codeWindow) {
return;
}
}
// Get the primary view from the code window.
IVsTextView textView;
ErrorHandler.ThrowOnFailure(codeWindow.GetPrimaryView(out textView));
// Set the cursor at the beginning of the declaration.
ErrorHandler.ThrowOnFailure(textView.SetCaretPos(sourceSpan.iStartLine, sourceSpan.iStartIndex));
// Make sure that the text is visible.
TextSpan visibleSpan = new TextSpan();
visibleSpan.iStartLine = sourceSpan.iStartLine;
visibleSpan.iStartIndex = sourceSpan.iStartIndex;
visibleSpan.iEndLine = sourceSpan.iStartLine;
visibleSpan.iEndIndex = sourceSpan.iStartIndex + 1;
ErrorHandler.ThrowOnFailure(textView.EnsureSpanVisible(visibleSpan));
}
protected override void SourceItems(out IVsHierarchy hierarchy, out uint itemId, out uint itemsCount) {
hierarchy = ownerHierarchy;
itemId = fileId;
itemsCount = 1;
}
public override string UniqueName {
get {
if (string.IsNullOrEmpty(fileMoniker)) {
ErrorHandler.ThrowOnFailure(ownerHierarchy.GetCanonicalName(fileId, out fileMoniker));
}
return string.Format(CultureInfo.InvariantCulture, "{0}/{1}", fileMoniker, Name);
}
}
private IntPtr FindDocDataFromRDT() {
// Get a reference to the RDT.
IVsRunningDocumentTable rdt = PythonPackage.GetGlobalService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null == rdt) {
return IntPtr.Zero;
}
// Get the enumeration of the running documents.
IEnumRunningDocuments documents;
ErrorHandler.ThrowOnFailure(rdt.GetRunningDocumentsEnum(out documents));
IntPtr documentData = IntPtr.Zero;
uint[] docCookie = new uint[1];
uint fetched;
while ((VSConstants.S_OK == documents.Next(1, docCookie, out fetched)) && (1 == fetched)) {
uint flags;
uint editLocks;
uint readLocks;
string moniker;
IVsHierarchy docHierarchy;
uint docId;
IntPtr docData = IntPtr.Zero;
try {
ErrorHandler.ThrowOnFailure(
rdt.GetDocumentInfo(docCookie[0], out flags, out readLocks, out editLocks, out moniker, out docHierarchy, out docId, out docData));
// Check if this document is the one we are looking for.
if ((docId == fileId) && (ownerHierarchy.Equals(docHierarchy))) {
documentData = docData;
docData = IntPtr.Zero;
break;
}
} finally {
if (IntPtr.Zero != docData) {
Marshal.Release(docData);
}
}
}
return documentData;
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2013 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using MsgPack.Serialization.Reflection;
namespace MsgPack.Serialization.EmittingSerializers
{
// Reduce JIT
/// <summary>
/// Defines non-generic functions of <see cref="EmittingSerializerBuilder{T}"/>.
/// </summary>
internal static class EmittingSerializerBuilderLogics
{
private static readonly Type[] _delegateConstructorParameterTypes = new Type[] { typeof( object ), typeof( IntPtr ) };
#region -- Arrays --
public static SerializerEmitter CreateArraySerializerCore( SerializationContext context, Type targetType, EmitterFlavor emitterFlavor )
{
Contract.Requires( targetType != null );
Contract.Ensures( Contract.Result<SerializerEmitter>() != null );
var emitter = SerializationMethodGeneratorManager.Get().CreateEmitter( targetType, emitterFlavor );
var traits = targetType.GetCollectionTraits();
CreatePackArrayProceduresCore( targetType, emitter, traits );
CreateUnpackArrayProceduresCore( context, targetType, emitter, traits );
return emitter;
}
private static void CreatePackArrayProceduresCore( Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
var il = emitter.GetPackToMethodILGenerator();
var localHolder = new LocalVariableHolder( il );
try
{
// Array
if ( targetType.IsArray )
{
/*
* // array
* packer.PackArrayHeader( length );
* for( int i = 0; i < length; i++ )
* {
* this._serializer.PackTo( packer, collection[ i ] );
* }
*/
var length = localHolder.PackingCollectionCount;
il.EmitAnyLdarg( 2 );
il.EmitLdlen();
il.EmitAnyStloc( length );
il.EmitAnyLdarg( 1 );
il.EmitAnyLdloc( length );
il.EmitAnyCall( Metadata._Packer.PackArrayHeader );
il.EmitPop();
Emittion.EmitFor(
il,
length,
( il0, i ) =>
Emittion.EmitSerializeValue(
emitter,
il0,
1,
traits.ElementType,
null,
NilImplication.MemberDefault,
il1 =>
{
il1.EmitAnyLdarg( 2 );
il1.EmitAnyLdloc( i );
il1.EmitLdelem( traits.ElementType );
},
localHolder
)
);
}
else if ( traits.CountProperty == null )
{
/*
* array = collection.ToArray();
* packer.PackArrayHeader( length );
* for( int i = 0; i < length; i++ )
* {
* this._serializer.PackTo( packer, array[ i ] );
* }
*/
var array = localHolder.GetSerializingCollection( traits.ElementType.MakeArrayType() );
EmitLoadTarget( targetType, il, 2 );
il.EmitAnyCall( Metadata._Enumerable.ToArray1Method.MakeGenericMethod( traits.ElementType ) );
il.EmitAnyStloc( array );
var length = localHolder.PackingCollectionCount;
il.EmitAnyLdloc( array );
il.EmitLdlen();
il.EmitAnyStloc( length );
il.EmitAnyLdarg( 1 );
il.EmitAnyLdloc( length );
il.EmitAnyCall( Metadata._Packer.PackArrayHeader );
il.EmitPop();
Emittion.EmitFor(
il,
length,
( il0, i ) =>
Emittion.EmitSerializeValue(
emitter,
il0,
1,
traits.ElementType,
null,
NilImplication.MemberDefault,
il1 =>
{
il1.EmitAnyLdloc( array );
il1.EmitAnyLdloc( i );
il1.EmitLdelem( traits.ElementType );
},
localHolder
)
);
}
else
{
/*
* // Enumerable
* packer.PackArrayHeader( collection.Count );
* foreach( var item in list )
* {
* this._serializer.PackTo( packer, array[ i ] );
* }
*/
var collection = localHolder.GetSerializingCollection( targetType );
// This instruction always ldarg, not to be ldarga
il.EmitAnyLdarg( 2 );
il.EmitAnyStloc( collection );
var count = localHolder.PackingCollectionCount;
EmitLoadTarget( targetType, il, 2 );
il.EmitGetProperty( traits.CountProperty );
il.EmitAnyStloc( count );
il.EmitAnyLdarg( 1 );
il.EmitAnyLdloc( count );
il.EmitAnyCall( Metadata._Packer.PackArrayHeader );
il.EmitPop();
Emittion.EmitForEach(
il,
traits,
collection,
( il0, getCurrentEmitter ) =>
Emittion.EmitSerializeValue(
emitter,
il0,
1,
traits.ElementType,
null,
NilImplication.MemberDefault,
_ => getCurrentEmitter(),
localHolder
)
);
}
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void CreateUnpackArrayProceduresCore( SerializationContext context, Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
CreateArrayUnpackFrom( context, targetType, emitter, traits );
CreateArrayUnpackTo( targetType, emitter, traits );
}
private static void CreateArrayUnpackFrom( SerializationContext context, Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
var il = emitter.GetUnpackFromMethodILGenerator();
var localHolder = new LocalVariableHolder( il );
var instanceType = targetType;
try
{
if ( targetType.IsInterface || targetType.IsAbstract )
{
instanceType = context.DefaultCollectionTypes.GetConcreteType( targetType );
if ( instanceType == null )
{
il.EmitTypeOf( targetType );
il.EmitAnyCall( SerializationExceptions.NewNotSupportedBecauseCannotInstanciateAbstractTypeMethod );
il.EmitThrow();
return;
}
}
/*
* if (!unpacker.IsArrayHeader)
* {
* throw SerializationExceptions.NewIsNotArrayHeader();
* }
*
* TCollection collection = new ...;
* this.UnpackToCore(unpacker, array);
* return collection;
*/
il.EmitAnyLdarg( 1 );
il.EmitGetProperty( Metadata._Unpacker.IsArrayHeader );
var endIf = il.DefineLabel( "END_IF" );
il.EmitBrtrue_S( endIf );
il.EmitAnyCall( SerializationExceptions.NewIsNotArrayHeaderMethod );
il.EmitThrow();
il.MarkLabel( endIf );
var collection = localHolder.GetDeserializingCollection( instanceType );
// Emit newobj, newarr, or call ValueType..ctor()
Emittion.EmitConstruction(
il,
collection,
il0 => Emittion.EmitGetUnpackerItemsCountAsInt32( il0, 1, localHolder )
);
EmitInvokeArrayUnpackToHelper( targetType, emitter, traits, il, 1, il0 => il0.EmitAnyLdloc( collection ) );
il.EmitAnyLdloc( collection );
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void CreateArrayUnpackTo( Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
var il = emitter.GetUnpackToMethodILGenerator();
try
{
EmitInvokeArrayUnpackToHelper( targetType, emitter, traits, il, 1, il0 => il0.EmitAnyLdarg( 2 ) );
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void EmitInvokeArrayUnpackToHelper( Type targetType, SerializerEmitter emitter, CollectionTraits traits, TracingILGenerator il, int unpackerArgumentIndex, Action<TracingILGenerator> loadCollectionEmitting )
{
il.EmitAnyLdarg( unpackerArgumentIndex );
var serializerGetting = emitter.RegisterSerializer( traits.ElementType );
if ( targetType.IsArray )
{
// Array
/*
* UnpackHelpers.UnpackArrayTo( unpacker, GET_SERIALIZER, collection );
*/
serializerGetting( il, 0 );
loadCollectionEmitting( il );
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackArrayTo_1.MakeGenericMethod( traits.ElementType ) );
}
else if ( targetType.IsGenericType )
{
serializerGetting( il, 0 );
loadCollectionEmitting( il );
if ( targetType.IsValueType )
{
il.EmitBox( targetType );
}
if ( traits.AddMethod.ReturnType == null || traits.AddMethod.ReturnType == typeof( void ) )
{
// with void Add( T item )
/*
* Action<T> addition = TCollection.Add
* UnpackHelpers.UnpackCollectionTo( unpacker, GET_SERIALIZER, collection, addition );
*/
var itemType = traits.AddMethod.GetParameters()[ 0 ].ParameterType;
EmitNewDelegate( il, targetType, traits.AddMethod, loadCollectionEmitting, typeof( Action<> ).MakeGenericType( itemType ) );
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackCollectionTo_1.MakeGenericMethod( itemType ) );
}
else
{
// with TDiscarded Add( T item )
/*
* Func<T, TDiscarded> addition = TCollection.Add
* UnpackHelpers.UnpackCollectionTo( unpacker, GET_SERIALIZER, collection, addition );
*/
var itemType = traits.AddMethod.GetParameters()[ 0 ].ParameterType;
var discardingType = traits.AddMethod.ReturnType;
EmitNewDelegate( il, targetType, traits.AddMethod, loadCollectionEmitting, typeof( Func<,> ).MakeGenericType( itemType, discardingType ) );
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackCollectionTo_2.MakeGenericMethod( itemType, discardingType ) );
}
}
else
{
loadCollectionEmitting( il );
if ( targetType.IsValueType )
{
il.EmitBox( targetType );
}
if ( traits.AddMethod.ReturnType == null || traits.AddMethod.ReturnType == typeof( void ) )
{
// with void Add( object item )
/*
* Action<object> addition = TCollection.Add
* UnpackHelpers.UnpackCollectionTo( unpacker, collection, addition );
*/
EmitNewDelegate( il, targetType, traits.AddMethod, loadCollectionEmitting, typeof( Action<object> ) );
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackNonGenericCollectionTo );
}
else
{
// with TDiscarded Add( object item )
/*
* Func<TDiscarded> addition = TCollection.Add
* UnpackHelpers.UnpackCollectionTo( unpacker, collection, addition );
*/
var discardingType = traits.AddMethod.ReturnType;
EmitNewDelegate( il, targetType, traits.AddMethod, loadCollectionEmitting, typeof( Func<,> ).MakeGenericType( typeof( object ), discardingType ) );
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackNonGenericCollectionTo_1.MakeGenericMethod( discardingType ) );
}
}
}
private static void EmitNewDelegate( TracingILGenerator il, Type targetType, MethodInfo method, Action<TracingILGenerator> loadTargetEmitting, Type delegateType )
{
loadTargetEmitting( il );
if ( targetType.IsValueType )
{
il.EmitBox( targetType );
}
if ( method.IsStatic || method.IsFinal || !method.IsVirtual )
{
il.EmitLdftn( method );
}
else
{
il.EmitDup();
il.EmitLdvirtftn( method );
}
il.EmitNewobj( delegateType.GetConstructor( _delegateConstructorParameterTypes ) );
}
#endregion -- Arrays --
#region -- Maps --
public static SerializerEmitter CreateMapSerializerCore( SerializationContext context, Type targetType, EmitterFlavor emitterFlavor )
{
Contract.Requires( targetType != null );
Contract.Ensures( Contract.Result<SerializerEmitter>() != null );
var emitter = SerializationMethodGeneratorManager.Get().CreateEmitter( targetType, emitterFlavor );
var traits = targetType.GetCollectionTraits();
CreateMapPack(
targetType,
emitter,
traits
);
CreateMapUnpack(
context,
targetType,
emitter,
traits
);
return emitter;
}
private static void CreateMapPack( Type targetType, SerializerEmitter emiter, CollectionTraits traits )
{
var il = emiter.GetPackToMethodILGenerator();
var localHolder = new LocalVariableHolder( il );
try
{
/*
* int count = ((ICollection<KeyValuePair<string, DateTime>>)dictionary).Count;
* packer.PackMapHeader(count);
* foreach (KeyValuePair<string, DateTime> current in dictionary)
* {
* this._serializer0.PackTo(packer, current.Key);
* this._serializer1.PackTo(packer, current.Value);
* }
*/
var collection = localHolder.GetSerializingCollection( targetType );
var item = localHolder.GetSerializingCollectionItem( traits.ElementType );
var keyProperty = traits.ElementType.GetProperty( "Key" );
var valueProperty = traits.ElementType.GetProperty( "Value" );
// This instruction is always ldarg, not to be ldarga.
il.EmitAnyLdarg( 2 );
il.EmitAnyStloc( collection );
var count = localHolder.PackingCollectionCount;
EmitLoadTarget( targetType, il, collection );
il.EmitGetProperty( traits.CountProperty );
il.EmitAnyStloc( count );
il.EmitAnyLdarg( 1 );
il.EmitAnyLdloc( count );
il.EmitAnyCall( Metadata._Packer.PackMapHeader );
il.EmitPop();
Emittion.EmitForEach(
il,
traits,
collection,
( il0, getCurrentEmitter ) =>
{
if ( traits.ElementType.IsGenericType )
{
Contract.Assert( traits.ElementType.GetGenericTypeDefinition() == typeof( KeyValuePair<,> ) );
getCurrentEmitter();
il0.EmitAnyStloc( item );
Emittion.EmitSerializeValue(
emiter,
il0,
1,
traits.ElementType.GetGenericArguments()[ 0 ],
null,
NilImplication.MemberDefault,
il1 =>
{
il1.EmitAnyLdloca( item );
il1.EmitGetProperty( keyProperty );
},
localHolder
);
Emittion.EmitSerializeValue(
emiter,
il0,
1,
traits.ElementType.GetGenericArguments()[ 1 ],
null,
NilImplication.MemberDefault,
il1 =>
{
il1.EmitAnyLdloca( item );
il1.EmitGetProperty( valueProperty );
},
localHolder
);
}
else
{
Contract.Assert( traits.ElementType == typeof( DictionaryEntry ) );
getCurrentEmitter();
il0.EmitAnyStloc( item );
Emittion.EmitSerializeValue(
emiter,
il0,
1,
typeof( MessagePackObject ),
null,
NilImplication.MemberDefault,
il1 =>
{
il0.EmitAnyLdloca( item );
il0.EmitGetProperty( Metadata._DictionaryEntry.Key );
il0.EmitUnbox_Any( typeof( MessagePackObject ) );
},
localHolder
);
Emittion.EmitSerializeValue(
emiter,
il0,
1,
typeof( MessagePackObject ),
null,
NilImplication.MemberDefault,
il1 =>
{
il0.EmitAnyLdloca( item );
il0.EmitGetProperty( Metadata._DictionaryEntry.Value );
il0.EmitUnbox_Any( typeof( MessagePackObject ) );
},
localHolder
);
}
}
);
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void CreateMapUnpack( SerializationContext context, Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
CreateMapUnpackFrom( context, targetType, emitter, traits );
CreateMapUnpackTo( targetType, emitter, traits );
}
private static void CreateMapUnpackFrom( SerializationContext context, Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
var il = emitter.GetUnpackFromMethodILGenerator();
var localHolder = new LocalVariableHolder( il );
var instanceType = targetType;
try
{
/*
* if (!unpacker.IsMapHeader)
* {
* throw SerializationExceptions.NewIsNotMapHeader();
* }
*
* TDictionary<TKey, TValue> dictionary = new ...;
* this.UnpackToCore(unpacker, dictionary);
* return dictionary;
*/
if ( targetType.IsInterface || targetType.IsAbstract )
{
instanceType = context.DefaultCollectionTypes.GetConcreteType( targetType );
if( instanceType == null )
{
il.EmitTypeOf( targetType );
il.EmitAnyCall( SerializationExceptions.NewNotSupportedBecauseCannotInstanciateAbstractTypeMethod );
il.EmitThrow();
return;
}
}
il.EmitAnyLdarg( 1 );
il.EmitGetProperty( Metadata._Unpacker.IsMapHeader );
var endIf = il.DefineLabel( "END_IF" );
il.EmitBrtrue_S( endIf );
il.EmitAnyCall( SerializationExceptions.NewIsNotMapHeaderMethod );
il.EmitThrow();
il.MarkLabel( endIf );
var collection = localHolder.GetDeserializingCollection( instanceType );
Emittion.EmitConstruction(
il,
collection,
il0 => Emittion.EmitGetUnpackerItemsCountAsInt32( il0, 1, localHolder )
);
EmitInvokeMapUnpackToHelper( targetType, emitter, traits, il, 1, il0 => il0.EmitAnyLdloc( collection ) );
il.EmitAnyLdloc( collection );
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void CreateMapUnpackTo( Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
var il = emitter.GetUnpackToMethodILGenerator();
try
{
EmitInvokeMapUnpackToHelper( targetType, emitter, traits, il, 1, il0 => il0.EmitAnyLdarg( 2 ) );
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void EmitInvokeMapUnpackToHelper( Type targetType, SerializerEmitter emitter, CollectionTraits traits, TracingILGenerator il, int unpackerArgumentIndex, Action<TracingILGenerator> loadCollectionEmitting )
{
il.EmitAnyLdarg( unpackerArgumentIndex );
if ( traits.ElementType.IsGenericType )
{
var keyType = traits.ElementType.GetGenericArguments()[ 0 ];
var valueType = traits.ElementType.GetGenericArguments()[ 1 ];
var keySerializerGetting = emitter.RegisterSerializer( keyType );
var valueSerializerGetting = emitter.RegisterSerializer( valueType );
keySerializerGetting( il, 0 );
valueSerializerGetting( il, 0 );
loadCollectionEmitting( il );
if ( targetType.IsValueType )
{
il.EmitBox( targetType );
}
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackMapTo_2.MakeGenericMethod( keyType, valueType ) );
}
else
{
loadCollectionEmitting( il );
if ( targetType.IsValueType )
{
il.EmitBox( targetType );
}
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackNonGenericMapTo );
}
}
#endregion -- Maps --
#region -- Miscs --
private static void EmitLoadTarget( Type targetType, TracingILGenerator il, int parameterIndex )
{
if ( targetType.IsValueType )
{
il.EmitAnyLdarga( parameterIndex );
}
else
{
il.EmitAnyLdarg( parameterIndex );
}
}
private static void EmitLoadTarget( Type targetType, TracingILGenerator il, LocalBuilder local )
{
if ( targetType.IsValueType )
{
il.EmitAnyLdloca( local );
}
else
{
il.EmitAnyLdloc( local );
}
}
#endregion -- Miscs --
}
}
| |
#pragma warning disable 1591
using DynabicBilling.RestAPI.RestInterfaces;
using DynabicBilling.RestApiDataContract;
using DynabicPlatform.Classes;
using DynabicPlatform.Exceptions;
namespace DynabicBilling
{
/// <summary>
/// Provides operations for creating, finding, updating, and deleting customers
/// </summary>
public class CustomerService : ICustomersService
{
private CommunicationLayer _service;
private readonly string _gatewayURL;
protected internal CustomerService(CommunicationLayer service)
{
_service = service;
_gatewayURL = service.Environment.GatewayURL + "/customers";
}
#region Customers
#region GET
/// <summary>
/// Get All Customers
/// </summary>
/// <param name="siteSubdomain">Name of the site</param>
/// <param name="format">Format of the Response</param>
/// <param name="pageNumber">The page number (Optional parameter, if is specified should be equal or greater than 1).</param>
/// <param name="pageSize">Size of the page (Optional parameter, if is specified should be equal or greater than 1).</param>
/// <returns>
/// Customers List
/// </returns>
public CustomersList GetAllCustomers(string siteSubdomain, string format = ContentFormat.XML, string pageNumber = null, string pageSize = null)
{
//return _service.Get<CustomersList>(string.Format("{0}/{1}.{2}", _gatewayURL, siteSubdomain, format));
return _service.Get<CustomersList>(string.Format("{0}/{1}.{2}?pageNumber={3}&pageSize={4}", _gatewayURL, siteSubdomain, format, pageNumber, pageSize));
}
/// <summary>
/// Get a Customer
/// </summary>
/// <param name="customerId">ID of the Customer</param>
/// <param name="format">Format of the Response</param>
/// <returns>CustomerResponseInfo</returns>
public CustomerResponse GetCustomer(string customerId, string format = ContentFormat.XML)
{
if (string.IsNullOrEmpty(customerId) || string.IsNullOrEmpty(format))
throw new NotFoundException();
return _service.Get<CustomerResponse>(string.Format("{0}/byid/{1}.{2}", _gatewayURL, customerId, format));
}
/// <summary>
/// Gets a Customer by reference Id
/// </summary>
/// <param name="siteSubdomain"> The subdomain of the Site that the Customer belongs to </param>
/// <param name="referenceId"> The Id of the Company whose Customer entry is to be retrieved </param>
/// <param name="format"> Format of the Response </param>
/// <returns> A CustomerResponse object corresponding to the requested Customer </returns>
public CustomerResponse GetCustomerByReferenceId(string siteSubdomain, string referenceId, string format = ContentFormat.XML)
{
return _service.Get<CustomerResponse>(string.Format("{0}/{1}/reference-id/{2}.{3}", _gatewayURL, siteSubdomain, referenceId, format));
}
#endregion GET
#region POST
/// <summary>
/// Create and Add a new Customer
/// </summary>
/// <param name="siteSubdomain"> The name of the Site to which the Customer will belong </param>
/// <param name="newCustomer">Reference to a new Customer to create</param>
/// <param name="format">Format of the passed Customer (XML or JSON)</param>
/// <returns>ID of the new Customer created, otherwise Error</returns>
public CustomerResponse AddCustomer(string siteSubdomain, CustomerRequest newCustomer, string format = ContentFormat.XML)
{
return _service.Post<CustomerRequest, CustomerResponse>(string.Format("{0}/{1}.{2}", _gatewayURL, siteSubdomain, format), newCustomer);
}
#endregion POST
#region PUT
/// <summary>
/// Updates info about a Customer. If The Customer's Address is not specified, one is created. Otherwise, it is updated
/// </summary>
/// <param name="updatedCustomer">Reference to a new info about the Customer</param>
/// <param name="customerId">ID of the Customer to Update</param>
/// <param name="format">Format of the Response</param>
/// <returns></returns>
public CustomerResponse UpdateCustomer(CustomerRequest updatedCustomer, string customerId, string format = ContentFormat.XML)
{
return _service.Put<CustomerRequest, CustomerResponse>(string.Format("{0}/{1}.{2}", _gatewayURL, customerId, format), updatedCustomer);
}
#endregion PUT
#region DELETE
/// <summary>
/// Deletes the customer.
/// </summary>
/// <param name="customerId">The customer id.</param>
public void DeleteCustomer(string customerId)
{
_service.Delete(string.Format("{0}/{1}", _gatewayURL, customerId));
}
#endregion DELETE
#endregion
#region CreditCards
#region GET
/// <summary>
/// Gets a Credit Card
/// </summary>
/// <param name="creditCardId"> The Id of the desired CreditCard </param>
/// <param name="format"> The desired response format (xml/json) </param>
/// <returns> A CreditCard object </returns>
public CreditCardResponse GetCreditCard(string creditCardId, string format = ContentFormat.XML)
{
return _service.Get<CreditCardResponse>(string.Format("{0}/credit-card/{1}.{2}", _gatewayURL, creditCardId, format));
}
/// <summary>
/// Gets all Credit Cards that correspond to a specific Customer
/// </summary>
/// <param name="customerId"> The Customer whose Credit Cards are to be retrieved </param>
/// <param name="format"> The desired response format (xml/json) </param>
/// <returns> A CreditCardsList object containing all credit cards that correspond to the specified Customer </returns>
public CreditCardsList GetCreditCards(string customerId, string format = ContentFormat.XML)
{
return _service.Get<CreditCardsList>(string.Format("{0}/{1}/credit-cards.{2}", _gatewayURL, customerId, format));
}
/// <summary>
/// Gets all Credit Cards that belong to a specific Customer with a specific ReferenceID
/// </summary>
/// <param name="customerReferenceId">Customer's ReferenceID</param>
/// <param name="format"> The desired response format (xml/json) </param>
/// <param name="siteSubdomain"> The site subdomain. </param>
/// <returns> A CreditCardsList object containing all credit cards that correspond to the specified Customer </returns>
public CreditCardsList GetCreditCardsByReferenceId(string siteSubdomain, string customerReferenceId, string format = ContentFormat.XML)
{
return _service.Get<CreditCardsList>(string.Format("{0}/{1}/reference-id/{2}/credit-cards.{3}", _gatewayURL, siteSubdomain, customerReferenceId, format));
}
/// <summary>
/// Gets first Credit Card that belongs to a specific Customer with given CustomerId
/// </summary>
/// <param name="customerId"> The Customer whose Credit Cards is to be retrieved </param>
/// <param name="format"> The format used for the data transfer (XML or JSON) </param>
/// <returns> A CreditCardResponse object containing first credit card that belongs to the specified Customer </returns>
public CreditCardResponse GetCustomersFirstCreditCard(string customerId, string format = ContentFormat.XML)
{
return _service.Get<CreditCardResponse>(string.Format("{0}/{1}/credit-card.{2}", _gatewayURL, customerId, format));
}
/// <summary>
/// Gets first Credit Card that belongs to a specific Customer with given ReferenceId
/// </summary>
/// <param name="customerReferenceId"> The Customer whose Credit Card is to be retrieved </param>
/// <param name="format"> The format used for the data transfer (XML or JSON) </param>
/// <param name="siteSubdomain"> The site subdomain. </param>
/// <returns> A CreditCardResponse object containing first credit card that belongs to the specified Customer </returns>
public CreditCardResponse GetFirstCreditCardForCustomerByReferenceId(string siteSubdomain, string customerReferenceId, string format = ContentFormat.XML)
{
return _service.Get<CreditCardResponse>(string.Format("{0}/{1}/reference-id/{2}/credit-card.{3}", _gatewayURL, siteSubdomain, customerReferenceId, format));
}
#endregion GET
#region POST
/// <summary>
/// Inserts a new Credit Card in the DB
/// </summary>
/// <param name="customerId"> The Id of the Customer the new CreditCard will belong to </param>
/// <param name="newCreditCard"> The CreditCard to be iserted </param>
/// <param name="format"> The desired data format (xml/json) </param>
/// <returns> A CreditCardResponse representing the newly-added CreditCard </returns>
public CreditCardResponse AddCreditCard(string customerId, CreditCardRequest newCreditCard, string format = ContentFormat.XML)
{
return _service.Post<CreditCardRequest, CreditCardResponse>(string.Format("{0}/{1}/credit-card.{2}", _gatewayURL, customerId, format), newCreditCard);
}
#endregion POST
#region PUT
/// <summary>
/// Updates a CreditCard in the DB
/// </summary>
/// <param name="customerId"> The Id of the Customer the CreditCard belongs to </param>
/// <param name="creditCardId"> ID of the CreditCard to update</param>
/// <param name="creditCard"> The CreditCard to be updated </param>
/// <param name="format"> The data format used (xml/json) </param>
/// <returns> A CreditCardResponse object representing the newly-updated CreditCard </returns>
public CreditCardResponse UpdateCreditCard(string customerId, string creditCardId, CreditCardRequest creditCard, string format = ContentFormat.XML)
{
return _service.Put<CreditCardRequest, CreditCardResponse>(string.Format("{0}/{1}/credit-card/{2}.{3}", _gatewayURL, customerId, creditCardId, format), creditCard);
}
/// <summary>
/// Updates a CreditCard in the DB
/// </summary>
/// <param name="siteSubdomanin">Subdomain of the Site where the Customer is registered</param>
/// <param name="customerReferenceId">The RefereceId of the Customer the CreditCard belongs to</param>
/// <param name="creditCardId"> ID of the CreditCard to update</param>
/// <param name="creditCard"> The CreditCard to be updated </param>
/// <param name="format"> The data format used (xml/json) </param>
/// <returns> A CreditCardResponse object representing the newly-updated CreditCard </returns>
public CreditCardResponse UpdateCreditCardByCustomerReferenceId(string siteSubdomanin, string customerReferenceId, string creditCardId, CreditCardRequest creditCard, string format = ContentFormat.XML)
{
return _service.Put<CreditCardRequest, CreditCardResponse>(string.Format("{0}/{1}/reference-id/{2}/credit-card/{3}.{4}", _gatewayURL, siteSubdomanin, customerReferenceId, creditCardId, format), creditCard);
}
#endregion PUT
#region DELETE
// TODO: later on
///// <summary>
///// Deletes all CreditCards that belong to a specific Customer
///// </summary>
///// <param name="customerId"> The Id of the Customer whose CreditCards are to be deleted </param>
///// <param name="format"> The data format used (xml/json) </param>
//void DeleteCreditCards(string customerId, string format= ContentFormat.XML);
/// <summary>
/// Deletes a CreditCard
/// </summary>
/// <param name="customerId"> The Id of the Customer the CreditCard belongs to </param>
/// <param name="creditCardId"> The Id of the CreditCard to be deleted </param>
public void DeleteCreditCard(string customerId, string creditCardId)
{
_service.Delete(string.Format("{0}/{1}/credit-card/{2}", _gatewayURL, customerId, creditCardId));
}
#endregion DELETE
#endregion
#region BillingAddresses
#region GET
/// <summary>
/// Gets all BillingAddresses for Customer
/// </summary>
/// <param name="customerId"> The Id of the Customer </param>
/// <param name="format"> The format of the Response </param>
/// <returns> An AddressList object containing all BillingAddresses for the specified Customer </returns>
public AddressList GetBillingAddresses(string customerId, string format = ContentFormat.XML)
{
return _service.Get<AddressList>(string.Format("{0}/{1}/billing-addresses.{2}", _gatewayURL, customerId, format));
}
/// <summary>
/// Gets a BillingAddress for a Customer
/// </summary>
/// <param name="customerId"> The Id of the Customer </param>
/// <param name="format"> The format of the Response </param>
/// <returns> An AddressResponse object containing the requested BillingAddress </returns>
public AddressResponse GetBillingAddress(string customerId, string format = ContentFormat.XML)
{
return _service.Get<AddressResponse>(string.Format("{0}/{1}/first-billing-address.{2}", _gatewayURL, customerId, format));
}
/// <summary>
/// Gets a BillingAddress for a Customer
/// </summary>
/// <param name="siteSubdomain">Subdomain of the Site where the Cusotmer is registered</param>
/// <param name="customerReferenceId">Customer's referenceId</param>
/// <param name="format"> The format used for the data transfer (XML or JSON) </param>
/// <returns> An AddressResponse object corresponding to the specified Id </returns>
public AddressResponse GetFirstBillingAddressForCustomerByReferenceId(string siteSubdomain, string customerReferenceId, string format = "xml")
{
return _service.Get<AddressResponse>(string.Format("{0}/{1}/reference-id/{2}/first-billing-address.{3}", _gatewayURL, siteSubdomain, customerReferenceId, format));
}
#endregion GET
#region POST
/// <summary>
/// Adds a new BillingAddress for a Customer
/// </summary>
/// <param name="customerId"> The Id of the Customer </param>
/// <param name="newBillingAddress"> The new BillingAddress </param>
/// <param name="format"> The format of the Response </param>
/// <returns> An AddressResponse object corresponding to the newly-inserted BillingAddress </returns>
public AddressResponse AddBillingAddress(string customerId, AddressRequest newBillingAddress, string format = ContentFormat.XML)
{
return _service.Post<AddressRequest, AddressResponse>(string.Format("{0}/{1}/billing-address.{2}", _gatewayURL, customerId, format), newBillingAddress);
}
#endregion POST
#region PUT
/// <summary>
/// Updates an existing BillingAddress for a Customer
/// </summary>
/// <param name="customerId"> The Id of the Customer </param>
/// <param name="billingAddressId"> The Id of the BillingAddress </param>
/// <param name="updatedBillingAddress"> The updated BillingAddress </param>
/// <param name="format"> The format of the Response </param>
/// <returns> An AddressResponse object corresponding to the newly-updated BillingAddress </returns>
public AddressResponse UpdateBillingAddress(string customerId, string billingAddressId, AddressRequest updatedBillingAddress, string format = ContentFormat.XML)
{
return _service.Put<AddressRequest, AddressResponse>(string.Format("{0}/{1}/billing-address/{2}.{3}", _gatewayURL, customerId, billingAddressId, format), updatedBillingAddress);
}
/// <summary>
/// Updates an existing BillingAddress for a Customer
/// </summary>
/// <param name="siteSubdomain"> Subdomain of the Site where the Customer is registered </param>
/// <param name="customerReferenceId"> The Customer's ReferenceID </param>
/// <param name="billingAddressId"> The Id of the BillingAddress </param>
/// <param name="updatedBillingAddress"> An AddressRequest object containing the updated BillingAddress record </param>
/// <param name="format"> The format used for the data transfer (XML or JSON) </param>
/// <returns> An AddressResponse object corresponding to the newly-updated BillingAddress </returns>
public AddressResponse UpdateBillingAddressByCustomerReferenceId(string siteSubdomain, string customerReferenceId, string billingAddressId, AddressRequest updatedBillingAddress, string format = "xml")
{
return _service.Put<AddressRequest, AddressResponse>(string.Format("{0}/{1}/reference-id/{2}/billing-address/{3}.{4}", _gatewayURL, siteSubdomain, customerReferenceId, billingAddressId, format), updatedBillingAddress);
}
#endregion PUT
#region DELETE
// TODO: later on!
///// <summary>
///// Deletes all BillingAddress for a Customer
///// </summary>
///// <param name="customerId"> The Id of the Customer </param>
///// <param name="format"> The format of the Response </param>
//void DeleteBillingAddresses(string customerId, string format= ContentFormat.XML);
/// <summary>
/// Deletes a BillingAddress for a Customer
/// </summary>
/// <param name="customerId"> The Id of the Customer </param>
/// <param name="billingAddressId"> The Id of the BillingAddress </param>
public void DeleteBillingAddress(string customerId, string billingAddressId)
{
_service.Delete(string.Format("{0}/{1}/billing-address/{2}", _gatewayURL, customerId, billingAddressId));
}
#endregion DELETE
#endregion
#region Countries
/// <summary>
/// Gets all Countries
/// </summary>
/// <returns>Countries collection</returns>
public CountryList GetCountries(string format = "xml")
{
return _service.Get<CountryList>(string.Format("{0}/country.{1}", _gatewayURL, format));
}
/// <summary>
/// Gets a Country by Id
/// </summary>
/// <param name="countryId"> The Id of the Country </param>
/// <param name="format"> Data transfer format </param>
/// <returns>Country</returns>
public Country GetCountry(string countryId, string format = "xml")
{
return _service.Get<Country>(string.Format("{0}/country/by-id/{1}.{2}", _gatewayURL, countryId, format));
}
/// <summary>
/// Gets a Country by ISO code (either 2 or 3 letter codes)
/// </summary>
/// <param name="countryIsoCode"> The Country ISO code, either 2 or 3 letters </param>
/// <param name="format"> Data transfer format </param>
/// <returns>Country</returns>
public Country GetCountryByCode(string countryIsoCode, string format = "xml")
{
return _service.Get<Country>(string.Format("{0}/country/by-code/{1}.{2}", _gatewayURL, countryIsoCode, format));
}
/// <summary>
/// Gets a Contry by Name
/// </summary>
/// <param name="countryName"> The Name of the Country </param>
/// <param name="format"> Data transfer format </param>
/// <returns> A Country object corresponding to the requested Country </returns>
public Country GetCountryByName(string countryName, string format = "xml")
{
return _service.Get<Country>(string.Format("{0}/country/by-name/{1}.{2}", _gatewayURL, countryName, format));
}
#endregion Countries
#region StateProvince
/// <summary>
/// Gets all StatesProvinces by Country Id
/// </summary>
/// <param name="countryId"> The Country Id </param>
/// <param name="format"> Data transfer format </param>
/// <returns>StatesProvinces collection</returns>
public StateProvinceList GetStateProvinces(string countryId, string format = "xml")
{
return _service.Get<StateProvinceList>(string.Format("{0}/stateprovince/by-country-id/{1}.{2}", _gatewayURL, countryId, format));
}
/// <summary>
/// Gets all StatesProvinces by Country ISO code (2 letters)
/// </summary>
/// <param name="countryTwoLetterISOCode"> The two-letter ISO country code </param>
/// <param name="format"> Data transfer format </param>
/// <returns>StatesProvinces collection</returns>
public StateProvinceList GetStateProvincesByCountryCode(string countryTwoLetterISOCode, string format = "xml")
{
return _service.Get<StateProvinceList>(string.Format("{0}/stateprovince/by-country-code/{1}.{2}", _gatewayURL, countryTwoLetterISOCode, format));
}
/// <summary>
/// Gets a StateProvince by Id
/// </summary>
/// <param name="stateProvinceId"> The Id of the StateProvince </param>
/// <param name="format"> Data transfer format </param>
/// <returns>StateProvince</returns>
public StateProvince GetStateProvince(string stateProvinceId, string format = "xml")
{
return _service.Get<StateProvince>(string.Format("{0}/stateprovince/by-id/{1}.{2}", _gatewayURL, stateProvinceId, format));
}
/// <summary>
/// Gets a StateProvince by Name
/// </summary>
/// <param name="stateProvinceName"> The Name of the StateProvince </param>
/// <param name="format"> Data transfer format </param>
/// <returns> A StateProvince object corresponding to the specified Name </returns>
public StateProvince GetStateProvinceByName(string stateProvinceName, string format = "xml")
{
return _service.Get<StateProvince>(string.Format("{0}/stateprovince/by-name/{1}.{2}", _gatewayURL, stateProvinceName, format));
}
#endregion StateProvince
#region Currency
/// <summary>
/// Gets all Currencies
/// </summary>
/// <param name="format"> Data transfer format (XML/JSON) </param>
/// <returns>CurrencyList</returns>
public CurrencyList GetCurrencies(string format = "xml")
{
return _service.Get<CurrencyList>(string.Format("{0}/currency.{1}", _gatewayURL, format));
}
/// <summary>
/// Gets a Currency by Id
/// </summary>
/// <param name="currencyId"> The Id of the Currency </param>
/// <param name="format"> Data transfer format (XML/JSON) </param>
/// <returns>Currency</returns>
public Currency GetCurrency(string currencyId, string format = "xml")
{
return _service.Get<Currency>(string.Format("{0}/currency/by-id/{1}.{2}", _gatewayURL, currencyId, format));
}
/// <summary>
/// Gets a Currency by Code
/// </summary>
/// <param name="currencyCode"> The Currency code (e.g. USD, EUR) </param>
/// <param name="format"> Data transfer format (XML/JSON) </param>
/// <returns>Currency</returns>
public Currency GetCurrencyByCode(string currencyCode, string format = "xml")
{
return _service.Get<Currency>(string.Format("{0}/currency/by-code/{1}.{2}", _gatewayURL, currencyCode, format));
}
/// <summary>
/// Gets the currency for a Country
/// </summary>
/// <param name="countryThreeISOCode"> The 3-letter Country code </param>
/// <param name="format"> Data transfer format (XML/JSON) </param>
/// <returns>Currency</returns>
public Currency GetCurrencyForCountryThreeIsoCode(string countryThreeISOCode, string format = "xml")
{
return _service.Get<Currency>(string.Format("{0}/currency/by-country-code/{1}.{2}", _gatewayURL, countryThreeISOCode, format));
}
#endregion Currency
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using Internal.Runtime.CompilerServices;
using REG_TZI_FORMAT = Interop.Kernel32.REG_TZI_FORMAT;
using TIME_ZONE_INFORMATION = Interop.Kernel32.TIME_ZONE_INFORMATION;
using TIME_DYNAMIC_ZONE_INFORMATION = Interop.Kernel32.TIME_DYNAMIC_ZONE_INFORMATION;
namespace System
{
public sealed partial class TimeZoneInfo
{
// registry constants for the 'Time Zones' hive
//
private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";
private const string DisplayValue = "Display";
private const string DaylightValue = "Dlt";
private const string StandardValue = "Std";
private const string MuiDisplayValue = "MUI_Display";
private const string MuiDaylightValue = "MUI_Dlt";
private const string MuiStandardValue = "MUI_Std";
private const string TimeZoneInfoValue = "TZI";
private const string FirstEntryValue = "FirstEntry";
private const string LastEntryValue = "LastEntry";
private const int MaxKeyLength = 255;
#pragma warning disable 0420
private sealed partial class CachedData
{
private static TimeZoneInfo GetCurrentOneYearLocal()
{
// load the data from the OS
TIME_ZONE_INFORMATION timeZoneInformation;
uint result = Interop.Kernel32.GetTimeZoneInformation(out timeZoneInformation);
return result == Interop.Kernel32.TIME_ZONE_ID_INVALID ?
CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) :
GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false);
}
private volatile OffsetAndRule _oneYearLocalFromUtc;
public OffsetAndRule GetOneYearLocalFromUtc(int year)
{
OffsetAndRule oneYearLocFromUtc = _oneYearLocalFromUtc;
if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year)
{
TimeZoneInfo currentYear = GetCurrentOneYearLocal();
AdjustmentRule rule = currentYear._adjustmentRules == null ? null : currentYear._adjustmentRules[0];
oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);
_oneYearLocalFromUtc = oneYearLocFromUtc;
}
return oneYearLocFromUtc;
}
}
#pragma warning restore 0420
private sealed class OffsetAndRule
{
public readonly int Year;
public readonly TimeSpan Offset;
public readonly AdjustmentRule Rule;
public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule)
{
Year = year;
Offset = offset;
Rule = rule;
}
}
/// <summary>
/// Returns a cloned array of AdjustmentRule objects
/// </summary>
public AdjustmentRule[] GetAdjustmentRules()
{
if (_adjustmentRules == null)
{
return Array.Empty<AdjustmentRule>();
}
return (AdjustmentRule[])_adjustmentRules.Clone();
}
private static void PopulateAllSystemTimeZones(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
{
if (reg != null)
{
foreach (string keyName in reg.GetSubKeyNames())
{
TimeZoneInfo value;
Exception ex;
TryGetTimeZone(keyName, false, out value, out ex, cachedData); // populate the cache
}
}
}
}
private TimeZoneInfo(in TIME_ZONE_INFORMATION zone, bool dstDisabled)
{
string standardName = zone.GetStandardName();
if (standardName.Length == 0)
{
_id = LocalId; // the ID must contain at least 1 character - initialize _id to "Local"
}
else
{
_id = standardName;
}
_baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0);
if (!dstDisabled)
{
// only create the adjustment rule if DST is enabled
REG_TZI_FORMAT regZone = new REG_TZI_FORMAT(zone);
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias);
if (rule != null)
{
_adjustmentRules = new[] { rule };
}
}
ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
_displayName = standardName;
_standardDisplayName = standardName;
_daylightDisplayName = zone.GetDaylightName();
}
/// <summary>
/// Helper function to check if the current TimeZoneInformation struct does not support DST.
/// This check returns true when the DaylightDate == StandardDate.
/// This check is only meant to be used for "Local".
/// </summary>
private static bool CheckDaylightSavingTimeNotSupported(in TIME_ZONE_INFORMATION timeZone) =>
timeZone.DaylightDate.Equals(timeZone.StandardDate);
/// <summary>
/// Converts a REG_TZI_FORMAT struct to an AdjustmentRule.
/// </summary>
private static AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset)
{
bool supportsDst = timeZoneInformation.StandardDate.Month != 0;
if (!supportsDst)
{
if (timeZoneInformation.Bias == defaultBaseUtcOffset)
{
// this rule will not contain any information to be used to adjust dates. just ignore it
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startDate,
endDate,
TimeSpan.Zero, // no daylight saving transition
TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),
TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),
new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule
noDaylightTransitions: false);
}
//
// Create an AdjustmentRule with TransitionTime objects
//
TransitionTime daylightTransitionStart;
if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true))
{
return null;
}
TransitionTime daylightTransitionEnd;
if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false))
{
return null;
}
if (daylightTransitionStart.Equals(daylightTransitionEnd))
{
// this happens when the time zone does support DST but the OS has DST disabled
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startDate,
endDate,
new TimeSpan(0, -timeZoneInformation.DaylightBias, 0),
daylightTransitionStart,
daylightTransitionEnd,
new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),
noDaylightTransitions: false);
}
/// <summary>
/// Helper function that searches the registry for a time zone entry
/// that matches the TimeZoneInformation struct.
/// </summary>
private static string FindIdFromTimeZoneInformation(in TIME_ZONE_INFORMATION timeZone, out bool dstDisabled)
{
dstDisabled = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
{
if (key == null)
{
return null;
}
foreach (string keyName in key.GetSubKeyNames())
{
if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))
{
return keyName;
}
}
}
return null;
}
/// <summary>
/// Helper function for retrieving the local system time zone.
/// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
/// Assumes cachedData lock is taken.
/// </summary>
/// <returns>A new TimeZoneInfo instance.</returns>
private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
//
// Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"
//
var dynamicTimeZoneInformation = new TIME_DYNAMIC_ZONE_INFORMATION();
// call kernel32!GetDynamicTimeZoneInformation...
uint result = Interop.Kernel32.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);
if (result == Interop.Kernel32.TIME_ZONE_ID_INVALID)
{
// return a dummy entry
return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
}
// check to see if we can use the key name returned from the API call
string dynamicTimeZoneKeyName = dynamicTimeZoneInformation.GetTimeZoneKeyName();
if (dynamicTimeZoneKeyName.Length != 0)
{
TimeZoneInfo zone;
Exception ex;
if (TryGetTimeZone(dynamicTimeZoneKeyName, dynamicTimeZoneInformation.DynamicDaylightTimeDisabled != 0, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
{
// successfully loaded the time zone from the registry
return zone;
}
}
var timeZoneInformation = new TIME_ZONE_INFORMATION(dynamicTimeZoneInformation);
// the key name was not returned or it pointed to a bogus entry - search for the entry ourselves
string id = FindIdFromTimeZoneInformation(timeZoneInformation, out bool dstDisabled);
if (id != null)
{
TimeZoneInfo zone;
Exception ex;
if (TryGetTimeZone(id, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
{
// successfully loaded the time zone from the registry
return zone;
}
}
// We could not find the data in the registry. Fall back to using
// the data from the Win32 API
return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
}
/// <summary>
/// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of
/// try/catch logic for handling the TimeZoneInfo private constructor that takes
/// a TIME_ZONE_INFORMATION structure.
/// </summary>
private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(in TIME_ZONE_INFORMATION timeZoneInformation, bool dstDisabled)
{
// first try to create the TimeZoneInfo with the original 'dstDisabled' flag
try
{
return new TimeZoneInfo(timeZoneInformation, dstDisabled);
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
// if 'dstDisabled' was false then try passing in 'true' as a last ditch effort
if (!dstDisabled)
{
try
{
return new TimeZoneInfo(timeZoneInformation, dstDisabled: true);
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
}
// the data returned from Windows is completely bogus; return a dummy entry
return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
}
/// <summary>
/// Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
/// This function wraps the logic necessary to keep the private
/// SystemTimeZones cache in working order
///
/// This function will either return a valid TimeZoneInfo instance or
/// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
/// </summary>
public static TimeZoneInfo FindSystemTimeZoneById(string id)
{
// Special case for Utc as it will not exist in the dictionary with the rest
// of the system time zones. There is no need to do this check for Local.Id
// since Local is a real time zone that exists in the dictionary cache
if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
{
return Utc;
}
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains('\0'))
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
}
TimeZoneInfo value;
Exception e;
TimeZoneInfoResult result;
CachedData cachedData = s_cachedData;
lock (cachedData)
{
result = TryGetTimeZone(id, false, out value, out e, cachedData);
}
if (result == TimeZoneInfoResult.Success)
{
return value;
}
else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
{
throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e);
}
else if (result == TimeZoneInfoResult.SecurityException)
{
throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e);
}
else
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
}
}
// DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
{
bool isDaylightSavings = false;
isAmbiguousLocalDst = false;
TimeSpan baseOffset;
int timeYear = time.Year;
OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
baseOffset = match.Offset;
if (match.Rule != null)
{
baseOffset = baseOffset + match.Rule.BaseUtcOffsetDelta;
if (match.Rule.HasDaylightSaving)
{
isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, null, out isAmbiguousLocalDst, Local);
baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
}
}
return baseOffset;
}
/// <summary>
/// Converts a REG_TZI_FORMAT struct to a TransitionTime
/// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
/// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
/// </summary>
private static bool TransitionTimeFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, out TransitionTime transitionTime, bool readStartDate)
{
//
// SYSTEMTIME -
//
// If the time zone does not support daylight saving time or if the caller needs
// to disable daylight saving time, the wMonth member in the SYSTEMTIME structure
// must be zero. If this date is specified, the DaylightDate value in the
// TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system
// assumes the time zone data is invalid and no changes will be applied.
//
bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
if (!supportsDst)
{
transitionTime = default(TransitionTime);
return false;
}
//
// SYSTEMTIME -
//
// * FixedDateRule -
// If the Year member is not zero, the transition date is absolute; it will only occur one time
//
// * FloatingDateRule -
// To select the correct day in the month, set the Year member to zero, the Hour and Minute
// members to the transition time, the DayOfWeek member to the appropriate weekday, and the
// Day member to indicate the occurence of the day of the week within the month (first through fifth).
//
// Using this notation, specify the 2:00a.m. on the first Sunday in April as follows:
// Hour = 2,
// Month = 4,
// DayOfWeek = 0,
// Day = 1.
//
// Specify 2:00a.m. on the last Thursday in October as follows:
// Hour = 2,
// Month = 10,
// DayOfWeek = 4,
// Day = 5.
//
if (readStartDate)
{
//
// read the "daylightTransitionStart"
//
if (timeZoneInformation.DaylightDate.Year == 0)
{
transitionTime = TransitionTime.CreateFloatingDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds),
timeZoneInformation.DaylightDate.Month,
timeZoneInformation.DaylightDate.Day, /* Week 1-5 */
(DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek);
}
else
{
transitionTime = TransitionTime.CreateFixedDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds),
timeZoneInformation.DaylightDate.Month,
timeZoneInformation.DaylightDate.Day);
}
}
else
{
//
// read the "daylightTransitionEnd"
//
if (timeZoneInformation.StandardDate.Year == 0)
{
transitionTime = TransitionTime.CreateFloatingDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.StandardDate.Hour,
timeZoneInformation.StandardDate.Minute,
timeZoneInformation.StandardDate.Second,
timeZoneInformation.StandardDate.Milliseconds),
timeZoneInformation.StandardDate.Month,
timeZoneInformation.StandardDate.Day, /* Week 1-5 */
(DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek);
}
else
{
transitionTime = TransitionTime.CreateFixedDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.StandardDate.Hour,
timeZoneInformation.StandardDate.Minute,
timeZoneInformation.StandardDate.Second,
timeZoneInformation.StandardDate.Milliseconds),
timeZoneInformation.StandardDate.Month,
timeZoneInformation.StandardDate.Day);
}
}
return true;
}
/// <summary>
/// Helper function that takes:
/// 1. A string representing a <time_zone_name> registry key name.
/// 2. A REG_TZI_FORMAT struct containing the default rule.
/// 3. An AdjustmentRule[] out-parameter.
/// </summary>
private static bool TryCreateAdjustmentRules(string id, in REG_TZI_FORMAT defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset)
{
rules = null;
e = null;
try
{
// Optional, Dynamic Time Zone Registry Data
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// HKLM
// Software
// Microsoft
// Windows NT
// CurrentVersion
// Time Zones
// <time_zone_name>
// Dynamic DST
// * "FirstEntry" REG_DWORD "1980"
// First year in the table. If the current year is less than this value,
// this entry will be used for DST boundaries
// * "LastEntry" REG_DWORD "2038"
// Last year in the table. If the current year is greater than this value,
// this entry will be used for DST boundaries"
// * "<year1>" REG_BINARY REG_TZI_FORMAT
// * "<year2>" REG_BINARY REG_TZI_FORMAT
// * "<year3>" REG_BINARY REG_TZI_FORMAT
//
using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false))
{
if (dynamicKey == null)
{
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(
defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
if (rule != null)
{
rules = new[] { rule };
}
return true;
}
//
// loop over all of the "<time_zone_name>\Dynamic DST" hive entries
//
// read FirstEntry {MinValue - (year1, 12, 31)}
// read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}
// read LastEntry {(yearN, 1, 1) - MaxValue }
// read the FirstEntry and LastEntry key values (ex: "1980", "2038")
int first = (int)dynamicKey.GetValue(FirstEntryValue, -1, RegistryValueOptions.None);
int last = (int)dynamicKey.GetValue(LastEntryValue, -1, RegistryValueOptions.None);
if (first == -1 || last == -1 || first > last)
{
return false;
}
// read the first year entry
REG_TZI_FORMAT dtzi;
if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, first.ToString(CultureInfo.InvariantCulture), out dtzi))
{
return false;
}
if (first == last)
{
// there is just 1 dynamic rule for this time zone.
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
if (rule != null)
{
rules = new[] { rule };
}
return true;
}
List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
// there are more than 1 dynamic rules for this time zone.
AdjustmentRule firstRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
DateTime.MinValue.Date, // MinValue
new DateTime(first, 12, 31), // December 31, <FirstYear>
defaultBaseUtcOffset);
if (firstRule != null)
{
rulesList.Add(firstRule);
}
// read the middle year entries
for (int i = first + 1; i < last; i++)
{
if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, i.ToString(CultureInfo.InvariantCulture), out dtzi))
{
return false;
}
AdjustmentRule middleRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
new DateTime(i, 1, 1), // January 01, <Year>
new DateTime(i, 12, 31), // December 31, <Year>
defaultBaseUtcOffset);
if (middleRule != null)
{
rulesList.Add(middleRule);
}
}
// read the last year entry
if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, last.ToString(CultureInfo.InvariantCulture), out dtzi))
{
return false;
}
AdjustmentRule lastRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
new DateTime(last, 1, 1), // January 01, <LastYear>
DateTime.MaxValue.Date, // MaxValue
defaultBaseUtcOffset);
if (lastRule != null)
{
rulesList.Add(lastRule);
}
// convert the List to an AdjustmentRule array
if (rulesList.Count != 0)
{
rules = rulesList.ToArray();
}
} // end of: using (RegistryKey dynamicKey...
}
catch (InvalidCastException ex)
{
// one of the RegistryKey.GetValue calls could not be cast to an expected value type
e = ex;
return false;
}
catch (ArgumentOutOfRangeException ex)
{
e = ex;
return false;
}
catch (ArgumentException ex)
{
e = ex;
return false;
}
return true;
}
private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi)
{
byte[] regValue = key.GetValue(name, null, RegistryValueOptions.None) as byte[];
if (regValue == null || regValue.Length != sizeof(REG_TZI_FORMAT))
{
dtzi = default;
return false;
}
fixed (byte * pBytes = ®Value[0])
dtzi = *(REG_TZI_FORMAT *)pBytes;
return true;
}
/// <summary>
/// Helper function that compares the StandardBias and StandardDate portion a
/// TimeZoneInformation struct to a time zone registry entry.
/// </summary>
private static bool TryCompareStandardDate(in TIME_ZONE_INFORMATION timeZone, in REG_TZI_FORMAT registryTimeZoneInfo) =>
timeZone.Bias == registryTimeZoneInfo.Bias &&
timeZone.StandardBias == registryTimeZoneInfo.StandardBias &&
timeZone.StandardDate.Equals(registryTimeZoneInfo.StandardDate);
/// <summary>
/// Helper function that compares a TimeZoneInformation struct to a time zone registry entry.
/// </summary>
private static bool TryCompareTimeZoneInformationToRegistry(in TIME_ZONE_INFORMATION timeZone, string id, out bool dstDisabled)
{
dstDisabled = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
{
if (key == null)
{
return false;
}
REG_TZI_FORMAT registryTimeZoneInfo;
if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out registryTimeZoneInfo))
{
return false;
}
//
// first compare the bias and standard date information between the data from the Win32 API
// and the data from the registry...
//
bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
if (!result)
{
return false;
}
result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) ||
//
// since Daylight Saving Time is not "disabled", do a straight comparision between
// the Win32 API data and the registry data ...
//
(timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias &&
timeZone.DaylightDate.Equals(registryTimeZoneInfo.DaylightDate));
// Finally compare the "StandardName" string value...
//
// we do not compare "DaylightName" as this TimeZoneInformation field may contain
// either "StandardName" or "DaylightName" depending on the time of year and current machine settings
//
if (result)
{
string registryStandardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
result = string.Equals(registryStandardName, timeZone.GetStandardName(), StringComparison.Ordinal);
}
return result;
}
}
/// <summary>
/// Helper function for retrieving a localized string resource via MUI.
/// The function expects a string in the form: "@resource.dll, -123"
///
/// "resource.dll" is a language-neutral portable executable (LNPE) file in
/// the %windir%\system32 directory. The OS is queried to find the best-fit
/// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui).
/// If a localized resource file exists, we LoadString resource ID "123" and
/// return it to our caller.
/// </summary>
private static string TryGetLocalizedNameByMuiNativeResource(string resource)
{
if (string.IsNullOrEmpty(resource))
{
return string.Empty;
}
// parse "@tzres.dll, -100"
//
// filePath = "C:\Windows\System32\tzres.dll"
// resourceId = -100
//
string[] resources = resource.Split(',');
if (resources.Length != 2)
{
return string.Empty;
}
string filePath;
int resourceId;
// get the path to Windows\System32
string system32 = Environment.SystemDirectory;
// trim the string "@tzres.dll" => "tzres.dll"
string tzresDll = resources[0].TrimStart('@');
try
{
filePath = Path.Combine(system32, tzresDll);
}
catch (ArgumentException)
{
// there were probably illegal characters in the path
return string.Empty;
}
if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId))
{
return string.Empty;
}
resourceId = -resourceId;
try
{
StringBuilder fileMuiPath = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH);
fileMuiPath.Length = Interop.Kernel32.MAX_PATH;
int fileMuiPathLength = Interop.Kernel32.MAX_PATH;
int languageLength = 0;
long enumerator = 0;
bool succeeded = Interop.Kernel32.GetFileMUIPath(
Interop.Kernel32.MUI_PREFERRED_UI_LANGUAGES,
filePath, null /* language */, ref languageLength,
fileMuiPath, ref fileMuiPathLength, ref enumerator);
if (!succeeded)
{
StringBuilderCache.Release(fileMuiPath);
return string.Empty;
}
return TryGetLocalizedNameByNativeResource(StringBuilderCache.GetStringAndRelease(fileMuiPath), resourceId);
}
catch (EntryPointNotFoundException)
{
return string.Empty;
}
}
/// <summary>
/// Helper function for retrieving a localized string resource via a native resource DLL.
/// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"
///
/// "resource.dll" is a language-specific resource DLL.
/// If the localized resource DLL exists, LoadString(resource) is returned.
/// </summary>
private static string TryGetLocalizedNameByNativeResource(string filePath, int resource)
{
using (SafeLibraryHandle handle =
Interop.Kernel32.LoadLibraryEx(filePath, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE))
{
if (!handle.IsInvalid)
{
const int LoadStringMaxLength = 500;
StringBuilder localizedResource = StringBuilderCache.Acquire(LoadStringMaxLength);
int result = Interop.User32.LoadString(handle, resource,
localizedResource, LoadStringMaxLength);
if (result != 0)
{
return StringBuilderCache.GetStringAndRelease(localizedResource);
}
}
}
return string.Empty;
}
/// <summary>
/// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry
///
/// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI
/// resource dll(s). When the keys do not exist, the function falls back to reading from the standard
/// key-values
/// </summary>
private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string displayName, out string standardName, out string daylightName)
{
displayName = string.Empty;
standardName = string.Empty;
daylightName = string.Empty;
// read the MUI_ registry keys
string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty, RegistryValueOptions.None) as string;
string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty, RegistryValueOptions.None) as string;
string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty, RegistryValueOptions.None) as string;
// try to load the strings from the native resource DLL(s)
if (!string.IsNullOrEmpty(displayNameMuiResource))
{
displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource);
}
if (!string.IsNullOrEmpty(standardNameMuiResource))
{
standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource);
}
if (!string.IsNullOrEmpty(daylightNameMuiResource))
{
daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource);
}
// fallback to using the standard registry keys
if (string.IsNullOrEmpty(displayName))
{
displayName = key.GetValue(DisplayValue, string.Empty, RegistryValueOptions.None) as string;
}
if (string.IsNullOrEmpty(standardName))
{
standardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
}
if (string.IsNullOrEmpty(daylightName))
{
daylightName = key.GetValue(DaylightValue, string.Empty, RegistryValueOptions.None) as string;
}
}
/// <summary>
/// Helper function that takes a string representing a <time_zone_name> registry key name
/// and returns a TimeZoneInfo instance.
/// </summary>
private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e)
{
e = null;
// Standard Time Zone Registry Data
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// HKLM
// Software
// Microsoft
// Windows NT
// CurrentVersion
// Time Zones
// <time_zone_name>
// * STD, REG_SZ "Standard Time Name"
// (For OS installed zones, this will always be English)
// * MUI_STD, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for Standard Time,
// add "%windir%\system32\" after "@"
// * DLT, REG_SZ "Daylight Time Name"
// (For OS installed zones, this will always be English)
// * MUI_DLT, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for Daylight Time,
// add "%windir%\system32\" after "@"
// * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..."
// * MUI_Display, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for the Display,
// add "%windir%\system32\" after "@"
// * TZI, REG_BINARY REG_TZI_FORMAT
//
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
{
if (key == null)
{
value = null;
return TimeZoneInfoResult.TimeZoneNotFoundException;
}
REG_TZI_FORMAT defaultTimeZoneInformation;
if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out defaultTimeZoneInformation))
{
// the registry value could not be cast to a byte array
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
AdjustmentRule[] adjustmentRules;
if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias))
{
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
GetLocalizedNamesByRegistryKey(key, out string displayName, out string standardName, out string daylightName);
try
{
value = new TimeZoneInfo(
id,
new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0),
displayName,
standardName,
daylightName,
adjustmentRules,
disableDaylightSavingTime: false);
return TimeZoneInfoResult.Success;
}
catch (ArgumentException ex)
{
// TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
value = null;
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
catch (InvalidTimeZoneException ex)
{
// TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
value = null;
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using WixSharp.CommonTasks;
using Xunit;
namespace WixSharp.Test
{
public class IssueFixesTest
{
[Fact]
[Description("Issue #67")]
public void Fix_Issue_67()
{
var project = new Project("MyProduct",
new Dir("%ProgramFiles%"));
project.LicenceFile = "license.rtf";
var file = project.BuildWxs();
}
[Fact]
public void ListConsts()
{
var list = Compiler.GetMappedWixConstants(true);
}
[Fact]
[Description("Issue #60")]
public void Fix_Issue_60()
{
var project = new Project("MyProduct",
new Dir("%ProgramFiles%",
new File("abc.txt", new FilePermission("Guest", GenericPermission.All))));
project.AddAction(new WixQuietExecAction("cmd.exe", "/c \"echo abc\""));
var batchFile = project.BuildMsiCmd();
string cmd = System.IO.File.ReadAllLines(batchFile).First();
int firstPos = cmd.IndexOf("WixUtilExtension.dll");
int lastPos = cmd.LastIndexOf("WixUtilExtension.dll");
Assert.Equal(firstPos, lastPos);
}
[Fact]
[Description("Issue #37")]
public void Should_Preserve_ConstantsInAttrDefs()
{
var project =
new Project("My Product",
new Dir(@"%ProgramFiles%\MyCompany",
new Dir("MyWebApp",
new File(@"MyWebApp\Default.aspx",
new IISVirtualDir
{
Name = "MyWebApp",
AppName = "Test",
WebSite = new WebSite("[IIS_SITE_NAME]", "[IIS_SITE_ADDRESS]:[IIS_SITE_PORT]"),
WebAppPool = new WebAppPool("MyWebApp", "Identity=applicationPoolIdentity")
}))));
string wxs = project.BuildWxs();
var address = XDocument.Load(wxs)
.FindSingle("WebAddress");
Assert.Equal("[IIS_SITE_ADDRESS]", address.ReadAttribute("IP"));
Assert.Equal("[IIS_SITE_PORT]", address.ReadAttribute("Port"));
}
[Fact]
[Description("Discussions #642332")]
public void Should_Process_DirAttributes()
{
Dir dir1, dir2;
var project =
new Project("My Product",
dir1 = new Dir(@"%ProgramFiles%\MyCompany",
dir2 = new Dir("MyWebApp", new File("Default.aspx"))));
dir1.AttributesDefinition = "DiskId=1";
dir2.AttributesDefinition = "DiskId=2";
string wxs = project.BuildWxs();
var dirs = XDocument.Load(wxs)
.FindAll("Directory")
.Where(x => x.HasAttribute("DiskId"))
.ToArray();
Assert.Equal(2, dirs.Count());
Assert.True(dirs[0].HasAttribute("Name", "MyCompany"));
Assert.True(dirs[0].HasAttribute("DiskId", "1"));
Assert.True(dirs[1].HasAttribute("Name", "MyWebApp"));
Assert.True(dirs[1].HasAttribute("DiskId", "2"));
}
[Fact]
[Description("Discussions #642332")]
public void Should_Process_DirAttributes_2()
{
var project =
new Project("My Product",
new Dir(@"%ProgramFiles%\MyCompany",
new Dir("MyWebApp", new File("Default.aspx"))));
project.AddEnvironmentVariable(new EnvironmentVariable("someVar", "Some value") { AttributesDefinition = "DiskId=2" });
string wxs = project.BuildWxs();
var doc = XDocument.Load(wxs);
}
[Fact]
[Description("Discussions #642263")]
public void Should_CanInject_UserProfileNoiseAutomatically()
{
var project = new Project("TestProject",
new Dir(@"%ProgramFiles%\My Company\My Product",
new File(@"Files\notepad.exe")),
new Dir(@"%CommonAppDataFolder%\Test Project",
new File(@"Files\TextFile.txt")),
new Dir(@"%PersonalFolder%\Test Project",
new File(@"Files\Baskets.bbd")));
string wxs = project.BuildWxs();
var doc = XDocument.Load(wxs);
}
[Fact]
[Description("Discussions #642263")]
public void Should_CanInject_UserProfileNoise()
{
var project = new Project("TestProject",
new Dir(@"%ProgramFiles%\My Company\My Product",
new File(@"Files\notepad.exe")),
new Dir(@"%CommonAppDataFolder%\Test Project",
new File(@"Files\TextFile.txt")),
new Dir(@"%PersonalFolder%\Test Project",
new File(@"Files\Baskets.bbd")));
project.WixSourceGenerated += xml =>
{
var dir = xml.FindAll("Directory")
.Where(x => x.HasAttribute("Name", "PersonalFolder"))
//.Where(x => x.HasAttribute("Name", v => v == "PersonalFolder"))
.SelectMany(x => x.FindAll("Component"))
.ForEach(comp => comp.InsertUserProfileRegValue()
.InsertUserProfileRemoveFolder());
};
string wxs = project.BuildWxs();
var doc = XDocument.Load(wxs);
}
[Fact]
[Description("Discussions #642263")]
public void Should_Inject_RemoveFolder()
{
var project = new Project("TestProject",
new Dir(@"%ProgramFiles%\My Company\My Product",
new File(@"Files\notepad.exe")),
new Dir(@"%CommonAppDataFolder%\Test Project",
new File(@"Files\TextFile.txt")),
new Dir(@"%PersonalFolder%\Test Project",
new File(@"Files\Baskets.bbd")));
project.WixSourceGenerated += Project_WixSourceGenerated;
string wxs = project.BuildWxs();
var doc = XDocument.Load(wxs);
}
void Project_WixSourceGenerated(XDocument document)
{
var dir = document.FindAll("Directory")
.Where(x => x.HasAttribute("Name", "Test Project") && x.Parent.HasAttribute("Name", "PersonalFolder"))
.First();
dir.FindFirst("Component")
.AddElement("RemoveFolder", "On=uninstall; Id=" + dir.Attribute("Id").Value)
.AddElement("RegistryValue", @"Root=HKCU; Key=Software\[Manufacturer]\[ProductName]; Type=string; Value=; KeyPath=yes");
}
[Fact]
[Description("Post 576142#post1428674")]
public void Should_Handle_NonstandardProductVersions()
{
Project project = new Project("MyProduct",
new Dir(@"%ProgramFiles%\My Company\My Product",
new File(this.GetType().Assembly.Location)
)
);
project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b");
project.Version = new Version("2014.1.26.0");
Compiler.BuildMsi(project);
}
[Fact]
[Description("Issue #39")]
public void Should_Handle_EmptyFeatures()
{
var binaries = new Feature("MyApp Binaries");
var docs = new Feature("MyApp Documentation");
var docs_01 = new Feature("Documentation 01");
var docs_02 = new Feature("Documentation 02");
var docs_03 = new Feature("Documentation 03");
docs.Children.Add(docs_01);
docs.Children.Add(docs_02);
docs.Children.Add(docs_03);
binaries.Children.Add(docs);
Project project = new Project("MyProduct",
new Dir(@"%ProgramFiles%\My Company\My Product",
new File(binaries, @"Files\Bin\MyApp.exe"),
new Dir(docs, @"Docs\Manual",
new File(docs_01, @"Files\Docs\Manual_01.txt"),
new File(docs_02, @"Files\Docs\Manual_02.txt"),
new File(docs_03, @"Files\Docs\Manual_03.txt")
)
)
);
project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b");
var wsxfile = project.BuildWxs();
var doc = XDocument.Load(wsxfile);
var product = doc.FindSingle("Product");
var rootFeature = doc.Select("Wix/Product/Feature");
Assert.NotNull(rootFeature);
var docsFeature = rootFeature.Elements()
.FirstOrDefault(e => e.HasLocalName("Feature")
&& e.HasAttribute("Title", value => value == "MyApp Documentation"));
Assert.NotNull(docsFeature);
var doc1Feature = docsFeature.Elements()
.FirstOrDefault(e => e.HasLocalName("Feature")
&& e.HasAttribute("Title", value => value == "Documentation 01"));
Assert.NotNull(doc1Feature);
var doc2Feature = docsFeature.Elements()
.FirstOrDefault(e => e.HasLocalName("Feature")
&& e.HasAttribute("Title", value => value == "Documentation 02"));
Assert.NotNull(doc2Feature);
var doc3Feature = docsFeature.Elements()
.FirstOrDefault(e => e.HasLocalName("Feature")
&& e.HasAttribute("Title", value => value == "Documentation 03"));
Assert.NotNull(doc3Feature);
}
[Fact]
[Description("Issue #49")]
public void Should_Fix_Issue_49()
{
{
var project = new Project("MyProduct");
var rootDir = new Dir(@"%ProgramFiles%",
new Dir(@"AAA\BBB",
new File(this.GetType().Assembly.Location)));
project.Dirs = new[] { rootDir };
project.UI = WUI.WixUI_InstallDir;
var msi = project.BuildMsi();
}
{
var project = new Project("MyProduct");
var rootDir = new Dir(@"C:\",
new Dir(@"Program Files (x86)\AAA\BBB",
new File(this.GetType().Assembly.Location)));
project.Dirs = new[] { rootDir };
project.UI = WUI.WixUI_InstallDir;
var msi = project.BuildMsi();
//var msi = project.BuildWxs();
}
{
var project = new Project("MyProduct");
var rootDir = new Dir(@"C:\Program Files (x86)",
new Dir(@"AAA\BBB",
new File(this.GetType().Assembly.Location)));
project.Dirs = new[] { rootDir };
project.BuildMsi();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayerServer
{
public class BackwardsCompatibility
{
public static void UpdateModcontrolPartList()
{
if (!File.Exists(Server.modFile))
{
return;
}
bool readingParts = false;
string modcontrolVersion = "";
StringBuilder sb = new StringBuilder();
sb.AppendLine("#MODCONTROLVERSION=" + Common.MODCONTROL_VERSION);
List<string> stockParts = Common.GetStockParts();
List<string> modParts = new List<string>();
bool partsPrinted = false;
using (StreamReader sr = new StreamReader(Server.modFile))
{
string currentLine = null;
while ((currentLine = sr.ReadLine()) != null)
{
string trimmedLine = currentLine.Trim();
if (!readingParts)
{
if (trimmedLine.StartsWith("#MODCONTROLVERSION=", StringComparison.Ordinal))
{
modcontrolVersion = trimmedLine.Substring(currentLine.IndexOf("=", StringComparison.Ordinal) + 1);
if (modcontrolVersion == Common.MODCONTROL_VERSION)
{
//Mod control file is up to date.
return;
}
}
else
{
sb.AppendLine(currentLine);
}
if (trimmedLine == "!partslist")
{
readingParts = true;
}
}
else
{
if (trimmedLine.StartsWith("#", StringComparison.Ordinal) || trimmedLine == string.Empty)
{
sb.AppendLine(currentLine);
continue;
}
//This is an edge case, but it's still possible if someone moves something manually.
if (trimmedLine.StartsWith("!", StringComparison.Ordinal))
{
if (!partsPrinted)
{
partsPrinted = true;
foreach (string stockPart in stockParts)
{
sb.AppendLine(stockPart);
}
foreach (string modPart in modParts)
{
sb.AppendLine(modPart);
}
}
readingParts = false;
sb.AppendLine(currentLine);
continue;
}
if (!stockParts.Contains(currentLine))
{
modParts.Add(currentLine);
}
}
}
}
if (!partsPrinted)
{
partsPrinted = true;
foreach (string stockPart in stockParts)
{
sb.AppendLine(stockPart);
}
foreach (string modPart in modParts)
{
sb.AppendLine(modPart);
}
}
File.WriteAllText(Server.modFile + ".new", sb.ToString());
File.Copy(Server.modFile + ".new", Server.modFile, true);
File.Delete(Server.modFile + ".new");
DarkLog.Debug("Added " + Common.MODCONTROL_VERSION + " parts to modcontrol.txt");
}
public static void RemoveOldPlayerTokens()
{
string playerDirectory = Path.Combine(Server.universeDirectory, "Players");
if (!Directory.Exists(playerDirectory))
{
return;
}
string[] playerFiles = Directory.GetFiles(playerDirectory, "*", SearchOption.TopDirectoryOnly);
Guid testGuid;
foreach (string playerFile in playerFiles)
{
try
{
string playerText = File.ReadAllLines(playerFile)[0];
if (Guid.TryParse(playerText, out testGuid))
{
//Player token detected, remove it
DarkLog.Debug("Removing old player token for " + Path.GetFileNameWithoutExtension(playerFile));
File.Delete(playerFile);
}
}
catch
{
DarkLog.Debug("Removing damaged player token for " + Path.GetFileNameWithoutExtension(playerFile));
File.Delete(playerFile);
}
}
}
public static void FixKerbals()
{
string kerbalPath = Path.Combine(Server.universeDirectory, "Kerbals");
int kerbalCount = 0;
while (File.Exists(Path.Combine(kerbalPath, kerbalCount + ".txt")))
{
string oldKerbalFile = Path.Combine(kerbalPath, kerbalCount + ".txt");
string kerbalName = null;
using (StreamReader sr = new StreamReader(oldKerbalFile))
{
string fileLine;
while ((fileLine = sr.ReadLine()) != null)
{
if (fileLine.StartsWith("name = ", StringComparison.Ordinal))
{
kerbalName = fileLine.Substring(fileLine.IndexOf("name = ", StringComparison.Ordinal) + 7);
break;
}
}
}
if (!String.IsNullOrEmpty(kerbalName))
{
DarkLog.Debug("Renaming kerbal " + kerbalCount + " to " + kerbalName);
File.Move(oldKerbalFile, Path.Combine(kerbalPath, kerbalName + ".txt"));
}
kerbalCount++;
}
if (kerbalCount != 0)
{
DarkLog.Normal("Kerbal database upgraded to 0.24 format");
}
}
public static void ConvertSettings(string oldSettings, string newSettings)
{
if (!File.Exists(oldSettings))
{
return;
}
using (StreamWriter sw = new StreamWriter(newSettings))
{
using (StreamReader sr = new StreamReader(oldSettings))
{
string currentLine;
while ((currentLine = sr.ReadLine()) != null)
{
string trimmedLine = currentLine.Trim();
if (!trimmedLine.Contains(",") || trimmedLine.StartsWith("#", StringComparison.Ordinal) || trimmedLine == string.Empty)
{
continue;
}
int seperatorIndex = trimmedLine.IndexOf(",", StringComparison.Ordinal);
string keyPart = trimmedLine.Substring(0, seperatorIndex).Trim();
string valuePart = trimmedLine.Substring(seperatorIndex + 1).Trim();
string realKey = keyPart;
foreach (FieldInfo fieldInfo in typeof(SettingsStore).GetFields())
{
if (fieldInfo.Name.ToLower() == keyPart.ToLower())
{
realKey = fieldInfo.Name;
break;
}
}
sw.WriteLine(realKey + "=" + valuePart);
}
}
}
File.Delete(oldSettings);
DarkLog.Debug("Converted settings to DMP v0.2.1.0 format");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using Lucene.Net.Support;
using NUnit.Framework;
using IBits = Lucene.Net.Util.IBits;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
/// <summary>
/// Test class to illustrate using IndexDeletionPolicy to provide multi-level rollback capability.
/// this test case creates an index of records 1 to 100, introducing a commit point every 10 records.
///
/// A "keep all" deletion policy is used to ensure we keep all commit points for testing purposes
/// </summary>
[TestFixture]
public class TestTransactionRollback : LuceneTestCase
{
private const string FIELD_RECORD_ID = "record_id";
private Directory Dir;
//Rolls back index to a chosen ID
private void RollBackLast(int id)
{
// System.out.println("Attempting to rollback to "+id);
string ids = "-" + id;
IndexCommit last = null;
ICollection<IndexCommit> commits = DirectoryReader.ListCommits(Dir);
for (IEnumerator<IndexCommit> iterator = commits.GetEnumerator(); iterator.MoveNext(); )
{
IndexCommit commit = iterator.Current;
IDictionary<string, string> ud = commit.UserData;
if (ud.Count > 0)
{
if (ud["index"].EndsWith(ids, StringComparison.Ordinal))
{
last = commit;
}
}
}
if (last == null)
{
throw new Exception("Couldn't find commit point " + id);
}
IndexWriter w = new IndexWriter(Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(new RollbackDeletionPolicy(this, id)).SetIndexCommit(last));
IDictionary<string, string> data = new Dictionary<string, string>();
data["index"] = "Rolled back to 1-" + id;
w.SetCommitData(data);
w.Dispose();
}
[Test]
public virtual void TestRepeatedRollBacks()
{
int expectedLastRecordId = 100;
while (expectedLastRecordId > 10)
{
expectedLastRecordId -= 10;
RollBackLast(expectedLastRecordId);
BitArray expecteds = new BitArray(100);
expecteds.Set(1, (expectedLastRecordId + 1), true);
CheckExpecteds(expecteds);
}
}
private void CheckExpecteds(BitArray expecteds)
{
IndexReader r = DirectoryReader.Open(Dir);
//Perhaps not the most efficient approach but meets our
//needs here.
IBits liveDocs = MultiFields.GetLiveDocs(r);
for (int i = 0; i < r.MaxDoc; i++)
{
if (liveDocs == null || liveDocs.Get(i))
{
string sval = r.Document(i).Get(FIELD_RECORD_ID);
if (sval != null)
{
int val = Convert.ToInt32(sval);
Assert.IsTrue(expecteds.SafeGet(val), "Did not expect document #" + val);
expecteds.SafeSet(val, false);
}
}
}
r.Dispose();
Assert.AreEqual(0, expecteds.Cardinality(), "Should have 0 docs remaining ");
}
/*
private void showAvailableCommitPoints() throws Exception {
Collection commits = DirectoryReader.ListCommits(dir);
for (Iterator iterator = commits.iterator(); iterator.hasNext();) {
IndexCommit comm = (IndexCommit) iterator.Next();
System.out.print("\t Available commit point:["+comm.getUserData()+"] files=");
Collection files = comm.getFileNames();
for (Iterator iterator2 = files.iterator(); iterator2.hasNext();) {
String filename = (String) iterator2.Next();
System.out.print(filename+", ");
}
System.out.println();
}
}
*/
[SetUp]
public override void SetUp()
{
base.SetUp();
Dir = NewDirectory();
//Build index, of records 1 to 100, committing after each batch of 10
IndexDeletionPolicy sdp = new KeepAllDeletionPolicy(this);
IndexWriter w = new IndexWriter(Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(sdp));
for (int currentRecordId = 1; currentRecordId <= 100; currentRecordId++)
{
Document doc = new Document();
doc.Add(NewTextField(FIELD_RECORD_ID, "" + currentRecordId, Field.Store.YES));
w.AddDocument(doc);
if (currentRecordId % 10 == 0)
{
IDictionary<string, string> data = new Dictionary<string, string>();
data["index"] = "records 1-" + currentRecordId;
w.SetCommitData(data);
w.Commit();
}
}
w.Dispose();
}
[TearDown]
public override void TearDown()
{
Dir.Dispose();
base.TearDown();
}
// Rolls back to previous commit point
internal class RollbackDeletionPolicy : IndexDeletionPolicy
{
private readonly TestTransactionRollback OuterInstance;
internal int RollbackPoint;
public RollbackDeletionPolicy(TestTransactionRollback outerInstance, int rollbackPoint)
{
this.OuterInstance = outerInstance;
this.RollbackPoint = rollbackPoint;
}
public override void OnCommit<T>(IList<T> commits)
{
}
public override void OnInit<T>(IList<T> commits)
{
foreach (IndexCommit commit in commits)
{
IDictionary<string, string> userData = commit.UserData;
if (userData.Count > 0)
{
// Label for a commit point is "Records 1-30"
// this code reads the last id ("30" in this example) and deletes it
// if it is after the desired rollback point
string x = userData["index"];
// LUCENENET specific - Bug in the original when "-" is the last character in
// the string, it tries to match one larger than what is available.
int lastIndex = x.LastIndexOf("-");
string lastVal = x.Substring(lastIndex + 1 == x.Length ? lastIndex : lastIndex + 1);
int last = Convert.ToInt32(lastVal);
if (last > RollbackPoint)
{
/*
System.out.print("\tRolling back commit point:" +
" UserData="+commit.getUserData() +") ("+(commits.Size()-1)+" commit points left) files=");
Collection files = commit.getFileNames();
for (Iterator iterator2 = files.iterator(); iterator2.hasNext();) {
System.out.print(" "+iterator2.Next());
}
System.out.println();
*/
commit.Delete();
}
}
}
}
}
internal class DeleteLastCommitPolicy : IndexDeletionPolicy
{
private readonly TestTransactionRollback OuterInstance;
public DeleteLastCommitPolicy(TestTransactionRollback outerInstance)
{
this.OuterInstance = outerInstance;
}
public override void OnCommit<T>(IList<T> commits)
{
}
public override void OnInit<T>(IList<T> commits)
{
commits.RemoveAt(commits.Count - 1);
}
}
[Test]
public virtual void TestRollbackDeletionPolicy()
{
for (int i = 0; i < 2; i++)
{
// Unless you specify a prior commit point, rollback
// should not work:
(new IndexWriter(Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(new DeleteLastCommitPolicy(this)))).Dispose();
IndexReader r = DirectoryReader.Open(Dir);
Assert.AreEqual(100, r.NumDocs);
r.Dispose();
}
}
// Keeps all commit points (used to build index)
internal class KeepAllDeletionPolicy : IndexDeletionPolicy
{
private readonly TestTransactionRollback OuterInstance;
public KeepAllDeletionPolicy(TestTransactionRollback outerInstance)
{
this.OuterInstance = outerInstance;
}
public override void OnCommit<T>(IList<T> commits)
{
}
public override void OnInit<T>(IList<T> commits)
{
}
}
}
}
| |
using System.ComponentModel;
using System.IO;
using System.Text;
using IdSharp.Common.Utils;
namespace IdSharp.Tagging.ID3v1
{
/// <summary>
/// ID3v1
/// </summary>
public partial class ID3v1Tag : IID3v1Tag
{
private string _title;
private string _artist;
private string _album;
private string _year;
private string _comment;
private int? _trackNumber;
private int _genreIndex;
private ID3v1TagVersion _tagVersion;
/// <summary>
/// Initializes a new instance of the <see cref="ID3v1Tag"/> class.
/// </summary>
public ID3v1Tag()
{
_tagVersion = ID3v1TagVersion.ID3v11;
_genreIndex = 12; // Other
}
/// <summary>
/// Initializes a new instance of the <see cref="ID3v1Tag"/> class.
/// </summary>
/// <param name="path">The full path of the file.</param>
public ID3v1Tag(string path)
{
_tagVersion = ID3v1TagVersion.ID3v11;
_genreIndex = 12; // Other
Read(path);
}
/// <summary>
/// Initializes a new instance of the <see cref="ID3v1Tag"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
public ID3v1Tag(Stream stream)
{
_tagVersion = ID3v1TagVersion.ID3v11;
_genreIndex = 12; // Other
Read(stream);
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>The title.</value>
public string Title
{
get { return _title; }
set
{
_title = GetTrimmedString(value, 30);
RaisePropertyChanged("Title");
}
}
/// <summary>
/// Gets or sets the artist.
/// </summary>
/// <value>The artist.</value>
public string Artist
{
get { return _artist; }
set
{
_artist = GetTrimmedString(value, 30);
RaisePropertyChanged("Artist");
}
}
/// <summary>
/// Gets or sets the album.
/// </summary>
/// <value>The album.</value>
public string Album
{
get { return _album; }
set
{
_album = GetTrimmedString(value, 30);
RaisePropertyChanged("Album");
}
}
/// <summary>
/// Gets or sets the year.
/// </summary>
/// <value>The year.</value>
public string Year
{
get { return _year; }
set
{
_year = GetTrimmedString(value, 4);
RaisePropertyChanged("Year");
}
}
/// <summary>
/// Gets or sets the comment.
/// </summary>
/// <value>The comment.</value>
public string Comment
{
get { return _comment; }
set
{
if (_tagVersion == ID3v1TagVersion.ID3v11)
_comment = GetTrimmedString(value, 28);
else
_comment = GetTrimmedString(value, 30);
RaisePropertyChanged("Comment");
}
}
/// <summary>
/// Gets or sets the track number.
/// </summary>
/// <value>The track number.</value>
public int? TrackNumber
{
get { return _trackNumber; }
set
{
if (value == null || value == 0)
{
_trackNumber = null;
if (_tagVersion == ID3v1TagVersion.ID3v11)
TagVersion = ID3v1TagVersion.ID3v10;
}
else if (value > 0 && value <= 255)
{
_trackNumber = value;
if (_tagVersion == ID3v1TagVersion.ID3v10)
TagVersion = ID3v1TagVersion.ID3v11;
}
RaisePropertyChanged("TrackNumber");
}
}
/// <summary>
/// Gets or sets the index of the genre.
/// </summary>
/// <value>The index of the genre.</value>
public int GenreIndex
{
get { return _genreIndex; }
set
{
if (value >= 0 && value <= 147)
_genreIndex = value;
RaisePropertyChanged("GenreIndex");
}
}
/// <summary>
/// Gets or sets the ID3v1 tag version.
/// </summary>
/// <value>The ID3v1 tag version.</value>
public ID3v1TagVersion TagVersion
{
get { return _tagVersion; }
set
{
_tagVersion = value;
RaisePropertyChanged("TagVersion");
if (value == ID3v1TagVersion.ID3v11)
{
Comment = _comment;
}
}
}
/// <summary>
/// Reads the ID3v1 tag from the specified path.
/// </summary>
/// <param name="path">The full path of the file.</param>
public void Read(string path)
{
using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
Read(fileStream);
}
}
/// <summary>
/// Reads the ID3v1 tag from the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
public void Read(Stream stream)
{
if (stream.Length >= 128)
{
stream.Seek(-128, SeekOrigin.End);
if (GetString(stream, 3) == "TAG")
{
Title = GetString(stream, 30);
Artist = GetString(stream, 30);
Album = GetString(stream, 30);
Year = GetString(stream, 4);
// Comment
byte[] buf = new byte[30];
stream.Read(buf, 0, 30);
string comment = GetString(buf);
// ID3v1.1
if (buf[28] == 0 && buf[29] != 0)
{
TagVersion = ID3v1TagVersion.ID3v11;
Comment = GetTrimmedString(comment, 28);
TrackNumber = buf[29];
}
else
{
TagVersion = ID3v1TagVersion.ID3v10;
Comment = comment;
TrackNumber = null;
}
int genreIndex = stream.Read1();
if (genreIndex < 0 || genreIndex > 147)
genreIndex = 12; // "Other"
GenreIndex = genreIndex;
}
else
{
Reset();
}
}
else
{
Reset();
}
}
/// <summary>
/// Resets the properties of the ID3v1 tag to their default values.
/// </summary>
public void Reset()
{
Title = null;
Artist = null;
Album = null;
Year = null;
Comment = null;
TrackNumber = null;
GenreIndex = 12; /* Other */
TagVersion = ID3v1TagVersion.ID3v11;
}
/// <summary>
/// Saves the ID3v1 tag to the specified path.
/// </summary>
/// <param name="path">The full path of the file.</param>
public void Save(string path)
{
using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
fileStream.Seek(0 - GetTagSize(fileStream), SeekOrigin.End);
byte[] titleBytes = SafeGetBytes(_title);
byte[] artistBytes = SafeGetBytes(_artist);
byte[] albumBytes = SafeGetBytes(_album);
byte[] yearBytes = SafeGetBytes(_year);
byte[] commentBytes;
fileStream.Write(Encoding.ASCII.GetBytes("TAG"));
WriteBytesPadded(fileStream, titleBytes, 30);
WriteBytesPadded(fileStream, artistBytes, 30);
WriteBytesPadded(fileStream, albumBytes, 30);
WriteBytesPadded(fileStream, yearBytes, 4);
if (_tagVersion == ID3v1TagVersion.ID3v11)
{
commentBytes = SafeGetBytes(_comment);
WriteBytesPadded(fileStream, commentBytes, 28);
fileStream.WriteByte(0);
fileStream.WriteByte((byte)(_trackNumber ?? 0));
}
else
{
commentBytes = SafeGetBytes(_comment);
WriteBytesPadded(fileStream, commentBytes, 30);
}
fileStream.WriteByte((byte)_genreIndex);
}
}
private void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Writes a specified number of bytes to a stream, padding any missing bytes with 0x00.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="byteArray">The byte array.</param>
/// <param name="length">The number of bytes to be written.</param>
private static void WriteBytesPadded(Stream stream, byte[] byteArray, int length)
{
int i;
for (i = 0; i < length && i < byteArray.Length && byteArray[i] != 0; i++)
{
stream.WriteByte(byteArray[i]);
}
for (; i < length; i++)
{
stream.WriteByte(0);
}
}
/// <summary>
/// Gets a string from a specified stream using ISO-8859-1 encoding.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="length">The length of the string in bytes.</param>
private static string GetString(Stream stream, int length)
{
byte[] byteArray = new byte[length];
stream.Read(byteArray, 0, length);
return GetString(byteArray);
}
/// <summary>
/// Gets a string from a specified byte array using ISO-8859-1 encoding.
/// </summary>
/// <param name="byteArray">The byte array.</param>
private static string GetString(byte[] byteArray)
{
if (byteArray == null || byteArray.Length == 0)
return null;
int maxLength;
for (maxLength = byteArray.Length; maxLength > 0; maxLength--)
{
if (byteArray[maxLength - 1] >= 32)
break;
}
return ByteUtils.ISO88591.GetString(byteArray, 0, maxLength).TrimEnd('\0').TrimEnd(' ');
}
/// <summary>
/// Gets a trimmed string with a maximum length from a specified string.
/// </summary>
/// <param name="value">The original string value.</param>
/// <param name="maxLength">Maximum length of the string.</param>
private static string GetTrimmedString(string value, int maxLength)
{
if (value == null)
return null;
value = value.TrimEnd('\0').Trim();
if (value.Length > maxLength)
return value.Substring(0, maxLength).Trim();
else
return value;
}
private static byte[] SafeGetBytes(string value)
{
if (value == null)
return new byte[0];
else
return ByteUtils.ISO88591.GetBytes(value);
}
}
}
| |
using GuiLabs.Canvas.Controls;
using GuiLabs.Editor.Blocks;
using GuiLabs.Editor.UI;
using System.Collections.Generic;
namespace GuiLabs.Editor.CSharp
{
[BlockSerialization("statement")]
public class StatementLine : ExpressionBlock, IReparsable, IMethodLevel
{
#region ctors
public StatementLine()
: base()
{
this.Multiline = true;
this.Draggable = true;
Context = CompletionContext.Statement;
}
public StatementLine(string initialText)
: this()
{
this.Text = initialText;
Reparse();
}
#endregion
#region OnEvents
protected override void OnKeyDownReturn(System.Windows.Forms.KeyEventArgs e)
{
if (Multiline
&& (e.Control
|| (this.Text.StartsWith("return")
&& this.MyTextBox.CaretIsAtEnd))
&& CtrlEnter(LastCtrlReturn))
{
e.Handled = true;
}
if (!e.Handled)
{
base.OnKeyDownReturn(e);
}
}
protected override void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == '/')
{
this.Replace(new CommentBlock());
e.Handled = true;
return;
}
base.OnKeyPress(sender, e);
}
protected override void OnRootChanged(RootBlock oldRoot, RootBlock newRoot)
{
base.OnRootChanged(oldRoot, newRoot);
if (newRoot != null)
{
Reparse();
}
}
protected override void OnTextHasChanged(ITextProvider changedControl, string oldText, string newText)
{
base.OnTextHasChanged(changedControl, oldText, newText);
Reparse();
}
#endregion
#region DragDrop
public override bool Draggable
{
get
{
if (this.Prev == null && this.Next == null)
{
return false;
}
return base.Draggable;
}
set
{
base.Draggable = value;
}
}
#endregion
#region Delete
public override void Delete()
{
if (this.Prev == null && this.Next == null)
{
this.Text = "";
}
else
{
base.Delete();
}
}
#endregion
#region Statement completion
protected override void FillItems(CustomItemsRequestEventArgs e)
{
LanguageService.GetCompletion(this, e.Items, this.Context);
AddStatementItems(e.Items);
e.ShowOnlyCustomItems = true;
}
#region Statements
private void AddStatementItems(ICompletionListBuilder items)
{
if (this.Text.Length <= 1 && this.Context == CompletionContext.Statement)
{
CompletionAddStatements(items);
}
}
public virtual void CompletionAddStatements(ICompletionListBuilder items)
{
items.AddText("return", Icons.Keyword);
items.AddText("throw", Icons.Keyword);
CompletionAddControlStructures(items);
}
public virtual void CompletionAddControlStructures(ICompletionListBuilder items)
{
AddControlStructure<IfBlock>("if", items);
if (this.Prev is IfBlock || this.Prev is ElseBlock)
{
AddControlStructure<ElseBlock>("else", items);
}
AddControlStructure<WhileBlock>("while", items);
AddControlStructure<DoWhileBlock>("do", items);
AddControlStructure<ForBlock>("for", items);
AddControlStructure<ForeachBlock>("foreach", items);
AddControlStructure<LockBlock>("lock", items);
AddControlStructure<TryBlock>("try", items);
if (this.Prev is TryBlock || this.Prev is CatchBlock)
{
AddControlStructure<CatchBlock>("catch", items);
AddControlStructure<FinallyBlock>("finally", items);
}
AddControlStructure<UsingStatementBlock>("using", items);
if (this.Next == null && ClassNavigator.FindContainingControlStructure(this) != null)
{
AddControlStructure<BreakStatement>("break", items);
AddControlStructure<ContinueStatement>("continue", items);
}
}
public virtual void AddControlStructure<T>(string text, ICompletionListBuilder items)
{
ReplaceBlocksItem item = ReplaceBlocksItem.Create<T>(text);
item.Picture = Icons.Keyword;
items.Add(item);
}
#endregion
#endregion
#region Local variable declaration
public void Reparse()
{
LanguageService ls = LanguageService.Get(this);
if (ls != null && ls.Parser != null)
{
StatementInfo = ls.Parser.ParseStatement(this.Text);
}
else
{
StatementInfo = null;
}
}
private IStatement mStatementInfo;
public IStatement StatementInfo
{
get
{
return mStatementInfo;
}
set
{
mStatementInfo = value;
}
}
public VariableDeclaration LocalVariableDeclaration
{
get
{
return StatementInfo != null ? StatementInfo.LocalVariableDeclaration : null;
}
}
#endregion
#region Style
protected override string StyleName()
{
return "StatementLine";
}
#endregion
#region Help
private static string[] mHelpStrings = new string[]
{
"This is a statement line."
};
public override IEnumerable<string> HelpStrings
{
get
{
foreach (string current in mHelpStrings)
{
yield return current;
}
foreach (string baseString in GetOldHelpStrings())
{
yield return baseString;
}
}
}
private IEnumerable<string> GetOldHelpStrings()
{
return base.HelpStrings;
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using Xunit;
using Shouldly;
using System.Collections;
namespace AutoMapper.UnitTests
{
public class When_mapping_to_existing_observable_collection : AutoMapperSpecBase
{
class CollectionHolder
{
public CollectionHolder()
{
Observable = new ObservableCollection<List<int>>();
}
public ObservableCollection<List<int>> Observable { get; set; }
}
class CollectionHolderDto
{
public CollectionHolderDto()
{
Observable = new List<List<int>>();
}
public List<List<int>> Observable { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => cfg.CreateMap<CollectionHolderDto, CollectionHolder>().ForMember(a => a.Observable, opt => opt.UseDestinationValue()));
[Fact]
public void Should_map_ok()
{
var ch = new CollectionHolderDto();
var list = new List<int>{ 5, 6 };
ch.Observable.Add(list);
var mapped = Mapper.Map<CollectionHolder>(ch);
mapped.Observable.Single().ShouldBe(list);
}
}
public class When_mapping_to_member_typed_as_IEnumerable : AutoMapperSpecBase
{
public class SourceItem { }
public class DestItem { }
public class SourceA
{
public IEnumerable<SourceItem> Items { get; set; }
public IEnumerable<SourceB> Bs { get; set; } // Problem
}
public class SourceB
{
public IEnumerable<SourceItem> Items { get; set; }
}
public class DestA
{
public IEnumerable<DestItem> Items { get; set; }
public IEnumerable<DestB> Bs { get; set; } // Problem
}
public class DestB
{
public IEnumerable<DestItem> Items { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg=>
{
cfg.CreateMap<SourceA, DestA>();
cfg.CreateMap<SourceB, DestB>();
});
[Fact]
public void Should_map_ok()
{
Mapper.Map<DestB>(new SourceB()).Items.ShouldBeEmpty();
}
}
public class When_mapping_to_existing_collection_typed_as_IEnumerable : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration => new MapperConfiguration(_=>{ });
[Fact]
public void Should_map_ok()
{
IEnumerable<int> destination = new List<int>();
var source = Enumerable.Range(1, 10).ToArray();
Mapper.Map(source, destination);
destination.SequenceEqual(source).ShouldBeTrue();
}
}
public class When_mapping_to_readonly_property_as_IEnumerable_and_existing_destination : AutoMapperSpecBase
{
public class Source
{
private readonly List<string> _myCollection = new List<string> { "one", "two" };
public string[] MyCollection => _myCollection.ToArray();
}
public class Destination
{
private IList<string> _myCollection = new List<string>();
public IEnumerable<string> MyCollection => _myCollection;
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
cfg.CreateMap<Source, Destination>().ForMember(m => m.MyCollection, opt =>
{
opt.MapFrom(src => src.MyCollection);
}));
[Fact]
public void Should_map_ok()
{
Mapper.Map(new Source(), new Destination())
.MyCollection.SequenceEqual(new[] { "one", "two" }).ShouldBeTrue();
}
}
public class When_mapping_to_readonly_property_as_IEnumerable : AutoMapperSpecBase
{
public class Source
{
private readonly List<string> _myCollection = new List<string> { "one", "two" };
public string[] MyCollection => _myCollection.ToArray();
}
public class Destination
{
private IList<string> _myCollection = new List<string>();
public IEnumerable<string> MyCollection => _myCollection;
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
cfg.CreateMap<Source, Destination>().ForMember(m => m.MyCollection, opt =>
{
opt.MapFrom(src => src.MyCollection);
opt.UseDestinationValue();
}));
[Fact]
public void Should_map_ok()
{
Mapper.Map<Destination>(new Source())
.MyCollection.SequenceEqual(new[] { "one", "two" }).ShouldBeTrue();
}
}
public class When_mapping_from_struct_collection : AutoMapperSpecBase
{
public struct MyCollection : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
for(int i = 1; i <= 10; i++)
{
yield return i;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class SourceItem
{
public string Name { get; set; }
public MyCollection ShipsTo { get; set; }
}
public class DestItem
{
public string Name { get; set; }
public List<int> ShipsTo { get; set; }
}
protected override MapperConfiguration Configuration =>
new MapperConfiguration(cfg => cfg.CreateMap<SourceItem, DestItem>());
[Fact]
public void Should_map_ok()
{
Mapper.Map<DestItem>(new SourceItem { ShipsTo = new MyCollection() })
.ShipsTo.SequenceEqual(Enumerable.Range(1, 10)).ShouldBeTrue();
}
}
public class When_mapping_to_custom_collection_type : AutoMapperSpecBase
{
public class MyCollection : CollectionBase
{
}
public class SourceItem
{
public string Name { get; set; }
public List<string> ShipsTo { get; set; }
}
public class DestItem
{
public string Name { get; set; }
public MyCollection ShipsTo { get; set; }
}
protected override MapperConfiguration Configuration =>
new MapperConfiguration(cfg => cfg.CreateMap<SourceItem, DestItem>());
[Fact]
public void Should_map_ok()
{
var items = Enumerable.Range(1, 10).Select(i => i.ToString()).ToArray();
Mapper.Map<DestItem>(new SourceItem { ShipsTo = new List<string>(items) })
.ShipsTo.Cast<string>().SequenceEqual(items).ShouldBeTrue();
}
}
public class When_mapping_to_unknown_collection_type : NonValidatingSpecBase
{
public class MyCollection
{
}
public class SourceItem
{
public string Name { get; set; }
public List<string> ShipsTo { get; set; }
}
public class DestItem
{
public string Name { get; set; }
public MyCollection ShipsTo { get; set; }
}
protected override MapperConfiguration Configuration =>
new MapperConfiguration(cfg =>
{
cfg.CreateMap<SourceItem, DestItem>();
cfg.CreateMissingTypeMaps = false;
});
[Fact]
public void Should_report_missing_map()
{
new Action(Configuration.AssertConfigurationIsValid).ShouldThrowException<AutoMapperConfigurationException>(ex =>
{
ex.PropertyMap.SourceMember.ShouldBe(typeof(SourceItem).GetProperty("ShipsTo"));
ex.Types.Value.ShouldBe(new TypePair(typeof(SourceItem), typeof(DestItem)));
});
}
}
public class When_mapping_collections_with_inheritance : AutoMapperSpecBase
{
public class Source
{
public IEnumerable<SourceItem> Items { get; set; }
}
public class Destination
{
public IEnumerable<DestinationItemBase> Items { get; set; }
}
public class SourceItem
{
public int Value { get; set; }
}
public class DestinationItemBase
{
public int Value { get; set; }
}
public class SpecificDestinationItem : DestinationItemBase
{
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<SourceItem, DestinationItemBase>().As<SpecificDestinationItem>();
cfg.CreateMap<SourceItem, SpecificDestinationItem>();
cfg.CreateMap<Source, Destination>();
});
}
public class When_passing_a_not_empty_collection : AutoMapperSpecBase
{
Destination _destination = new Destination();
class Source
{
public List<SourceItem> Items { get; }
}
class SourceItem
{
}
class Destination
{
public List<DestinationItem> Items { get; } = new List<DestinationItem> { new DestinationItem() };
}
class DestinationItem
{
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<SourceItem, DestinationItem>();
});
protected override void Because_of()
{
Mapper.Map(new Source(), _destination);
}
[Fact]
public void It_should_be_cleared_first()
{
_destination.Items.ShouldBeEmpty();
}
}
public class When_mapping_collections_with_structs : AutoMapperSpecBase
{
BarDTO _destination;
public struct Foo { }
public struct Bar
{
public IEnumerable<Foo> Foos { get; set; }
}
public struct FooDTO { }
public struct BarDTO
{
public IEnumerable<FooDTO> Foos { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Bar, BarDTO>();
cfg.CreateMap<Foo, FooDTO>();
});
protected override void Because_of()
{
_destination = Mapper.Map<BarDTO>(new Bar { Foos = new Foo[5] });
}
[Fact]
public void Should_map_ok()
{
_destination.Foos.SequenceEqual(new FooDTO[5]).ShouldBeTrue();
}
}
public class CollectionMapping
{
public CollectionMapping()
{
SetUp();
}
public void SetUp()
{
}
public class MasterWithList
{
private IList<Detail> _details = new List<Detail>();
public int Id { get; set; }
public IList<Detail> Details
{
get { return _details; }
set { _details = value; }
}
}
public class MasterWithCollection
{
public MasterWithCollection(ICollection<Detail> details)
{
Details = details;
}
public int Id { get; set; }
public ICollection<Detail> Details { get; set; }
}
public class MasterWithNoExistingCollection
{
public int Id { get; set; }
public HashSet<Detail> Details { get; set; }
}
public class Detail
{
public int Id { get; set; }
}
public class MasterDto
{
public int Id { get; set; }
public DetailDto[] Details { get; set; }
}
public class DetailDto
{
public int Id { get; set; }
}
private static IMapper mapper;
private static void FillCollection<TSource, TDestination, TSourceItem, TDestinationItem>(
TSource s, TDestination d,
Func<TSource, IEnumerable<TSourceItem>> getSourceEnum,
Func<TDestination, ICollection<TDestinationItem>> getDestinationColl)
{
ICollection<TDestinationItem> collection = getDestinationColl(d);
collection.Clear();
foreach (TSourceItem sourceItem in getSourceEnum(s))
{
collection.Add(mapper.Map<TSourceItem, TDestinationItem>(sourceItem));
}
}
[Fact]
public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_list()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<MasterDto, MasterWithCollection>()
.ForMember(d => d.Details, o => o.UseDestinationValue());
cfg.CreateMap<DetailDto, Detail>();
});
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new List<Detail>());
ICollection<Detail> originalCollection = master.Details;
config.CreateMapper().Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
originalCollection.Count.ShouldBe(master.Details.Count);
}
[Fact]
public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_set()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<MasterDto, MasterWithCollection>()
.ForMember(d => d.Details, o => o.UseDestinationValue());
cfg.CreateMap<DetailDto, Detail>();
});
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new HashSet<Detail>());
ICollection<Detail> originalCollection = master.Details;
config.CreateMapper().Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
originalCollection.Count.ShouldBe(master.Details.Count);
}
[Fact]
public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_set_with_aftermap()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<MasterDto, MasterWithCollection>()
.ForMember(d => d.Details, o => o.Ignore())
.AfterMap((s, d) => FillCollection(s, d, ss => ss.Details, dd => dd.Details));
cfg.CreateMap<DetailDto, Detail>();
});
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new HashSet<Detail>());
ICollection<Detail> originalCollection = master.Details;
mapper = config.CreateMapper();
mapper.Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
originalCollection.Count.ShouldBe(master.Details.Count);
}
[Fact]
public void Should_keep_and_fill_destination_list()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<MasterDto, MasterWithList>()
.ForMember(d => d.Details, o => o.UseDestinationValue());
cfg.CreateMap<DetailDto, Detail>();
});
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithList();
IList<Detail> originalCollection = master.Details;
config.CreateMapper().Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
originalCollection.Count.ShouldBe(master.Details.Count);
}
[Fact]
public void Should_not_replace_destination_collection()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<MasterDto, MasterWithCollection>()
.ForMember(d => d.Details, opt => opt.UseDestinationValue());
cfg.CreateMap<DetailDto, Detail>();
});
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new List<Detail>());
ICollection<Detail> originalCollection = master.Details;
config.CreateMapper().Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
}
[Fact]
public void Should_be_able_to_map_to_a_collection_type_that_implements_ICollection_of_T()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<MasterDto, MasterWithNoExistingCollection>();
cfg.CreateMap<DetailDto, Detail>();
});
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = config.CreateMapper().Map<MasterDto, MasterWithNoExistingCollection>(dto);
master.Details.Count.ShouldBe(2);
}
[Fact]
public void Should_not_replace_destination_list()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<MasterDto, MasterWithList>()
.ForMember(d => d.Details, opt => opt.UseDestinationValue());
cfg.CreateMap<DetailDto, Detail>();
});
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithList();
IList<Detail> originalCollection = master.Details;
config.CreateMapper().Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
}
[Fact]
public void Should_map_to_NameValueCollection() {
// initially results in the following exception:
// ----> System.InvalidCastException : Unable to cast object of type 'System.Collections.Specialized.NameValueCollection' to type 'System.Collections.IList'.
// this was fixed by adding NameValueCollectionMapper to the MapperRegistry.
var c = new NameValueCollection();
var config = new MapperConfiguration(cfg => { });
var mappedCollection = config.CreateMapper().Map<NameValueCollection, NameValueCollection>(c);
mappedCollection.ShouldNotBeNull();
}
}
public class When_mapping_from_ICollection_types_but_implementations_are_different : AutoMapperSpecBase
{
public class Source
{
public ICollection<Item> Items { get; set; }
public class Item
{
public int Value { get; set; }
}
}
public class Dest
{
public ICollection<Item> Items { get; set; } = new HashSet<Item>();
public class Item
{
public int Value { get; set; }
}
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Dest>();
cfg.CreateMap<Source.Item, Dest.Item>();
});
[Fact]
public void Should_map_items()
{
var source = new Source
{
Items = new List<Source.Item>
{
new Source.Item { Value = 5 }
}
};
var dest = new Dest();
Mapper.Map(source, dest);
dest.Items.Count.ShouldBe(1);
dest.Items.First().Value.ShouldBe(5);
}
}
public class When_mapping_enumerable_to_array : AutoMapperSpecBase
{
public class Source
{
public int X { get; set; }
public IEnumerable<SourceItem> Items { get; set; }
}
public class SourceItem
{
public int I { get; set; }
}
public class Target
{
public int X { get; set; }
public TargetItem[] Items { get; set; }
}
public class TargetItem
{
public int I { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.AllowNullCollections = true;
cfg.CreateMap<Source, Target>();
cfg.CreateMap<SourceItem, TargetItem>();
});
[Fact]
public void IncludedMappings()
{
var src = new Source
{
X = 5,
Items = new List<SourceItem>
{
new SourceItem {I = 1},
new SourceItem {I = 2},
new SourceItem {I = 3}
}
};
var dest = Mapper.Map<Source, Target>(src);
src.X.ShouldBe(dest.X);
dest.Items.Length.ShouldBe(3);
dest.Items[0].I.ShouldBe(1);
dest.Items[1].I.ShouldBe(2);
dest.Items[2].I.ShouldBe(3);
}
}
}
| |
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Xsl;
using Microsoft.Win32;
namespace HtmlAgilityPack
{
/// <summary>
/// A utility class to get HTML document from HTTP.
/// </summary>
public class HtmlWeb
{
/// <summary>
/// Represents the method that will handle the PreRequest event.
/// </summary>
public delegate bool PreRequestHandler(HttpWebRequest request);
/// <summary>
/// Represents the method that will handle the PostResponse event.
/// </summary>
public delegate void PostResponseHandler(HttpWebRequest request, HttpWebResponse response);
/// <summary>
/// Represents the method that will handle the PreHandleDocument event.
/// </summary>
public delegate void PreHandleDocumentHandler(HtmlDocument document);
private int _streamBufferSize = 1024;
private string _cachePath;
private bool _usingCache;
private bool _fromCache;
private bool _cacheOnly;
private bool _useCookies;
private int _requestDuration;
private bool _autoDetectEncoding = true;
private HttpStatusCode _statusCode = HttpStatusCode.OK;
private Uri _responseUri;
/// <summary>
/// Occurs before an HTTP request is executed.
/// </summary>
public PreRequestHandler PreRequest;
/// <summary>
/// Occurs after an HTTP request has been executed.
/// </summary>
public PostResponseHandler PostResponse;
/// <summary>
/// Occurs before an HTML document is handled.
/// </summary>
public PreHandleDocumentHandler PreHandleDocument;
/// <summary>
/// Creates an instance of an HtmlWeb class.
/// </summary>
public HtmlWeb()
{
}
/// <summary>
/// Gets an HTML document from an Internet resource and saves it to the specified file.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="path">The location of the file where you want to save the document.</param>
public void Get(string url, string path)
{
Get(url, path, "GET");
}
/// <summary>
/// Gets an HTML document from an Internet resource and saves it to the specified file.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="path">The location of the file where you want to save the document.</param>
/// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param>
public void Get(string url, string path, string method)
{
Uri uri = new Uri(url);
if ((uri.Scheme == Uri.UriSchemeHttps) ||
(uri.Scheme == Uri.UriSchemeHttp))
{
Get(uri, method, path, null);
}
else
{
throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'.");
}
}
/// <summary>
/// Gets an HTML document from an Internet resource.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <returns>A new HTML document.</returns>
public HtmlDocument Load(string url)
{
return Load(url, "GET");
}
/// <summary>
/// Loads an HTML document from an Internet resource.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param>
/// <returns>A new HTML document.</returns>
public HtmlDocument Load(string url, string method)
{
Uri uri = new Uri(url);
HtmlDocument doc;
if ((uri.Scheme == Uri.UriSchemeHttps) ||
(uri.Scheme == Uri.UriSchemeHttp))
{
doc = LoadUrl(uri, method);
}
else
{
if (uri.Scheme == Uri.UriSchemeFile)
{
doc = new HtmlDocument();
doc.OptionAutoCloseOnEnd = false;
doc.OptionAutoCloseOnEnd = true;
doc.DetectEncodingAndLoad(url, _autoDetectEncoding);
}
else
{
throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'.");
}
}
if (PreHandleDocument != null)
{
PreHandleDocument(doc);
}
return doc;
}
private bool IsCacheHtmlContent(string path)
{
string ct = GetContentTypeForExtension(Path.GetExtension(path), null);
return IsHtmlContent(ct);
}
private bool IsHtmlContent(string contentType)
{
return contentType.ToLower().StartsWith("text/html");
}
private string GetCacheHeadersPath(Uri uri)
{
//return Path.Combine(GetCachePath(uri), ".h.xml");
return GetCachePath(uri) + ".h.xml";
}
/// <summary>
/// Gets the cache file path for a specified url.
/// </summary>
/// <param name="uri">The url fo which to retrieve the cache path. May not be null.</param>
/// <returns>The cache file path.</returns>
public string GetCachePath(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
if (!UsingCache)
{
throw new HtmlWebException("Cache is not enabled. Set UsingCache to true first.");
}
string cachePath;
if (uri.AbsolutePath == "/")
{
cachePath = Path.Combine(_cachePath, ".htm");
}
else
{
cachePath = Path.Combine(_cachePath, (uri.Host + uri.AbsolutePath).Replace('/', '\\'));
}
return cachePath;
}
/// <summary>
/// Gets a value indicating if the last document was retrieved from the cache.
/// </summary>
public bool FromCache
{
get
{
return _fromCache;
}
}
/// <summary>
/// Gets the URI of the Internet resource that actually responded to the request.
/// </summary>
public Uri ResponseUri
{
get
{
return _responseUri;
}
}
/// <summary>
/// Gets or Sets a value indicating whether to get document only from the cache.
/// If this is set to true and document is not found in the cache, nothing will be loaded.
/// </summary>
public bool CacheOnly
{
get
{
return _cacheOnly;
}
set
{
if ((value) && !UsingCache)
{
throw new HtmlWebException("Cache is not enabled. Set UsingCache to true first.");
}
_cacheOnly = value;
}
}
/// <summary>
/// Gets or Sets a value indicating if cookies will be stored.
/// </summary>
public bool UseCookies
{
get
{
return _useCookies;
}
set
{
_useCookies = value;
}
}
/// <summary>
/// Gets the last request duration in milliseconds.
/// </summary>
public int RequestDuration
{
get
{
return _requestDuration;
}
}
/// <summary>
/// Gets or Sets a value indicating if document encoding must be automatically detected.
/// </summary>
public bool AutoDetectEncoding
{
get
{
return _autoDetectEncoding;
}
set
{
_autoDetectEncoding = value;
}
}
/// <summary>
/// Gets the last request status.
/// </summary>
public HttpStatusCode StatusCode
{
get
{
return _statusCode;
}
}
/// <summary>
/// Gets or Sets the size of the buffer used for memory operations.
/// </summary>
public int StreamBufferSize
{
get
{
return _streamBufferSize;
}
set
{
if (_streamBufferSize <= 0)
{
throw new ArgumentException("Size must be greater than zero.");
}
_streamBufferSize = value;
}
}
private HtmlDocument LoadUrl(Uri uri, string method)
{
HtmlDocument doc = new HtmlDocument();
doc.OptionAutoCloseOnEnd = false;
doc.OptionFixNestedTags = true;
_statusCode = Get(uri, method, null, doc);
if (_statusCode == HttpStatusCode.NotModified)
{
// read cached encoding
doc.DetectEncodingAndLoad(GetCachePath(uri));
}
return doc;
}
private HttpStatusCode Get(Uri uri, string method, string path, HtmlDocument doc)
{
string cachePath = null;
HttpWebRequest req;
bool oldFile = false;
req = WebRequest.Create(uri) as HttpWebRequest;
req.Method = method;
_fromCache = false;
_requestDuration = 0;
int tc = Environment.TickCount;
if (UsingCache)
{
cachePath = GetCachePath(req.RequestUri);
if (File.Exists(cachePath))
{
req.IfModifiedSince = File.GetLastAccessTime(cachePath);
oldFile = true;
}
}
if (_cacheOnly)
{
if (!File.Exists(cachePath))
{
throw new HtmlWebException("File was not found at cache path: '" + cachePath + "'");
}
if (path != null)
{
IOLibrary.CopyAlways(cachePath, path);
// touch the file
File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath));
}
_fromCache = true;
return HttpStatusCode.NotModified;
}
if (_useCookies)
{
req.CookieContainer = new CookieContainer();
}
if (PreRequest != null)
{
// allow our user to change the request at will
if (!PreRequest(req))
{
return HttpStatusCode.ResetContent;
}
// dump cookie
// if (_useCookies)
// {
// foreach(Cookie cookie in req.CookieContainer.GetCookies(req.RequestUri))
// {
// HtmlLibrary.Trace("Cookie " + cookie.Name + "=" + cookie.Value + " path=" + cookie.Path + " domain=" + cookie.Domain);
// }
// }
}
HttpWebResponse resp;
try
{
resp = req.GetResponse() as HttpWebResponse;
}
catch (WebException we)
{
_requestDuration = Environment.TickCount - tc;
resp = (HttpWebResponse)we.Response;
if (resp == null)
{
if (oldFile)
{
if (path != null)
{
IOLibrary.CopyAlways(cachePath, path);
// touch the file
File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath));
}
return HttpStatusCode.NotModified;
}
throw;
}
}
catch(Exception)
{
_requestDuration = Environment.TickCount - tc;
throw;
}
// allow our user to get some info from the response
if (PostResponse != null)
{
PostResponse(req, resp);
}
_requestDuration = Environment.TickCount - tc;
_responseUri = resp.ResponseUri;
bool html = IsHtmlContent(resp.ContentType);
System.Text.Encoding respenc;
if ((resp.ContentEncoding != null) && (resp.ContentEncoding.Length>0))
{
respenc = System.Text.Encoding.GetEncoding(resp.ContentEncoding);
}
else
{
respenc = null;
}
if (resp.StatusCode == HttpStatusCode.NotModified)
{
if (UsingCache)
{
_fromCache = true;
if (path != null)
{
IOLibrary.CopyAlways(cachePath, path);
// touch the file
File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath));
}
return resp.StatusCode;
}
else
{
// this should *never* happen...
throw new HtmlWebException("Server has send a NotModifed code, without cache enabled.");
}
}
Stream s = resp.GetResponseStream();
if (s != null)
{
if (UsingCache)
{
// NOTE: LastModified does not contain milliseconds, so we remove them to the file
SaveStream(s, cachePath, RemoveMilliseconds(resp.LastModified), _streamBufferSize);
// save headers
SaveCacheHeaders(req.RequestUri, resp);
if (path != null)
{
// copy and touch the file
IOLibrary.CopyAlways(cachePath, path);
File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath));
}
}
else
{
// try to work in-memory
if ((doc != null) && (html))
{
if (respenc != null)
{
doc.Load(s, respenc);
}
else
{
doc.Load(s, true);
}
}
}
resp.Close();
}
return resp.StatusCode;
}
private string GetCacheHeader(Uri requestUri, string name, string def)
{
// note: some headers are collection (ex: www-authenticate)
// we don't handle that here
XmlDocument doc = new XmlDocument();
doc.Load(GetCacheHeadersPath(requestUri));
XmlNode node = doc.SelectSingleNode("//h[translate(@n, 'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')='" + name.ToUpper() + "']");
if (node == null)
{
return def;
}
// attribute should exist
return node.Attributes[name].Value;
}
private void SaveCacheHeaders(Uri requestUri, HttpWebResponse resp)
{
// we cache the original headers aside the cached document.
string file = GetCacheHeadersPath(requestUri);
XmlDocument doc = new XmlDocument();
doc.LoadXml("<c></c>");
XmlNode cache = doc.FirstChild;
foreach(string header in resp.Headers)
{
XmlNode entry = doc.CreateElement("h");
XmlAttribute att = doc.CreateAttribute("n");
att.Value = header;
entry.Attributes.Append(att);
att = doc.CreateAttribute("v");
att.Value = resp.Headers[header];
entry.Attributes.Append(att);
cache.AppendChild(entry);
}
doc.Save(file);
}
private static long SaveStream(Stream stream, string path, DateTime touchDate, int streamBufferSize)
{
FilePreparePath(path);
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryReader br = null;
BinaryWriter bw = null;
long len;
try
{
br = new BinaryReader(stream);
bw = new BinaryWriter(fs);
len = 0;
byte[] buffer;
do
{
buffer = br.ReadBytes(streamBufferSize);
len += buffer.Length;
if (buffer.Length>0)
{
bw.Write(buffer);
}
}
while (buffer.Length>0);
}
finally
{
if (br != null)
{
br.Close();
}
if (bw != null)
{
bw.Flush();
bw.Close();
}
if (fs != null)
{
fs.Close();
}
}
File.SetLastWriteTime(path, touchDate);
return len;
}
private static void FilePreparePath(string target)
{
if (File.Exists(target))
{
FileAttributes atts = File.GetAttributes(target);
File.SetAttributes(target, atts & ~FileAttributes.ReadOnly);
}
else
{
string dir = Path.GetDirectoryName(target);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
}
private static DateTime RemoveMilliseconds(DateTime t)
{
return new DateTime(t.Year, t.Month, t.Day, t.Hour, t.Minute, t.Second, 0);
}
/// <summary>
/// Gets the path extension for a given MIME content type.
/// </summary>
/// <param name="contentType">The input MIME content type.</param>
/// <param name="def">The default path extension to return if any error occurs.</param>
/// <returns>The MIME content type's path extension.</returns>
public static string GetExtensionForContentType(string contentType, string def)
{
if ((contentType == null) || (contentType.Length == 0))
{
return def;
}
string ext;
try
{
RegistryKey reg = Registry.ClassesRoot;
reg = reg.OpenSubKey(@"MIME\Database\Content Type\" + contentType, false);
ext = (string)reg.GetValue("Extension", def);
}
catch(Exception)
{
ext = def;
}
return ext;
}
/// <summary>
/// Gets the MIME content type for a given path extension.
/// </summary>
/// <param name="extension">The input path extension.</param>
/// <param name="def">The default content type to return if any error occurs.</param>
/// <returns>The path extention's MIME content type.</returns>
public static string GetContentTypeForExtension(string extension, string def)
{
if ((extension == null) || (extension.Length == 0))
{
return def;
}
string contentType;
try
{
RegistryKey reg = Registry.ClassesRoot;
reg = reg.OpenSubKey(extension, false);
contentType = (string)reg.GetValue("", def);
}
catch(Exception)
{
contentType = def;
}
return contentType;
}
/// <summary>
/// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter.
/// </summary>
/// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="writer">The XmlTextWriter to which you want to save.</param>
public void LoadHtmlAsXml(string htmlUrl, XmlTextWriter writer)
{
HtmlDocument doc = Load(htmlUrl);
doc.Save(writer);
}
/// <summary>
/// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter, after an XSLT transformation.
/// </summary>
/// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
/// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param>
/// <param name="writer">The XmlTextWriter to which you want to save.</param>
public void LoadHtmlAsXml(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, XmlTextWriter writer)
{
LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, null);
}
/// <summary>
/// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter, after an XSLT transformation.
/// </summary>
/// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp". May not be null.</param>
/// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
/// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param>
/// <param name="writer">The XmlTextWriter to which you want to save.</param>
/// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param>
public void LoadHtmlAsXml(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, XmlTextWriter writer, string xmlPath)
{
if (htmlUrl == null)
{
throw new ArgumentNullException("htmlUrl");
}
HtmlDocument doc = Load(htmlUrl);
if (xmlPath != null)
{
XmlTextWriter w = new XmlTextWriter(xmlPath, doc.Encoding);
doc.Save(w);
w.Close();
}
if (xsltArgs == null)
{
xsltArgs = new XsltArgumentList();
}
// add some useful variables to the xslt doc
xsltArgs.AddParam("url", "", htmlUrl);
xsltArgs.AddParam("requestDuration", "", RequestDuration);
xsltArgs.AddParam("fromCache", "", FromCache);
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xsltUrl);
xslt.Transform(doc, xsltArgs, writer);
}
/// <summary>
/// Creates an instance of the given type from the specified Internet resource.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="type">The requested type.</param>
/// <returns>An newly created instance.</returns>
public object CreateInstance(string url, Type type)
{
return CreateInstance(url, null, null, type);
}
/// <summary>
/// Creates an instance of the given type from the specified Internet resource.
/// </summary>
/// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
/// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param>
/// <param name="type">The requested type.</param>
/// <returns>An newly created instance.</returns>
public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type)
{
return CreateInstance(htmlUrl, xsltUrl, xsltArgs, type, null);
}
/// <summary>
/// Creates an instance of the given type from the specified Internet resource.
/// </summary>
/// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
/// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param>
/// <param name="type">The requested type.</param>
/// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param>
/// <returns>An newly created instance.</returns>
public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type, string xmlPath)
{
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
if (xsltUrl == null)
{
LoadHtmlAsXml(htmlUrl, writer);
}
else
{
if (xmlPath == null)
{
LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer);
}
else
{
LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, xmlPath);
}
}
writer.Flush();
StringReader sr = new StringReader(sw.ToString());
XmlTextReader reader = new XmlTextReader(sr);
XmlSerializer serializer = new XmlSerializer(type);
object o = null;
try
{
o = serializer.Deserialize(reader);
}
catch(InvalidOperationException ex)
{
throw new Exception(ex.ToString() + ", --- xml:" + sw.ToString());
}
return o;
}
/// <summary>
/// Gets or Sets the cache path. If null, no caching mechanism will be used.
/// </summary>
public string CachePath
{
get
{
return _cachePath;
}
set
{
_cachePath = value;
}
}
/// <summary>
/// Gets or Sets a value indicating whether the caching mechanisms should be used or not.
/// </summary>
public bool UsingCache
{
get
{
if (_cachePath == null)
{
return false;
}
return _usingCache;
}
set
{
if ((value) && (_cachePath == null))
{
throw new HtmlWebException("You need to define a CachePath first.");
}
_usingCache = value;
}
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.10.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google Analytics API Version v2.4
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/analytics/'>Google Analytics API</a>
* <tr><th>API Version<td>v2.4
* <tr><th>API Rev<td>20160308 (432)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/analytics/'>
* https://developers.google.com/analytics/</a>
* <tr><th>Discovery Name<td>analytics
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google Analytics API can be found at
* <a href='https://developers.google.com/analytics/'>https://developers.google.com/analytics/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Analytics.v2_4
{
/// <summary>The Analytics Service.</summary>
public class AnalyticsService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v2.4";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public AnalyticsService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public AnalyticsService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
data = new DataResource(this);
management = new ManagementResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "analytics"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/analytics/v2.4/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "analytics/v2.4/"; }
}
/// <summary>Available OAuth 2.0 scopes for use with the Google Analytics API.</summary>
public class Scope
{
/// <summary>View and manage your Google Analytics data</summary>
public static string Analytics = "https://www.googleapis.com/auth/analytics";
/// <summary>View your Google Analytics data</summary>
public static string AnalyticsReadonly = "https://www.googleapis.com/auth/analytics.readonly";
}
private readonly DataResource data;
/// <summary>Gets the Data resource.</summary>
public virtual DataResource Data
{
get { return data; }
}
private readonly ManagementResource management;
/// <summary>Gets the Management resource.</summary>
public virtual ManagementResource Management
{
get { return management; }
}
}
///<summary>A base abstract class for Analytics requests.</summary>
public abstract class AnalyticsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new AnalyticsBaseServiceRequest instance.</summary>
protected AnalyticsBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: atom]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/atom+xml</summary>
[Google.Apis.Util.StringValueAttribute("atom")]
Atom,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: false]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes Analytics parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "atom",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "false",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "data" collection of methods.</summary>
public class DataResource
{
private const string Resource = "data";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public DataResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Returns Analytics report data for a view (profile).</summary>
/// <param name="ids">Unique table ID for retrieving report data. Table ID is of the form ga:XXXX, where XXXX is the
/// Analytics view (profile) ID.</param>
/// <param name="startDate">Start date for fetching report data. All
/// requests should specify a start date formatted as YYYY-MM-DD.</param>
/// <param name="endDate">End date for
/// fetching report data. All requests should specify an end date formatted as YYYY-MM-DD.</param>
/// <param
/// name="metrics">A comma-separated list of Analytics metrics. E.g., 'ga:sessions,ga:pageviews'. At least one metric
/// must be specified to retrieve a valid Analytics report.</param>
public virtual GetRequest Get(string ids, string startDate, string endDate, string metrics)
{
return new GetRequest(service, ids, startDate, endDate, metrics);
}
/// <summary>Returns Analytics report data for a view (profile).</summary>
public class GetRequest : AnalyticsBaseServiceRequest<string>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string ids, string startDate, string endDate, string metrics)
: base(service)
{
Ids = ids;
StartDate = startDate;
EndDate = endDate;
Metrics = metrics;
InitParameters();
}
/// <summary>Unique table ID for retrieving report data. Table ID is of the form ga:XXXX, where XXXX is the
/// Analytics view (profile) ID.</summary>
[Google.Apis.Util.RequestParameterAttribute("ids", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Ids { get; private set; }
/// <summary>Start date for fetching report data. All requests should specify a start date formatted as
/// YYYY-MM-DD.</summary>
[Google.Apis.Util.RequestParameterAttribute("start-date", Google.Apis.Util.RequestParameterType.Query)]
public virtual string StartDate { get; private set; }
/// <summary>End date for fetching report data. All requests should specify an end date formatted as YYYY-
/// MM-DD.</summary>
[Google.Apis.Util.RequestParameterAttribute("end-date", Google.Apis.Util.RequestParameterType.Query)]
public virtual string EndDate { get; private set; }
/// <summary>A comma-separated list of Analytics metrics. E.g., 'ga:sessions,ga:pageviews'. At least one
/// metric must be specified to retrieve a valid Analytics report.</summary>
[Google.Apis.Util.RequestParameterAttribute("metrics", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Metrics { get; private set; }
/// <summary>A comma-separated list of Analytics dimensions. E.g., 'ga:browser,ga:city'.</summary>
[Google.Apis.Util.RequestParameterAttribute("dimensions", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Dimensions { get; set; }
/// <summary>A comma-separated list of dimension or metric filters to be applied to the report
/// data.</summary>
[Google.Apis.Util.RequestParameterAttribute("filters", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filters { get; set; }
/// <summary>The maximum number of entries to include in this feed.</summary>
[Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>An Analytics advanced segment to be applied to the report data.</summary>
[Google.Apis.Util.RequestParameterAttribute("segment", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Segment { get; set; }
/// <summary>A comma-separated list of dimensions or metrics that determine the sort order for the report
/// data.</summary>
[Google.Apis.Util.RequestParameterAttribute("sort", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Sort { get; set; }
/// <summary>An index of the first entity to retrieve. Use this parameter as a pagination mechanism along
/// with the max-results parameter.</summary>
/// [minimum: 1]
[Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> StartIndex { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "data"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"ids", new Google.Apis.Discovery.Parameter
{
Name = "ids",
IsRequired = true,
ParameterType = "query",
DefaultValue = null,
Pattern = @"ga:[0-9]+",
});
RequestParameters.Add(
"start-date", new Google.Apis.Discovery.Parameter
{
Name = "start-date",
IsRequired = true,
ParameterType = "query",
DefaultValue = null,
Pattern = @"[0-9]{4}-[0-9]{2}-[0-9]{2}",
});
RequestParameters.Add(
"end-date", new Google.Apis.Discovery.Parameter
{
Name = "end-date",
IsRequired = true,
ParameterType = "query",
DefaultValue = null,
Pattern = @"[0-9]{4}-[0-9]{2}-[0-9]{2}",
});
RequestParameters.Add(
"metrics", new Google.Apis.Discovery.Parameter
{
Name = "metrics",
IsRequired = true,
ParameterType = "query",
DefaultValue = null,
Pattern = @"ga:.+",
});
RequestParameters.Add(
"dimensions", new Google.Apis.Discovery.Parameter
{
Name = "dimensions",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(ga:.+)?",
});
RequestParameters.Add(
"filters", new Google.Apis.Discovery.Parameter
{
Name = "filters",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"ga:.+",
});
RequestParameters.Add(
"max-results", new Google.Apis.Discovery.Parameter
{
Name = "max-results",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"segment", new Google.Apis.Discovery.Parameter
{
Name = "segment",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"sort", new Google.Apis.Discovery.Parameter
{
Name = "sort",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(-)?ga:.+",
});
RequestParameters.Add(
"start-index", new Google.Apis.Discovery.Parameter
{
Name = "start-index",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>The "management" collection of methods.</summary>
public class ManagementResource
{
private const string Resource = "management";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ManagementResource(Google.Apis.Services.IClientService service)
{
this.service = service;
accounts = new AccountsResource(service);
goals = new GoalsResource(service);
profiles = new ProfilesResource(service);
segments = new SegmentsResource(service);
webproperties = new WebpropertiesResource(service);
}
private readonly AccountsResource accounts;
/// <summary>Gets the Accounts resource.</summary>
public virtual AccountsResource Accounts
{
get { return accounts; }
}
/// <summary>The "accounts" collection of methods.</summary>
public class AccountsResource
{
private const string Resource = "accounts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public AccountsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Lists all accounts to which the user has access.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists all accounts to which the user has access.</summary>
public class ListRequest : AnalyticsBaseServiceRequest<string>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The maximum number of accounts to include in this response.</summary>
[Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>An index of the first account to retrieve. Use this parameter as a pagination mechanism
/// along with the max-results parameter.</summary>
/// [minimum: 1]
[Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> StartIndex { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "management/accounts"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"max-results", new Google.Apis.Discovery.Parameter
{
Name = "max-results",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"start-index", new Google.Apis.Discovery.Parameter
{
Name = "start-index",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly GoalsResource goals;
/// <summary>Gets the Goals resource.</summary>
public virtual GoalsResource Goals
{
get { return goals; }
}
/// <summary>The "goals" collection of methods.</summary>
public class GoalsResource
{
private const string Resource = "goals";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public GoalsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Lists goals to which the user has access.</summary>
/// <param name="accountId">Account ID to retrieve goals for. Can either be a specific account ID or '~all', which
/// refers to all the accounts that user has access to.</param>
/// <param name="webPropertyId">Web property ID to
/// retrieve goals for. Can either be a specific web property ID or '~all', which refers to all the web properties that
/// user has access to.</param>
/// <param name="profileId">View (Profile) ID to retrieve goals for. Can either be a
/// specific view (profile) ID or '~all', which refers to all the views (profiles) that user has access to.</param>
public virtual ListRequest List(string accountId, string webPropertyId, string profileId)
{
return new ListRequest(service, accountId, webPropertyId, profileId);
}
/// <summary>Lists goals to which the user has access.</summary>
public class ListRequest : AnalyticsBaseServiceRequest<string>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId, string webPropertyId, string profileId)
: base(service)
{
AccountId = accountId;
WebPropertyId = webPropertyId;
ProfileId = profileId;
InitParameters();
}
/// <summary>Account ID to retrieve goals for. Can either be a specific account ID or '~all', which
/// refers to all the accounts that user has access to.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>Web property ID to retrieve goals for. Can either be a specific web property ID or '~all',
/// which refers to all the web properties that user has access to.</summary>
[Google.Apis.Util.RequestParameterAttribute("webPropertyId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string WebPropertyId { get; private set; }
/// <summary>View (Profile) ID to retrieve goals for. Can either be a specific view (profile) ID or
/// '~all', which refers to all the views (profiles) that user has access to.</summary>
[Google.Apis.Util.RequestParameterAttribute("profileId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProfileId { get; private set; }
/// <summary>The maximum number of goals to include in this response.</summary>
[Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>An index of the first goal to retrieve. Use this parameter as a pagination mechanism along
/// with the max-results parameter.</summary>
/// [minimum: 1]
[Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> StartIndex { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"webPropertyId", new Google.Apis.Discovery.Parameter
{
Name = "webPropertyId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"profileId", new Google.Apis.Discovery.Parameter
{
Name = "profileId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"max-results", new Google.Apis.Discovery.Parameter
{
Name = "max-results",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"start-index", new Google.Apis.Discovery.Parameter
{
Name = "start-index",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly ProfilesResource profiles;
/// <summary>Gets the Profiles resource.</summary>
public virtual ProfilesResource Profiles
{
get { return profiles; }
}
/// <summary>The "profiles" collection of methods.</summary>
public class ProfilesResource
{
private const string Resource = "profiles";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProfilesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Lists views (profiles) to which the user has access.</summary>
/// <param name="accountId">Account ID for the views (profiles) to retrieve. Can either be a specific account ID or
/// '~all', which refers to all the accounts to which the user has access.</param>
/// <param
/// name="webPropertyId">Web property ID for the views (profiles) to retrieve. Can either be a specific web property ID
/// or '~all', which refers to all the web properties to which the user has access.</param>
public virtual ListRequest List(string accountId, string webPropertyId)
{
return new ListRequest(service, accountId, webPropertyId);
}
/// <summary>Lists views (profiles) to which the user has access.</summary>
public class ListRequest : AnalyticsBaseServiceRequest<string>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId, string webPropertyId)
: base(service)
{
AccountId = accountId;
WebPropertyId = webPropertyId;
InitParameters();
}
/// <summary>Account ID for the views (profiles) to retrieve. Can either be a specific account ID or
/// '~all', which refers to all the accounts to which the user has access.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>Web property ID for the views (profiles) to retrieve. Can either be a specific web property
/// ID or '~all', which refers to all the web properties to which the user has access.</summary>
[Google.Apis.Util.RequestParameterAttribute("webPropertyId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string WebPropertyId { get; private set; }
/// <summary>The maximum number of views (profiles) to include in this response.</summary>
[Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>An index of the first entity to retrieve. Use this parameter as a pagination mechanism
/// along with the max-results parameter.</summary>
/// [minimum: 1]
[Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> StartIndex { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"webPropertyId", new Google.Apis.Discovery.Parameter
{
Name = "webPropertyId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"max-results", new Google.Apis.Discovery.Parameter
{
Name = "max-results",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"start-index", new Google.Apis.Discovery.Parameter
{
Name = "start-index",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly SegmentsResource segments;
/// <summary>Gets the Segments resource.</summary>
public virtual SegmentsResource Segments
{
get { return segments; }
}
/// <summary>The "segments" collection of methods.</summary>
public class SegmentsResource
{
private const string Resource = "segments";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public SegmentsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Lists advanced segments to which the user has access.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists advanced segments to which the user has access.</summary>
public class ListRequest : AnalyticsBaseServiceRequest<string>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The maximum number of advanced segments to include in this response.</summary>
[Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>An index of the first advanced segment to retrieve. Use this parameter as a pagination
/// mechanism along with the max-results parameter.</summary>
/// [minimum: 1]
[Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> StartIndex { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "management/segments"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"max-results", new Google.Apis.Discovery.Parameter
{
Name = "max-results",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"start-index", new Google.Apis.Discovery.Parameter
{
Name = "start-index",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly WebpropertiesResource webproperties;
/// <summary>Gets the Webproperties resource.</summary>
public virtual WebpropertiesResource Webproperties
{
get { return webproperties; }
}
/// <summary>The "webproperties" collection of methods.</summary>
public class WebpropertiesResource
{
private const string Resource = "webproperties";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public WebpropertiesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Lists web properties to which the user has access.</summary>
/// <param name="accountId">Account ID to retrieve web properties for. Can either be a specific account ID or '~all',
/// which refers to all the accounts that user has access to.</param>
public virtual ListRequest List(string accountId)
{
return new ListRequest(service, accountId);
}
/// <summary>Lists web properties to which the user has access.</summary>
public class ListRequest : AnalyticsBaseServiceRequest<string>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId)
: base(service)
{
AccountId = accountId;
InitParameters();
}
/// <summary>Account ID to retrieve web properties for. Can either be a specific account ID or '~all',
/// which refers to all the accounts that user has access to.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>The maximum number of web properties to include in this response.</summary>
[Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>An index of the first entity to retrieve. Use this parameter as a pagination mechanism
/// along with the max-results parameter.</summary>
/// [minimum: 1]
[Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> StartIndex { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "management/accounts/{accountId}/webproperties"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"max-results", new Google.Apis.Discovery.Parameter
{
Name = "max-results",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"start-index", new Google.Apis.Discovery.Parameter
{
Name = "start-index",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
}
namespace Google.Apis.Analytics.v2_4.Data
{
}
| |
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 BullsAndCows.Web.Api.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;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Orleans.Utilities
{
/// <summary>
/// A thread-safe dictionary for read-heavy workloads.
/// </summary>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
internal class CachedReadConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
/// <summary>
/// The number of cache misses which are tolerated before the cache is regenerated.
/// </summary>
private const int CacheMissesBeforeCaching = 10;
private readonly ConcurrentDictionary<TKey, TValue> dictionary;
private readonly IEqualityComparer<TKey> comparer;
/// <summary>
/// Approximate number of reads which did not hit the cache since it was last invalidated.
/// This is used as a heuristic that the dictionary is not being modified frequently with respect to the read volume.
/// </summary>
private int cacheMissReads;
/// <summary>
/// Cached version of <see cref="dictionary"/>.
/// </summary>
private Dictionary<TKey, TValue> readCache;
/// <summary>
/// Initializes a new instance of the <see cref="CachedReadConcurrentDictionary{TKey,TValue}"/> class.
/// </summary>
public CachedReadConcurrentDictionary()
{
this.dictionary = new ConcurrentDictionary<TKey, TValue>();
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedReadConcurrentDictionary{TKey,TValue}"/> class
/// that contains elements copied from the specified collection.
/// </summary>
/// <param name="collection">
/// The <see cref="T:IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to the new instance.
/// </param>
public CachedReadConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection)
{
this.dictionary = new ConcurrentDictionary<TKey, TValue>(collection);
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedReadConcurrentDictionary{TKey,TValue}"/> class
/// that contains elements copied from the specified collection and uses the specified
/// <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="comparer">
/// The <see cref="IEqualityComparer{TKey}"/> implementation to use when comparing keys.
/// </param>
public CachedReadConcurrentDictionary(IEqualityComparer<TKey> comparer)
{
this.comparer = comparer;
this.dictionary = new ConcurrentDictionary<TKey, TValue>(comparer);
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedReadConcurrentDictionary{TKey,TValue}"/>
/// class that contains elements copied from the specified collection and uses the specified
/// <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="collection">
/// The <see cref="T:IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to the new instance.
/// </param>
/// <param name="comparer">
/// The <see cref="IEqualityComparer{TKey}"/> implementation to use when comparing keys.
/// </param>
public CachedReadConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer)
{
this.comparer = comparer;
this.dictionary = new ConcurrentDictionary<TKey, TValue>(collection, comparer);
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
/// <inheritdoc />
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => this.GetReadDictionary().GetEnumerator();
/// <inheritdoc />
public void Add(KeyValuePair<TKey, TValue> item)
{
((IDictionary<TKey, TValue>) this.dictionary).Add(item);
this.InvalidateCache();
}
/// <inheritdoc />
public void Clear()
{
this.dictionary.Clear();
this.InvalidateCache();
}
/// <inheritdoc />
public bool Contains(KeyValuePair<TKey, TValue> item) => this.GetReadDictionary().Contains(item);
/// <inheritdoc />
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
this.GetReadDictionary().CopyTo(array, arrayIndex);
}
/// <inheritdoc />
public bool Remove(KeyValuePair<TKey, TValue> item)
{
var result = ((IDictionary<TKey, TValue>) this.dictionary).Remove(item);
if (result) this.InvalidateCache();
return result;
}
/// <inheritdoc />
public int Count => this.GetReadDictionary().Count;
/// <inheritdoc />
public bool IsReadOnly => false;
/// <inheritdoc />
public void Add(TKey key, TValue value)
{
((IDictionary<TKey, TValue>) this.dictionary).Add(key, value);
this.InvalidateCache();
}
/// <summary>
/// Adds a key/value pair to the <see cref="CachedReadConcurrentDictionary{TKey,TValue}"/> if the key does not exist.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="valueFactory">The function used to generate a value for the key</param>
/// <returns>The value for the key. This will be either the existing value for the key if the key is already in the dictionary, or the new value if the key was not in the dictionary.</returns>
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
TValue value;
if (this.GetReadDictionary().TryGetValue(key, out value))
return value;
value = this.dictionary.GetOrAdd(key, valueFactory);
InvalidateCache();
return value;
}
/// <summary>
/// Attempts to add the specified key and value.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add. The value can be a null reference (Nothing
/// in Visual Basic) for reference types.</param>
/// <returns>true if the key/value pair was added successfully; otherwise, false.</returns>
public bool TryAdd(TKey key, TValue value)
{
if (this.dictionary.TryAdd(key, value))
{
this.InvalidateCache();
return true;
}
return false;
}
/// <inheritdoc />
public bool ContainsKey(TKey key) => this.GetReadDictionary().ContainsKey(key);
/// <inheritdoc />
public bool Remove(TKey key)
{
var result = ((IDictionary<TKey, TValue>) this.dictionary).Remove(key);
if (result) this.InvalidateCache();
return result;
}
/// <inheritdoc />
public bool TryGetValue(TKey key, out TValue value) => this.GetReadDictionary().TryGetValue(key, out value);
/// <inheritdoc />
public TValue this[TKey key]
{
get { return this.GetReadDictionary()[key]; }
set
{
this.dictionary[key] = value;
this.InvalidateCache();
}
}
/// <inheritdoc />
public ICollection<TKey> Keys => this.GetReadDictionary().Keys;
/// <inheritdoc />
public ICollection<TValue> Values => this.GetReadDictionary().Values;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private IDictionary<TKey, TValue> GetReadDictionary() => this.readCache ?? this.GetWithoutCache();
private IDictionary<TKey, TValue> GetWithoutCache()
{
// If the dictionary was recently modified or the cache is being recomputed, return the dictionary directly.
if (Interlocked.Increment(ref this.cacheMissReads) < CacheMissesBeforeCaching) return this.dictionary;
// Recompute the cache if too many cache misses have occurred.
this.cacheMissReads = 0;
return this.readCache = new Dictionary<TKey, TValue>(this.dictionary, this.comparer);
}
private void InvalidateCache()
{
this.cacheMissReads = 0;
this.readCache = null;
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.IO;
using System.Collections;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Stats;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Caching.AutoExpiration;
using Alachisoft.NCache.Caching.EvictionPolicies;
using Alachisoft.NCache.Common.Monitoring;
using Alachisoft.NCache.Runtime;
using System.Collections.Generic;
using Alachisoft.NCache.Common.Protobuf;
using Alachisoft.NCache.SocketServer.Pooling;
using Alachisoft.NCache.Common.Pooling;
using Runtime = Alachisoft.NCache.Runtime;
using Alachisoft.NCache.Common.Locking;
using Alachisoft.NCache.Runtime.Events;
using Alachisoft.NCache.Common.Caching;
namespace Alachisoft.NCache.SocketServer.Command
{
class AddAndInsertCommandBase : CommandBase
{
//public static StreamWriter writer = new StreamWriter("c:\\ServerPerf.log.txt");
//public static HPTimeStats ts = new HPTimeStats();
private readonly BitSet _bitSet;
private readonly PriorityEvictionHint _priorityEvictionHint;
protected struct CommandInfo
{
public bool DoAsync;
public int DataFormatValue;
public long RequestId;
public string Key;
public string Group;
public string SubGroup;
public string Type;
public string ProviderName;
public string ResyncProviderName;
public BitSet Flag;
public object LockId;
public LockAccessType LockAccessType;
public ExpirationHint ExpirationHint;
public PriorityEvictionHint EvictionHint;
public short RemoveCallbackId;
public short UpdateCallbackId;
public short DsItemAddedCallbackId;
public Hashtable queryInfo;
public ulong ItemVersion;
public object value;
public EventDataFilter UpdateDataFilter;
public EventDataFilter RemoveDataFilter;
public string ClientID;
public int CallbackType;
}
internal static string NC_NULL_VAL = "NLV";
protected string serializationContext;
public override bool CanHaveLargedata
{
get
{
return true;
}
}
public AddAndInsertCommandBase()
{
_bitSet = new BitSet();
_priorityEvictionHint = new PriorityEvictionHint();
}
public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
{
}
//public override void ExecuteCommand(ClientManager clientManager, string command, byte[] data)
//{
//}
//PROTOBUF
protected virtual CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager, string cacheId)
{
//if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("AddInsertCmd.Parse", "enter");
CommandInfo cmdInfo = new CommandInfo();
Hashtable queryInfoHashtable = null;
Hashtable tagHashtable = null;
Hashtable namedTagHashtable = null;
string version = string.Empty;
NCache nCache = clientManager.CmdExecuter as NCache;
Caching.Cache cache = nCache.Cache;
switch (command.type)
{
case Alachisoft.NCache.Common.Protobuf.Command.Type.ADD:
Alachisoft.NCache.Common.Protobuf.AddCommand addCommand = command.addCommand;
if (clientManager.ClientVersion < 5000 && !clientManager.CreateEventSubscription)
{
if (addCommand.removeCallbackId != -1 || addCommand.updateCallbackId != -1)
{
Util.EventHelper.SubscribeEvents(clientManager.ClientID, TopicConstant.ItemLevelEventsTopic, nCache, null);
clientManager.CreateEventSubscription = true;
}
}
cmdInfo.Key = clientManager.CacheTransactionalPool.StringPool.GetString(addCommand.key);
cmdInfo.DoAsync = addCommand.isAsync;
cmdInfo.DsItemAddedCallbackId = (short)addCommand.datasourceItemAddedCallbackId;
cmdInfo.EvictionHint = _priorityEvictionHint;
cmdInfo.EvictionHint.Priority = (CacheItemPriority)addCommand.priority;
cmdInfo.ExpirationHint = Alachisoft.NCache.Caching.Util.ProtobufHelper.GetExpirationHintObj(clientManager.CacheTransactionalPool, null, addCommand.absExpiration, addCommand.sldExpiration, addCommand.isResync, serializationContext);
BitSet bitset = _bitSet;
bitset.Data =((byte)addCommand.flag);
cmdInfo.Flag = bitset;
cmdInfo.ProviderName = addCommand.providerName.Length == 0 ? null : addCommand.providerName;
cmdInfo.queryInfo = new Hashtable();
cmdInfo.ClientID = addCommand.clientID;
version = command.version;
if (queryInfoHashtable != null)
{
if (cmdInfo.queryInfo == null) cmdInfo.queryInfo = new Hashtable();
cmdInfo.queryInfo.Add("query-info", queryInfoHashtable);
}
cmdInfo.RemoveCallbackId = (short)addCommand.removeCallbackId;
//for old clients data fitler information will be missing
if (addCommand.removeDataFilter != -1)
cmdInfo.RemoveDataFilter = (EventDataFilter)addCommand.removeDataFilter;
else
cmdInfo.RemoveDataFilter = Runtime.Events.EventDataFilter.None;
cmdInfo.RequestId = addCommand.requestId;
cmdInfo.ResyncProviderName = addCommand.resyncProviderName.Length == 0 ? null : addCommand.resyncProviderName;
if (addCommand.subGroup != null) cmdInfo.SubGroup = addCommand.subGroup.Length == 0 ? null : addCommand.subGroup;
cmdInfo.UpdateCallbackId = (short)addCommand.updateCallbackId;
if (addCommand.updateDataFilter != -1)
{
cmdInfo.UpdateDataFilter = (EventDataFilter)addCommand.updateDataFilter;
}
else
cmdInfo.UpdateDataFilter = (int)Runtime.Events.EventDataFilter.None;
cmdInfo.value = cache.SocketServerDataService.GetCacheData(addCommand.data.ToArray(), cmdInfo.Flag);
try
{
for (int count = 0; count < addCommand.data.Count; count++)
{
cmdInfo.DataFormatValue = cmdInfo.DataFormatValue + addCommand.data[count].Length;
}
}
catch
{
}
break;
case Alachisoft.NCache.Common.Protobuf.Command.Type.INSERT:
Alachisoft.NCache.Common.Protobuf.InsertCommand insertCommand = command.insertCommand;
if (clientManager.ClientVersion < 5000 && !clientManager.CreateEventSubscription)
{
if (insertCommand.removeCallbackId != -1 || insertCommand.updateCallbackId != -1)
{
Util.EventHelper.SubscribeEvents(clientManager.ClientID, TopicConstant.ItemLevelEventsTopic, nCache, null);
clientManager.CreateEventSubscription = true;
}
}
cmdInfo.Key = clientManager.CacheTransactionalPool.StringPool.GetString(insertCommand.key);
cmdInfo.DoAsync = insertCommand.isAsync;
cmdInfo.DsItemAddedCallbackId = (short)insertCommand.datasourceUpdatedCallbackId;
cmdInfo.EvictionHint = _priorityEvictionHint;
cmdInfo.EvictionHint.Priority = (CacheItemPriority)insertCommand.priority;
cmdInfo.ExpirationHint = Alachisoft.NCache.Caching.Util.ProtobufHelper.GetExpirationHintObj(clientManager.CacheTransactionalPool, null, insertCommand.absExpiration, insertCommand.sldExpiration, insertCommand.isResync, serializationContext);
bitset = _bitSet;
bitset.Data =((byte)insertCommand.flag);
cmdInfo.Flag = bitset;
cmdInfo.ProviderName = insertCommand.providerName.Length == 0 ? null : insertCommand.providerName;
cmdInfo.ClientID = insertCommand.clientID;
cmdInfo.CallbackType = insertCommand.CallbackType;
version = command.version;
//version added in 4.2 [Dated: 18-Nov-2013; Author: Sami]
if (tagHashtable != null)
{
if (cmdInfo.queryInfo == null) cmdInfo.queryInfo = new Hashtable();
cmdInfo.queryInfo.Add("tag-info", tagHashtable);
}
cmdInfo.RemoveCallbackId = (short)insertCommand.removeCallbackId;
if (insertCommand.removeDataFilter != -1)
cmdInfo.RemoveDataFilter = (EventDataFilter)insertCommand.removeDataFilter ;
else
cmdInfo.RemoveDataFilter = Runtime.Events.EventDataFilter.None;
cmdInfo.RequestId = insertCommand.requestId;
cmdInfo.ResyncProviderName = insertCommand.resyncProviderName.Length == 0 ? null : insertCommand.resyncProviderName;
cmdInfo.UpdateCallbackId = (short)insertCommand.updateCallbackId;
if (insertCommand.updateDataFilter != -1)
cmdInfo.UpdateDataFilter = (EventDataFilter)insertCommand.updateDataFilter ;
else
cmdInfo.UpdateDataFilter = (int)Runtime.Events.EventDataFilter.None;
cmdInfo.ItemVersion = insertCommand.itemVersion;
cmdInfo.LockAccessType = (LockAccessType)insertCommand.lockAccessType;
cmdInfo.LockId = insertCommand.lockId;
cmdInfo.value = cache.SocketServerDataService.GetCacheData(insertCommand.data, cmdInfo.Flag);
try
{
for (int count = 0; count < insertCommand.data.Count; count++)
{
cmdInfo.DataFormatValue = cmdInfo.DataFormatValue + insertCommand.data[count].Length;
}
}
catch
{
}
break;
}
return cmdInfo;
}
#region ILeasable
public override void ResetLeasable()
{
base.ResetLeasable();
serializationContext = default;
_bitSet.ResetLeasable();
_priorityEvictionHint.ResetLeasable();
}
public override void ReturnLeasableToPool()
{
throw new NotImplementedException();
}
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
extern alias analysis;
extern alias pythontools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using pythontools::Microsoft.PythonTools;
using pythontools::Microsoft.PythonTools.Intellisense;
using analysis::Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools.MockVsTests;
using TestUtilities;
namespace PythonToolsMockTests {
[TestClass]
public class EditorTests {
[ClassInitialize]
public static void Initialize(TestContext context) {
AssertListener.Initialize();
VsProjectAnalyzer.DefaultTimeout = 10000;
VsProjectAnalyzer.AssertOnRequestFailure = true;
}
[TestInitialize]
public void OnTestInitialized() {
MockPythonToolsPackage.SuppressTaskProvider = true;
}
[TestCleanup]
public void OnTestCleanup() {
MockPythonToolsPackage.SuppressTaskProvider = false;
}
[TestMethod, Priority(0)]
public void BuiltinFunctionSigHelp() {
using (var view = new PythonEditor()) {
view.TypeAndWaitForAnalysis("min");
view.Type("(");
for (int retries = 10; retries > 0; --retries) {
using (var sh = view.View.WaitForSession<ISignatureHelpSession>()) {
var doc = sh.Session.Signatures[0].Documentation;
if (doc.Contains("still being calculated")) {
view.VS.Sleep(100);
continue;
}
AssertUtil.AreEqual(new Regex(@".*min\([^)]+\).*"), doc);
break;
}
}
}
}
[TestMethod, Priority(0)]
public void SigHelpInClass() {
using (var view = new PythonEditor()) {
view.TypeAndWaitForAnalysis("class C(): pass\n");
view.MoveCaret(1, 9);
view.ParamInfo();
view.View.AssertNoIntellisenseSession();
}
}
[TestMethod, Priority(0)]
public void BuiltinFunctionCompletions() {
using (var view = new PythonEditor()) {
view.TypeAndWaitForAnalysis("min");
view.Type(".");
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
AssertUtil.Contains(sh.Session.Completions(), "__call__");
}
}
}
[TestMethod, Priority(0)]
public void FilterCompletions() {
using (var view = new PythonEditor()) {
view.TypeAndWaitForAnalysis("min");
view.Type(".");
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
AssertUtil.Contains(sh.Session.Completions(), "__call__");
view.Type("class");
AssertUtil.DoesntContain(sh.Session.Completions(), "__call__");
}
}
}
[TestMethod, Priority(0)]
public void DotCompletes() {
using (var view = new PythonEditor()) {
view.TypeAndWaitForAnalysis("min");
view.Type(".");
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
AssertUtil.Contains(sh.Session.Completions(), "__call__");
view.Type("class.");
Assert.AreEqual("min.__class__.", view.Text);
}
}
}
[TestMethod, Priority(0)]
public void NonIdentifierDismisses() {
using (var view = new PythonEditor()) {
view.TypeAndWaitForAnalysis("min");
view.Type(".");
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
AssertUtil.Contains(sh.Session.Completions(), "__call__");
view.Type("#");
Assert.IsTrue(sh.Session.IsDismissed);
}
view.View.AssertNoIntellisenseSession();
Assert.AreEqual("min.#", view.Text);
}
}
[TestMethod, Priority(0)]
public void EnterCommits() {
using (var view = new PythonEditor()) {
view.TypeAndWaitForAnalysis("min");
view.Type(".");
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
AssertUtil.ContainsAtLeast(sh.Session.Completions(), "__class__");
view.Type("class\r");
}
Assert.AreEqual("min.__class__", view.Text);
}
}
[TestMethod, Priority(0)]
public void EnterDismisses() {
using (var view = new PythonEditor()) {
view.AdvancedOptions.EnterCommitsIntellisense = false;
view.AdvancedOptions.AutoListMembers = true;
view.TypeAndWaitForAnalysis("min");
view.Type(".");
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
AssertUtil.ContainsAtLeast(sh.Session.Completions(), "__class__");
view.Type("class\r");
}
Assert.AreEqual("min.class\r\n", view.Text);
}
}
[TestMethod, Priority(0)]
public void EnterCommitsCompleteNoNewLine() {
using (var view = new PythonEditor()) {
view.AdvancedOptions.AddNewLineAtEndOfFullyTypedWord = true;
view.AdvancedOptions.AutoListMembers = true;
view.AdvancedOptions.AutoListIdentifiers = false;
view.AdvancedOptions.HideAdvancedMembers = false;
view.Type("min.__");
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
AssertUtil.ContainsAtLeast(sh.Session.Completions(), "__class__");
view.Type("class__\r");
}
Assert.AreEqual("min.__class__\r\n", view.Text);
}
}
[TestMethod, Priority(0)]
public void TabCommits() {
using (var view = new PythonEditor()) {
view.AdvancedOptions.EnterCommitsIntellisense = false;
view.AdvancedOptions.AutoListMembers = true;
view.AdvancedOptions.AutoListIdentifiers = false;
view.AdvancedOptions.HideAdvancedMembers = false;
view.Type("min.");
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
AssertUtil.ContainsAtLeast(sh.Session.Completions(), "__class__");
view.Type("class\t");
}
Assert.AreEqual("min.__class__", view.Text);
}
}
[TestMethod, Priority(0)]
public void DecoratorCompletions() {
using (var view = new PythonEditor()) {
view.Type("@");
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
AssertUtil.ContainsAtLeast(sh.Session.Completions(), "property", "staticmethod");
}
}
}
[TestMethod, Priority(0)]
public void DecoratorNonCompletions() {
using (var view = new PythonEditor()) {
view.Type("a = b @");
view.View.AssertNoIntellisenseSession();
}
}
[TestMethod, Priority(0)]
public void AutoListIdentifierCompletions() {
using (var view = new PythonEditor()) {
view.AdvancedOptions.AutoListIdentifiers = true;
view.Type("a = ");
foreach (var c in "abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ") {
// x<space> should bring up a completion session
Console.WriteLine("Typing {0}", c);
view.Type(c.ToString());
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
sh.Session.Dismiss();
}
view.Backspace();
}
view.View.AssertNoIntellisenseSession();
// x<space> should not bring up a completion session
// Don't check too many items, since asserting that no session
// starts is slow.
foreach (var c in "1234567890([{") {
Console.WriteLine("Typing {0}", c);
view.Type(c.ToString());
view.View.AssertNoIntellisenseSession();
view.Backspace();
}
}
}
private void AutoListTest(string code, params int[] triggerAtIndex) {
AutoListTest(code, PythonLanguageVersion.V33, triggerAtIndex);
}
private void AutoListTest(string code, PythonLanguageVersion version, params int[] triggerAtIndex) {
using (var view = new PythonEditor(version: version)) {
view.AdvancedOptions.AutoListIdentifiers = true;
view.AdvancedOptions.AutoListMembers = true;
int lastStart = 0;
string text;
foreach (var _i in triggerAtIndex) {
bool expectCompletions = _i >= 0;
int expected = _i > 0 ? _i : -_i;
text = code.Substring(lastStart, expected - lastStart);
if (!string.IsNullOrEmpty(text)) {
Console.WriteLine("Typing '{0}' [{1}, {2})", text, lastStart, expected);
view.Type(text);
using (var sh = view.View.WaitForSession<ICompletionSession>(false)) {
// Having a session here is okay as long as nothing is selected
var hasCommittableCompletion = sh?.Session?.SelectedCompletionSet?.SelectionStatus?.IsSelected ?? false;
if (hasCommittableCompletion) {
sh.Session.Dismiss();
Assert.Fail($"Completion for {text} should not have any item selected");
} else if (sh != null) {
sh.Session.Dismiss();
}
}
}
lastStart = expected;
if (expectCompletions) {
text = code.Substring(expected, 1);
Console.WriteLine("Typing '{0}' [{1}, {2}) and expect completions", text, expected, expected + 1);
view.Type(text);
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
sh.Session.Dismiss();
}
lastStart = expected + 1;
}
}
text = code.Substring(lastStart);
if (!string.IsNullOrEmpty(text)) {
Console.WriteLine("Typing '{0}' [{1}, {2})", text, lastStart, code.Length);
view.Type(text);
view.View.AssertNoIntellisenseSession();
}
}
}
[TestMethod, Priority(0)]
public void AutoListInDef() {
AutoListTest("def fn(p:a, q=b) -> x", 9, 14, 20);
}
[TestMethod, Priority(0)]
public void AutoListInAssignment() {
AutoListTest("a, b, c = a, b, c", 10, 13, 16);
}
[TestMethod, Priority(0)]
public void AutoListInClass() {
AutoListTest("class F(o, p):", 8, 11);
}
[TestMethod, Priority(0)]
public void AutoListInLambda() {
AutoListTest("a = lambda x, y: p", 4, 17);
}
[TestMethod, Priority(0)]
public void AutoListInWith() {
AutoListTest("with a as b, c(x) as d:", 5, 13, -22);
}
[TestMethod, Priority(0)]
public void AutoListInLiterals() {
AutoListTest("[a, b, c]", 1, 4, 7);
AutoListTest("{a, b, c}", 1, 4, 7);
AutoListTest("(a, b, c)", 1, 4, 7);
AutoListTest("{a: b, c: d, e: f}", 1, 4, 7, 10, 13, 16);
}
[TestMethod, Priority(0)]
public void AutoListInComprehensions() {
// TODO: Make completions trigger after spaces
// eg: AutoListTest("[a for a in b]", 1, 3, 9, 12);
AutoListTest("[a for a in b for c in d if x]", 1, -7, 12, -18, 23, 28);
AutoListTest("{a for a in b for c in d if x}", 1, -7, 12, -18, 23, 28);
AutoListTest("(a for a in b for c in d if x)", 1, -7, 12, -18, 23, 28);
AutoListTest("{a: b for a, b in b for c, d in e if x}", 1, 4, -10, -13, 18, 32, 37);
AutoListTest("x = [a for a in b for c in d if x]", 0, 5, -11, 16, -22, 27, 32);
}
[TestMethod, Priority(0)]
public void AutoListInStatements() {
AutoListTest("assert a", 0, -6, 7);
AutoListTest("a += b", 0, 5);
AutoListTest("del a", 0, -3, 4);
AutoListTest("exec a", PythonLanguageVersion.V27, -4, 5);
AutoListTest("for a in b", -3, -5, 9);
AutoListTest("if a", -2, 3);
AutoListTest("global a", -6, 7);
AutoListTest("nonlocal a", PythonLanguageVersion.V33, -8, 9);
AutoListTest("print a", PythonLanguageVersion.V27, -5, 6);
AutoListTest("return a", -6, 7);
AutoListTest("while a", -5, 6);
AutoListTest("yield a", -5, 6);
}
[TestMethod, Priority(0)]
public void DisableAutoCompletions() {
using (var view = new PythonEditor()) {
view.AdvancedOptions.AutoListMembers = false;
view.AdvancedOptions.AutoListIdentifiers = false;
foreach (var t in new[] { "a", "a.", "import " }) {
Console.WriteLine("Typed " + t);
view.Type(t);
view.View.AssertNoIntellisenseSession();
view.Clear();
}
}
}
[TestMethod, Priority(0)]
public void CompletionsAtEndOfLastChildScope() {
using (var view = new PythonEditor(@"class A:
def f(param1, param2):
y = 234
class B:
pass
")) {
view.MoveCaret(5, 9);
view.TypeAndWaitForAnalysis("p");
view.MemberList();
using (var sh = view.View.WaitForSession<ICompletionSession>()) {
AssertUtil.ContainsAtLeast(sh.Session.Completions(), "param1", "param2");
}
}
}
[TestMethod, Priority(0)]
public void NewlineWithinComment() {
using (var view = new PythonEditor(@"# comment")) {
view.MoveCaret(1, 1);
view.Enter();
Assert.AreEqual(2, view.CurrentSnapshot.LineCount);
Assert.AreEqual("", view.CurrentSnapshot.GetLineFromLineNumber(0).GetText());
Assert.AreEqual("# comment", view.CurrentSnapshot.GetLineFromLineNumber(1).GetText());
}
using (var view = new PythonEditor(@"# comment")) {
view.MoveCaret(1, 3);
view.Enter();
Assert.AreEqual(2, view.CurrentSnapshot.LineCount);
Assert.AreEqual("# ", view.CurrentSnapshot.GetLineFromLineNumber(0).GetText());
Assert.AreEqual("# comment", view.CurrentSnapshot.GetLineFromLineNumber(1).GetText());
}
using (var view = new PythonEditor(@"# comment")) {
view.MoveCaret(1, 10);
view.Enter();
Assert.AreEqual(2, view.CurrentSnapshot.LineCount);
Assert.AreEqual("# comment", view.CurrentSnapshot.GetLineFromLineNumber(0).GetText());
Assert.AreEqual("", view.CurrentSnapshot.GetLineFromLineNumber(1).GetText());
}
using (var view = new PythonEditor(@" # comment")) {
view.MoveCaret(1, 7);
view.Enter();
Assert.AreEqual(2, view.CurrentSnapshot.LineCount);
Assert.AreEqual(" # ", view.CurrentSnapshot.GetLineFromLineNumber(0).GetText());
Assert.AreEqual(" # comment", view.CurrentSnapshot.GetLineFromLineNumber(1).GetText());
}
}
}
static class IntellisenseTestExtensions {
public static IEnumerable<string> Completions(this ICompletionSession session) {
Assert.IsNotNull(session);
Assert.AreEqual(1, session.CompletionSets.Count);
return session.CompletionSets[0].Completions.Select(x => x.InsertionText);
}
public static void Clear(this MockVsTextView view) {
var snapshot = view.View.TextSnapshot;
using (var edit = snapshot.TextBuffer.CreateEdit()) {
edit.Delete(new Microsoft.VisualStudio.Text.Span(0, snapshot.Length));
edit.Apply();
}
}
public static PythonToolsService GetPyService(this MockVs session) {
var service = session.ServiceProvider.GetPythonToolsService();
Assert.IsNotNull(service, "PythonToolsService is unavailable");
return service;
}
}
}
| |
/*
* Copyright (c) 2015, Wisconsin Robotics
* 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 Wisconsin Robotics 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 WISCONSIN ROBOTICS 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 BadgerJaus.Util;
namespace BadgerJaus.Messages.PrimitiveDriver
{
public class ReportWrenchEffort : QueryWrenchEffort
{
public const int PROPULSIVE_LINEAR_EFFORT_X_BIT = 0;
public const int PROPULSIVE_LINEAR_EFFORT_Y_BIT = 1;
public const int PROPULSIVE_LINEAR_EFFORT_Z_BIT = 2;
public const int PROPULSIVE_ROTATIONAL_EFFORT_X_BIT = 3;
public const int PROPULSIVE_ROTATIONAL_EFFORT_Y_BIT = 4;
public const int PROPULSIVE_ROTATIONAL_EFFORT_Z_BIT = 5;
public const int RESISTIVE_LINEAR_EFFORT_X_BIT = 6;
public const int RESISTIVE_LINEAR_EFFORT_Y_BIT = 7;
public const int RESISTIVE_LINEAR_EFFORT_Z_BIT = 8;
public const int RESISTIVE_ROTATIONAL_EFFORT_X_BIT = 9;
public const int RESISTIVE_ROTATIONAL_EFFORT_Y_BIT = 10;
public const int RESISTIVE_ROTATIONAL_EFFORT_Z_BIT = 11;
public const int PROPULSIVE_EFFORT_MIN = -100;
public const int PROPULSIVE_EFFORT_MAX = 100;
public const int RESISTIVE_EFFORT_MIN = 0;
public const int RESISTIVE_EFFORT_MAX = 100;
JausUnsignedShort propLinearX;
JausUnsignedShort propLinearY;
JausUnsignedShort propLinearZ;
JausUnsignedShort propRotX;
JausUnsignedShort propRotY;
JausUnsignedShort propRotZ;
JausByte resistLinearX;
JausByte resistLinearY;
JausByte resistLinearZ;
JausByte resistRotX;
JausByte resistRotY;
JausByte resistRotZ;
protected override int CommandCode
{
get { return JausCommandCode.REPORT_WRENCH_EFFORT; }
}
protected override void InitFieldData()
{
base.InitFieldData();
propLinearX = new JausUnsignedShort();
propLinearY = new JausUnsignedShort();
propLinearZ = new JausUnsignedShort();
propRotX = new JausUnsignedShort();
propRotY = new JausUnsignedShort();
propRotZ = new JausUnsignedShort();
resistLinearX = new JausByte();
resistLinearY = new JausByte();
resistLinearZ = new JausByte();
resistRotX = new JausByte();
resistRotY = new JausByte();
resistRotZ = new JausByte();
}
public bool isFieldSet(int bit)
{
return presence.IsBitSet(bit);
}
public void SetPropulsiveLinearEffortX(double xEffort)
{
propLinearX.SetValueFromDouble(xEffort, PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
presence.setBit(PROPULSIVE_LINEAR_EFFORT_X_BIT);
}
public void SetPropulsiveLinearEffortY(double yEffort)
{
propLinearY.SetValueFromDouble(yEffort, PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
presence.setBit(PROPULSIVE_LINEAR_EFFORT_Y_BIT);
}
public void SetPropulsiveLinearEffortZ(double zEffort)
{
propLinearZ.SetValueFromDouble(zEffort, PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
presence.setBit(PROPULSIVE_LINEAR_EFFORT_Z_BIT);
}
public void SetPropulsiveRotationalEffortX(double xEffort)
{
propRotX.SetValueFromDouble(xEffort, PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
presence.setBit(PROPULSIVE_ROTATIONAL_EFFORT_X_BIT);
}
public void SetPropulsiveRotationalEffortY(double yEffort)
{
propRotY.SetValueFromDouble(yEffort, PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
presence.setBit(PROPULSIVE_ROTATIONAL_EFFORT_Y_BIT);
}
public void SetPropulsiveRotationalEffortZ(double zEffort)
{
propRotZ.SetValueFromDouble(zEffort, PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
presence.setBit(PROPULSIVE_ROTATIONAL_EFFORT_Z_BIT);
}
public void SetResistiveLinearEffortX(double xEffort)
{
resistLinearX.SetValueFromDouble(xEffort, RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
presence.setBit(RESISTIVE_LINEAR_EFFORT_X_BIT);
}
public void SetResistiveLinearEffortY(double yEffort)
{
resistLinearY.SetValueFromDouble(yEffort, RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
presence.setBit(RESISTIVE_LINEAR_EFFORT_Y_BIT);
}
public void SetResistiveLinearEffortZ(double zEffort)
{
resistLinearZ.SetValueFromDouble(zEffort, RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
presence.setBit(RESISTIVE_LINEAR_EFFORT_Z_BIT);
}
public void SetResistiveRotationalEffortX(double xEffort)
{
resistRotX.SetValueFromDouble(xEffort, RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
presence.setBit(RESISTIVE_ROTATIONAL_EFFORT_X_BIT);
}
public void SetResistiveRotationalEffortY(double yEffort)
{
resistRotY.SetValueFromDouble(yEffort, RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
presence.setBit(RESISTIVE_ROTATIONAL_EFFORT_Y_BIT);
}
public void SetResistiveRotationalEffortZ(double zEffort)
{
resistRotZ.SetValueFromDouble(zEffort, RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
presence.setBit(RESISTIVE_ROTATIONAL_EFFORT_Z_BIT);
}
public double GetPropulsiveLinearEffortX()
{
return propLinearX.ScaleValueToDouble(PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
}
public double GetPropulsiveLinearEffortY()
{
return propLinearY.ScaleValueToDouble(PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
}
public double GetPropulsiveLinearEffortZ()
{
return propLinearZ.ScaleValueToDouble(PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
}
public double GetPropulsiveRotationalEffortX()
{
return propRotX.ScaleValueToDouble(PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
}
public double GetPropulsiveRotationalEffortY()
{
return propRotY.ScaleValueToDouble(PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
}
public double GetPropulsiveRotationalEffortZ()
{
return propRotZ.ScaleValueToDouble(PROPULSIVE_EFFORT_MIN, PROPULSIVE_EFFORT_MAX);
}
public double GetResistiveLinearEffortX()
{
return resistLinearX.ScaleValueToDouble(RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
}
public double GetResistiveLinearEffortY()
{
return resistLinearY.ScaleValueToDouble(RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
}
public double GetResistiveLinearEffortZ()
{
return resistLinearZ.ScaleValueToDouble(RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
}
public double GetResistiveRotationalEffortX()
{
return resistRotX.ScaleValueToDouble(RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
}
public double GetResistiveRotationalEffortY()
{
return resistRotY.ScaleValueToDouble(RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
}
public double GetResistiveRotationalEffortZ()
{
return resistRotZ.ScaleValueToDouble(RESISTIVE_EFFORT_MIN, RESISTIVE_EFFORT_MAX);
}
public override int GetPayloadSize()
{
int payloadSize = 0;
payloadSize += base.GetPayloadSize();
if (presence.IsBitSet(PROPULSIVE_LINEAR_EFFORT_X_BIT))
payloadSize += JausBaseType.SHORT_BYTE_SIZE;
if (presence.IsBitSet(PROPULSIVE_LINEAR_EFFORT_Y_BIT))
payloadSize += JausBaseType.SHORT_BYTE_SIZE;
if (presence.IsBitSet(PROPULSIVE_LINEAR_EFFORT_Z_BIT))
payloadSize += JausBaseType.SHORT_BYTE_SIZE;
if (presence.IsBitSet(PROPULSIVE_ROTATIONAL_EFFORT_X_BIT))
payloadSize += JausBaseType.SHORT_BYTE_SIZE;
if (presence.IsBitSet(PROPULSIVE_ROTATIONAL_EFFORT_Y_BIT))
payloadSize += JausBaseType.SHORT_BYTE_SIZE;
if (presence.IsBitSet(PROPULSIVE_ROTATIONAL_EFFORT_Z_BIT))
payloadSize += JausBaseType.SHORT_BYTE_SIZE;
if (presence.IsBitSet(RESISTIVE_LINEAR_EFFORT_X_BIT))
payloadSize += JausBaseType.BYTE_BYTE_SIZE;
if (presence.IsBitSet(RESISTIVE_LINEAR_EFFORT_Y_BIT))
payloadSize += JausBaseType.BYTE_BYTE_SIZE;
if (presence.IsBitSet(RESISTIVE_LINEAR_EFFORT_Z_BIT))
payloadSize += JausBaseType.BYTE_BYTE_SIZE;
if (presence.IsBitSet(RESISTIVE_ROTATIONAL_EFFORT_X_BIT))
payloadSize += JausBaseType.BYTE_BYTE_SIZE;
if (presence.IsBitSet(RESISTIVE_ROTATIONAL_EFFORT_Y_BIT))
payloadSize += JausBaseType.BYTE_BYTE_SIZE;
if (presence.IsBitSet(RESISTIVE_ROTATIONAL_EFFORT_Z_BIT))
payloadSize += JausBaseType.BYTE_BYTE_SIZE;
return payloadSize;
}
protected override bool SetPayloadFromJausBuffer(byte[] buffer, int index, out int indexOffset)
{
base.SetPayloadFromJausBuffer(buffer, index, out indexOffset);
if (presence.IsBitSet(PROPULSIVE_LINEAR_EFFORT_X_BIT))
{
propLinearX.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(PROPULSIVE_LINEAR_EFFORT_Y_BIT))
{
propLinearY.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(PROPULSIVE_LINEAR_EFFORT_Z_BIT))
{
propLinearZ.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(PROPULSIVE_ROTATIONAL_EFFORT_X_BIT))
{
propRotX.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(PROPULSIVE_ROTATIONAL_EFFORT_Y_BIT))
{
propRotY.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(PROPULSIVE_ROTATIONAL_EFFORT_Z_BIT))
{
propRotZ.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(RESISTIVE_LINEAR_EFFORT_X_BIT))
{
resistLinearX.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(RESISTIVE_LINEAR_EFFORT_Y_BIT))
{
resistLinearY.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(RESISTIVE_LINEAR_EFFORT_Z_BIT))
{
resistLinearZ.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(RESISTIVE_ROTATIONAL_EFFORT_X_BIT))
{
resistRotX.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(RESISTIVE_ROTATIONAL_EFFORT_Y_BIT))
{
resistRotY.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(RESISTIVE_ROTATIONAL_EFFORT_Z_BIT))
{
resistRotZ.Deserialize(buffer, indexOffset, out indexOffset);
}
return true;
}
protected override bool PayloadToJausBuffer(byte[] buffer, int index, out int indexOffset)
{
base.PayloadToJausBuffer(buffer, index, out indexOffset);
if (presence.IsBitSet(PROPULSIVE_LINEAR_EFFORT_X_BIT))
{
if (!propLinearX.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(PROPULSIVE_LINEAR_EFFORT_Y_BIT))
{
if (!propLinearY.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(PROPULSIVE_LINEAR_EFFORT_Z_BIT))
{
if (!propLinearZ.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(PROPULSIVE_ROTATIONAL_EFFORT_X_BIT))
{
if (!propRotX.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(PROPULSIVE_ROTATIONAL_EFFORT_Y_BIT))
{
if (!propRotY.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(PROPULSIVE_ROTATIONAL_EFFORT_Z_BIT))
{
if (!propRotZ.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(RESISTIVE_LINEAR_EFFORT_X_BIT))
{
if (!resistLinearX.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(RESISTIVE_LINEAR_EFFORT_Y_BIT))
{
if (!resistLinearY.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(RESISTIVE_LINEAR_EFFORT_Z_BIT))
{
if (!resistLinearZ.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(RESISTIVE_ROTATIONAL_EFFORT_X_BIT))
{
if (!resistRotX.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(RESISTIVE_ROTATIONAL_EFFORT_Y_BIT))
{
if (!resistRotY.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(RESISTIVE_ROTATIONAL_EFFORT_Z_BIT))
{
if (!resistRotZ.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
return true;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Reflection.TypeDelegator.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Reflection
{
public partial class TypeDelegator : Type
{
#region Methods and constructors
protected override TypeAttributes GetAttributeFlagsImpl()
{
return default(TypeAttributes);
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
return default(ConstructorInfo);
}
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
return default(ConstructorInfo[]);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return default(Object[]);
}
public override Object[] GetCustomAttributes(bool inherit)
{
return default(Object[]);
}
public override Type GetElementType()
{
return default(Type);
}
public override EventInfo GetEvent(string name, BindingFlags bindingAttr)
{
return default(EventInfo);
}
public override EventInfo[] GetEvents()
{
return default(EventInfo[]);
}
public override EventInfo[] GetEvents(BindingFlags bindingAttr)
{
return default(EventInfo[]);
}
public override FieldInfo GetField(string name, BindingFlags bindingAttr)
{
return default(FieldInfo);
}
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
return default(FieldInfo[]);
}
public override Type GetInterface(string name, bool ignoreCase)
{
return default(Type);
}
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
return default(InterfaceMapping);
}
public override Type[] GetInterfaces()
{
return default(Type[]);
}
public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr)
{
return default(MemberInfo[]);
}
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
return default(MemberInfo[]);
}
protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
return default(MethodInfo);
}
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
return default(MethodInfo[]);
}
public override Type GetNestedType(string name, BindingFlags bindingAttr)
{
return default(Type);
}
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
return default(Type[]);
}
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
return default(PropertyInfo[]);
}
protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
{
return default(PropertyInfo);
}
protected override bool HasElementTypeImpl()
{
return default(bool);
}
public override Object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters)
{
return default(Object);
}
protected override bool IsArrayImpl()
{
return default(bool);
}
protected override bool IsByRefImpl()
{
return default(bool);
}
protected override bool IsCOMObjectImpl()
{
return default(bool);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return default(bool);
}
protected override bool IsPointerImpl()
{
return default(bool);
}
protected override bool IsPrimitiveImpl()
{
return default(bool);
}
protected override bool IsValueTypeImpl()
{
return default(bool);
}
protected TypeDelegator()
{
}
public TypeDelegator(Type delegatingType)
{
Contract.Ensures(delegatingType == this.typeImpl);
Contract.Ensures(this.typeImpl != null);
}
#endregion
#region Properties and indexers
public override Assembly Assembly
{
get
{
return default(Assembly);
}
}
public override string AssemblyQualifiedName
{
get
{
return default(string);
}
}
public override Type BaseType
{
get
{
return default(Type);
}
}
public override string FullName
{
get
{
return default(string);
}
}
public override Guid GUID
{
get
{
return default(Guid);
}
}
public override int MetadataToken
{
get
{
return default(int);
}
}
public override Module Module
{
get
{
return default(Module);
}
}
public override string Name
{
get
{
return default(string);
}
}
public override string Namespace
{
get
{
return default(string);
}
}
public override RuntimeTypeHandle TypeHandle
{
get
{
return default(RuntimeTypeHandle);
}
}
public override Type UnderlyingSystemType
{
get
{
return default(Type);
}
}
#endregion
#region Fields
protected Type typeImpl;
#endregion
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* ICalParser is a general purpose .Net parser for iCalendar format files (RFC 2445)
*
* Copyright (C) 2004 J. Tim Spurway
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
using System.Collections;
using System.IO;
using System.Text;
namespace ASC.Api.Calendar.iCalParser
{
/// <summary>
/// Parse iCalendar rfc2445 streams and convert to another format based on the emitter used.
/// </summary>
///
/// <remarks>
/// This class is the main entry point for the ICalParser library. A parser is created
/// with a TextReader that contains the iCalendar stream to be parsed, and an IEmitter, which
/// is used to transform the iCalendar into another format.
///
/// Each iCalendar format file is in the form:
///
/// ID[[;attr1;attr2;attr3;...;attrn]:value]
///
/// where ID is the main keyword identifying the iCalendar entry, followed optionally by a
/// set of attributes and a single value. The parser works by identifying the specific IDs,
/// attributes and values, categorizing them based on similar 'behaviour' (as defined in the <code>Token</code>
/// class) and passing on recognized symbols to the emitter for further processing.
///
/// The error recovery policy of the parser is pretty simple. When an error is detected, it is recorded,
/// and the rest of the (possibly folded) line is read, and parsing continues.
/// </remarks>
///
/// <example>
/// The following snippet will read the contents of the file 'myCalendar.ics', which the
/// parser will expect to contain iCalendar statements, and will write the RdfICalendar
/// equivalent to standard output.
/// <code>
/// RDFEmitter emitter = new RDFEmitter( );
/// StreamReader reader = new StreamReader( "myCalendar.ics" );
/// Parser parser = new Parser( reader, emitter );
/// parser.Parse( );
/// Console.WriteLine( emitter.Rdf );
/// </code>
/// </example>
///
public class Parser
{
readonly ArrayList errors;
readonly Scanner scanner;
Stack stack, attributes;
readonly IEmitter emitter;
int linenumber;
Token id, iprop; // id is the current ID for the current line
/// <summary>
/// Create a new iCalendar parser.
/// </summary>
/// <param name="reader">The reader that contains the stream of text iCalendar</param>
/// <param name="_emitter">The emitter that will transform the iCalendar elements</param>
public Parser(TextReader reader, IEmitter _emitter)
{
scanner = new Scanner(reader);
emitter = _emitter;
emitter.VParser = this;
errors = new ArrayList();
}
public ArrayList Errors
{
get
{
return errors;
}
}
public string ErrorString
{
get
{
if (!HasErrors)
{
return "";
}
StringBuilder rval = new StringBuilder();
foreach (ParserError error in errors)
{
rval.Append(error.ToString()).Append("\r\n");
}
return rval.ToString();
}
}
public bool HasErrors
{
get { return errors.Count > 0; }
}
/*/// <summary>
/// Give public access to the parse stack.
/// </summary>
private Stack VStack
{
get { return stack; }
}*/
/// <summary>
/// Main entry point for starting the Parser.
/// </summary>
public void Parse()
{
Parse(true);
}
/// <summary>
/// Alternate entry point for starting the parser.
/// </summary>
/// <param name="emitHandT">Indicates if the emitter should be told to emit headers
/// and trailers before and after emitting the iCalendar body</param>
public void Parse(bool emitHandT)
{
stack = new Stack();
linenumber = 0;
attributes = new Stack(); // a stack of key-value pairs (implemented as a stack of DitionaryEntry)
if (emitHandT)
{
emitter.doIntro();
}
// each time through the loop will get a single (maybe folded) line
while (true)
{
// check for termination condition
if (scanner.isEOF())
{
// end of file - do cleanup and go
break;
}
// empty the attribute stack and the iprop value...
attributes.Clear();
iprop = null;
id = null;
//FIXME: linenumber doesn't really keep track of actual line numbers because
// it is not aware of folded lines...
linenumber++;
//DEBUG: emit line number
//emitter.emit( linenumber + ". " );
if (!parseID())
{
continue;
}
// we now have to parse a set of attributes (semi-colon separated) or
// a value (delimited by a colon)
Token sep = scanner.GetNextToken(ScannerState.ParseSimple);
if (sep == null || sep.TokenVal == TokenValue.Error)
{
// some kind of error - skip rest of line and continue
reportError(scanner, " expecting : or ; after id - found nothing.");
continue;
}
else if (sep.TokenVal == TokenValue.SemiColon)
{
if (!parseAttributes(scanner))
{
continue;
}
// now we have to parse the value
sep = scanner.GetNextToken(ScannerState.ParseSimple);
if (!parseValue())
{
continue;
}
}
else if (sep.TokenVal == TokenValue.Colon)
{
if (!parseValue())
{
continue;
}
}
else
{
reportError(scanner, "expecting : or ; after id - found: " + sep.TokenText);
continue;
}
// now sploosh out the attributes (if any) and finish the ID tag
while (attributes.Count > 0)
{
DictionaryEntry entry = (DictionaryEntry)attributes.Pop();
Token key = (Token)entry.Key;
Token val = (Token)entry.Value;
emitter.doAttribute(key, val);
}
emitter.doEnd(id);
}
if (emitHandT)
{
emitter.doOutro();
}
}
protected void reportError(Scanner s, string msg)
{
s.ConsumeToEOL();
errors.Add(new ParserError(linenumber, msg));
}
/// <summary>
/// Parse the first field (ID) of the line. Returns a boolean on weather or not the
/// method sucesfully recognized an ID. If not, the method insures that the scanner
/// will start at the beginning of a new line.
/// </summary>
/// <returns></returns>
protected virtual bool parseID()
{
Token t; // re-usable token variable
id = scanner.GetNextToken(ScannerState.ParseID);
if (id == null || id.TokenVal == TokenValue.Error)
{
// some kind of error - skip rest of line and continue
reportError(scanner, "expecting ID - found nothing.");
return false;
}
switch (id.TokenVal)
{
case TokenValue.Tbegin:
t = scanner.GetNextToken(ScannerState.ParseSimple);
if (t == null || t.isError() || t.TokenVal != TokenValue.Colon)
{
if (t == null)
reportError(scanner, " expecting : - found nothing.");
else
reportError(scanner, " expecting : - found " + t.TokenText);
return false;
}
t = scanner.GetNextToken(ScannerState.ParseID);
if (t == null || t.isError() || (!t.isBeginEndValue() && !t.isResourceProperty()))
{
if (t == null)
reportError(scanner, " expecting a valid beginend value - found nothing.");
else
reportError(scanner, " expecting a valid beginend value - found " + t.TokenText);
return false;
}
// check for the different types of begin tags
if (t.isResourceProperty())
{
emitter.doResourceBegin(t);
}
else if (t.isComponent())
{
emitter.doComponent();
emitter.doComponentBegin(t);
}
else if (t.TokenVal == TokenValue.Tvcalendar)
{
emitter.doComponentBegin(t);
}
else
{
emitter.doBegin(t);
}
stack.Push(t); // to match up to the corresponding end value
//scanner.ConsumeToEOL();
return false;
case TokenValue.Tend:
t = scanner.GetNextToken(ScannerState.ParseSimple);
if (t == null || t.isError() || t.TokenVal != TokenValue.Colon)
{
if (t == null)
reportError(scanner, " expecting : - found nothing.");
else
reportError(scanner, " expecting : - found " + t.TokenText);
return false;
}
t = scanner.GetNextToken(ScannerState.ParseID);
if (t == null || t.isError() || (!t.isBeginEndValue() && !t.isResourceProperty()))
{
if (t == null)
reportError(scanner, " expecting a valid beginend value - found nothing.");
else
reportError(scanner, " expecting a valid beginend value - found " + t.TokenText);
return false;
}
// the end is easier - ignore the last one...
if (stack.Count != 0)
{
emitter.doEnd(t);
if (t.isComponent())
{
emitter.doEndComponent();
}
stack.Pop();
}
else
{
reportError(scanner, "stack stuff is weird - probably illformed .ics file - parsing " + id.TokenText);
}
//scanner.ConsumeToEOL();
return false;
case TokenValue.Trrule:
emitter.doResourceBegin(id);
break;
default:
emitter.doID(id);
break;
}
return true;
}
/// <summary>
/// Parse the list of attributes - separated by ';'s. Attributes always are in the
/// form 'id=value' and indicate key/value pairs in the iCalendar attribute format.
/// </summary>
/// <returns></returns>
protected virtual bool parseAttributes(Scanner scan)
{
Token key = scan.GetNextToken(ScannerState.ParseKey);
if (key == null || key.TokenVal == TokenValue.Error)
{
// some kind of error - skip rest of line and continue
if (key == null)
reportError(scanner, " expecting ID - found nothing.");
else
reportError(scanner, " expecting ID - found " + key.TokenText);
return false;
}
Token sep = scan.GetNextToken(ScannerState.ParseSimple);
if (sep == null || sep.TokenVal != TokenValue.Equals)
{
// some kind of error - skip rest of line and continue
if (sep == null)
reportError(scanner, " expecting = - found nothing.");
else
reportError(scanner, " expecting = - found " + sep.TokenText);
return false;
}
Token val = scan.GetNextToken(ScannerState.ParseParms);
if (val == null || val.TokenVal == TokenValue.Error)
{
// some kind of error - skip rest of line and continue
if (val == null)
reportError(scanner, " expecting parameter - found nothing.");
else
reportError(scanner, " expecting parameter - found " + val.TokenText);
return false;
}
if (key.TokenVal == TokenValue.Tvalue && scanner == scan)
{
// it's an IPROP - don't ask...
iprop = val;
}
else
{
attributes.Push(new DictionaryEntry(key, val));
}
// do a recursive case to identify all of the attributes
sep = scan.GetNextToken(ScannerState.ParseSimple);
if (sep == null || sep.TokenVal == TokenValue.Error)
{
// if we are parsing an rrule - this is the line termination
if (scanner != scan)
{
return true;
}
// some kind of error - skip rest of line and continue
if (sep == null)
reportError(scanner, " expecting : or ; - found nothing.");
else
reportError(scanner, " expecting : or ; - found " + sep.TokenText);
return false;
}
if (sep.TokenVal == TokenValue.Colon)
{
// termination case
return true;
}
else if (sep.TokenVal == TokenValue.SemiColon)
{
// recursive case
return parseAttributes(scan);
}
return true;
}
/// <summary>
/// Parse the value. The value is the last data item on a iCalendar input line.
/// </summary>
/// <returns></returns>
protected virtual bool parseValue()
{
Token val = scanner.GetNextToken(ScannerState.ParseValue);
if (val == null || val.TokenVal == TokenValue.Error)
{
// some kind of error - skip rest of line and continue
if (val == null)
reportError(scanner, " expecting value - found nothing.");
else
reportError(scanner, " expecting value - found " + val.TokenText);
return false;
}
// the emmision of code for the value will depend on the ID for this line
if (id.isSymbolicProperty())
{
emitter.doSymbolic(val);
return false; // because this ends the tag
}
else if (id.isMailtoProperty())
{
emitter.doMailto(val);
}
else if (id.isValueProperty())
{
if (id.TokenVal == TokenValue.Trrule)
{
// this is a special case - the value will be an attribute list...
parseAttributes(new Scanner(new StringReader(val.TokenText)));
}
else
{
emitter.doValueProperty(val, iprop);
}
}
else if (iprop != null && id.TokenVal != TokenValue.Xtension)
{
if (iprop.TokenText.ToLowerInvariant() == "uri")
{
// special case
emitter.doURIResource(val);
}
else
{
emitter.doIprop(val, iprop);
}
return false;
}
else
{
if (id.TokenVal == TokenValue.TrecurrenceId)
val.FormatDateTime(); // if this is a recurrence id, then format the date so that it is a legal date type for RDF and RQL
emitter.doRest(val, id);
return false;
}
return true;
}
}
}
| |
using System;
using NSec.Cryptography;
using Xunit;
namespace NSec.Tests.Base
{
public static class AeadAlgorithmTests
{
public static readonly TheoryData<AeadAlgorithm> AeadAlgorithms = Registry.AeadAlgorithms;
private const int L = 547;
#region Properties
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void Properties(AeadAlgorithm a)
{
Assert.True(a.KeySize > 0);
Assert.InRange(a.NonceSize, 0, 24);
Assert.InRange(a.TagSize, 0, 255);
}
#endregion
#region Encrypt #1
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithNullKey(AeadAlgorithm a)
{
Assert.Throws<ArgumentNullException>("key", () => a.Encrypt(null!, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithDisposedKey(AeadAlgorithm a)
{
var k = new Key(a);
k.Dispose();
Assert.Throws<ObjectDisposedException>(() => a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithWrongKey(AeadAlgorithm a)
{
using var k = new Key(SignatureAlgorithm.Ed25519);
Assert.Throws<ArgumentException>("key", () => a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithNonceTooSmall(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.Throws<ArgumentException>("nonce", () => a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize - 1), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithNonceTooLarge(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.Throws<ArgumentException>("nonce", () => a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize + 1), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptEmptySuccess(AeadAlgorithm a)
{
using var k = new Key(a);
var b = a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty);
Assert.NotNull(b);
Assert.Equal(a.TagSize, b.Length);
}
#endregion
#region Encrypt #2
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithSpanWithNullKey(AeadAlgorithm a)
{
Assert.Throws<ArgumentNullException>("key", () => a.Encrypt(null!, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, Span<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithSpanWithDisposedKey(AeadAlgorithm a)
{
var k = new Key(a);
k.Dispose();
Assert.Throws<ObjectDisposedException>(() => a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, new byte[a.TagSize]));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithSpanWithWrongKey(AeadAlgorithm a)
{
using var k = new Key(SignatureAlgorithm.Ed25519);
Assert.Throws<ArgumentException>("key", () => a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, Span<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithSpanWithNonceTooSmall(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.Throws<ArgumentException>("nonce", () => a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize - 1), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, Span<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithSpanWithNonceTooLarge(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.Throws<ArgumentException>("nonce", () => a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize + 1), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, Span<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptEmptyWithSpanTooSmall(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.Throws<ArgumentException>("ciphertext", () => a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, new byte[a.TagSize - 1]));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptEmptyWithSpanTooLarge(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.Throws<ArgumentException>("ciphertext", () => a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, new byte[a.TagSize + 1]));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithNonceOverlapping(AeadAlgorithm a)
{
using var k = new Key(a);
var ad = Utilities.RandomBytes.Slice(0, 100);
var b = Utilities.RandomBytes.Slice(0, L);
var expected = new byte[b.Length + a.TagSize];
var actual = new byte[b.Length + a.TagSize];
Utilities.RandomBytes.Slice(200, actual.Length).CopyTo(actual);
a.Encrypt(k, actual.AsSpan(10, a.NonceSize), ad, b, expected);
a.Encrypt(k, actual.AsSpan(10, a.NonceSize), ad, b, actual);
Assert.Equal(expected, actual);
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithAdOverlapping(AeadAlgorithm a)
{
using var k = new Key(a);
var n = Utilities.RandomBytes.Slice(0, a.NonceSize);
var b = Utilities.RandomBytes.Slice(0, L);
var expected = new byte[b.Length + a.TagSize];
var actual = new byte[b.Length + a.TagSize];
Utilities.RandomBytes.Slice(200, actual.Length).CopyTo(actual);
a.Encrypt(k, n, actual, b, expected);
a.Encrypt(k, n, actual, b, actual);
Assert.Equal(expected, actual);
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithPlaintextOverlapping(AeadAlgorithm a)
{
using var k = new Key(a);
var n = Utilities.RandomBytes.Slice(0, a.NonceSize).ToArray();
var ad = Utilities.RandomBytes.Slice(0, 100).ToArray();
var b = Utilities.RandomBytes.Slice(200, 200).ToArray();
Assert.Throws<ArgumentException>("ciphertext", () => a.Encrypt(k, n, ad, b.AsSpan(10, 100), b.AsSpan(60, 100 + a.TagSize)));
Assert.Throws<ArgumentException>("ciphertext", () => a.Encrypt(k, n, ad, b.AsSpan(60, 100), b.AsSpan(10, 100 + a.TagSize)));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithSpanOutOfPlace(AeadAlgorithm a)
{
using var k = new Key(a);
var n = Utilities.RandomBytes.Slice(0, a.NonceSize);
var ad = Utilities.RandomBytes.Slice(0, 100);
var expected = new byte[L + a.TagSize];
var actual = new byte[L + a.TagSize];
var plaintext = Utilities.RandomBytes.Slice(0, L);
a.Encrypt(k, n, ad, plaintext, expected);
a.Encrypt(k, n, ad, plaintext, actual);
Assert.Equal(expected, actual);
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void EncryptWithSpanInPlace(AeadAlgorithm a)
{
using var k = new Key(a);
var n = Utilities.RandomBytes.Slice(0, a.NonceSize);
var ad = Utilities.RandomBytes.Slice(0, 100);
var expected = new byte[L + a.TagSize];
var actual = new byte[L + a.TagSize];
Utilities.RandomBytes.Slice(0, L).CopyTo(actual);
a.Encrypt(k, n, ad, actual.AsSpan(0, L), expected);
a.Encrypt(k, n, ad, actual.AsSpan(0, L), actual);
Assert.Equal(expected, actual);
}
#endregion
#region Decrypt #1
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithNullKey(AeadAlgorithm a)
{
Assert.Throws<ArgumentNullException>("key", () => a.Decrypt(null!, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithDisposedKey(AeadAlgorithm a)
{
var k = new Key(a);
k.Dispose();
Assert.Throws<ObjectDisposedException>(() => a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, new byte[a.TagSize]));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithWrongKey(AeadAlgorithm a)
{
using var k = new Key(SignatureAlgorithm.Ed25519);
Assert.Throws<ArgumentException>("key", () => a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithNonceTooSmall(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.Null(a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize - 1), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithNonceTooLarge(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.Null(a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize + 1), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithCiphertextTooSmall(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.Null(a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, new byte[a.TagSize - 1]));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptEmptySuccess(AeadAlgorithm a)
{
using var k = new Key(a);
var ct = a.Encrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty);
Assert.NotNull(ct);
Assert.Equal(a.TagSize, ct.Length);
var pt = a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ct);
Assert.NotNull(pt);
Assert.Empty(pt);
}
#endregion
#region Decrypt #2
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithSpanWithNullKey(AeadAlgorithm a)
{
Assert.Throws<ArgumentNullException>("key", () => a.Decrypt(null!, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, Span<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithSpanWithDisposedKey(AeadAlgorithm a)
{
var k = new Key(a);
k.Dispose();
Assert.Throws<ObjectDisposedException>(() => a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, new byte[a.TagSize], Span<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithSpanWithWrongKey(AeadAlgorithm a)
{
using var k = new Key(SignatureAlgorithm.Ed25519);
Assert.Throws<ArgumentException>("key", () => a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, Span<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithSpanWithNonceTooSmall(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.False(a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize - 1), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, Span<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithSpanWithNonceTooLarge(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.False(a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize + 1), ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty, Span<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithSpanWithCiphertextTooSmall(AeadAlgorithm a)
{
using var k = new Key(a);
Assert.False(a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, new byte[a.TagSize - 1], Span<byte>.Empty));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithSpanTooLarge(AeadAlgorithm a)
{
using var k = new Key(a);
var n = Utilities.RandomBytes.Slice(0, a.NonceSize).ToArray();
var ct = a.Encrypt(k, n, ReadOnlySpan<byte>.Empty, ReadOnlySpan<byte>.Empty);
Assert.NotNull(ct);
Assert.Equal(a.TagSize, ct.Length);
Assert.Throws<ArgumentException>("plaintext", () => a.Decrypt(k, n, ReadOnlySpan<byte>.Empty, ct, new byte[1]));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithAdOverlapping(AeadAlgorithm a)
{
using var k = new Key(a);
var n = Utilities.RandomBytes.Slice(0, a.NonceSize);
var b = Utilities.RandomBytes.Slice(0, L);
var expected = b.ToArray();
var actual = Utilities.RandomBytes.Slice(200, L).ToArray();
var ciphertext = a.Encrypt(k, n, actual.AsSpan(10, 100), expected);
Assert.True(a.Decrypt(k, n, actual.AsSpan(10, 100), ciphertext, actual));
Assert.Equal(expected, actual);
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithCiphertextOverlapping(AeadAlgorithm a)
{
using var k = new Key(a);
var n = Utilities.RandomBytes.Slice(0, a.NonceSize).ToArray();
var ad = Utilities.RandomBytes.Slice(0, 100).ToArray();
var b = Utilities.RandomBytes.Slice(200, 200).ToArray();
Assert.Throws<ArgumentException>("plaintext", () => a.Decrypt(k, n, ad, b.AsSpan(10, 100 + a.TagSize), b.AsSpan(60, 100)));
Assert.Throws<ArgumentException>("plaintext", () => a.Decrypt(k, n, ad, b.AsSpan(60, 100 + a.TagSize), b.AsSpan(10, 100)));
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithSpanOutOfPlace(AeadAlgorithm a)
{
using var k = new Key(a);
var n = Utilities.RandomBytes.Slice(0, a.NonceSize);
var ad = Utilities.RandomBytes.Slice(0, 100);
var expected = Utilities.RandomBytes.Slice(0, L).ToArray();
var actual = new byte[L];
var ciphertext = a.Encrypt(k, n, ad, expected);
Assert.True(a.Decrypt(k, n, ad, ciphertext, actual));
Assert.Equal(expected, actual);
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptWithSpanInPlace(AeadAlgorithm a)
{
using var k = new Key(a);
var n = Utilities.RandomBytes.Slice(0, a.NonceSize);
var ad = Utilities.RandomBytes.Slice(0, 100);
var actual = new byte[L + a.TagSize];
var expected = new byte[L + a.TagSize];
a.Encrypt(k, n, ad, Utilities.RandomBytes.Slice(0, L), actual);
a.Encrypt(k, n, ad, Utilities.RandomBytes.Slice(0, L), expected);
Assert.True(a.Decrypt(k, n, ad, actual, expected.AsSpan(0, L)));
Assert.True(a.Decrypt(k, n, ad, actual, actual.AsSpan(0, L)));
Assert.Equal(expected, actual);
}
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void DecryptFailClearsPlaintext(AeadAlgorithm a)
{
using var k = new Key(a);
var pt = new byte[16];
for (var i = 0; i < pt.Length; i++)
{
pt[i] = 0xD6;
}
var ct = new byte[pt.Length + a.TagSize];
Assert.False(a.Decrypt(k, Utilities.RandomBytes.Slice(0, a.NonceSize), ReadOnlySpan<byte>.Empty, ct, pt));
Assert.Equal(new byte[pt.Length], pt);
}
#endregion
#region CreateKey
[Theory]
[MemberData(nameof(AeadAlgorithms))]
public static void CreateKey(AeadAlgorithm a)
{
using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextArchiving });
Assert.Same(a, k.Algorithm);
Assert.False(k.HasPublicKey);
Assert.Throws<InvalidOperationException>(() => k.PublicKey);
Assert.Equal(a.KeySize, k.Size);
var actual = k.Export(KeyBlobFormat.RawSymmetricKey);
var unexpected = Utilities.FillArray(actual.Length, actual[0]);
Assert.NotEqual(unexpected, actual);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Merger.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data {
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
/// <devdoc>
/// Merge Utilities.
/// </devdoc>
internal sealed class Merger {
private DataSet dataSet = null;
private DataTable dataTable = null;
private bool preserveChanges;
private MissingSchemaAction missingSchemaAction;
private bool isStandAlonetable = false;
private bool _IgnoreNSforTableLookup = false; // Everett Behavior : SQL BU DT 370850
internal Merger(DataSet dataSet, bool preserveChanges, MissingSchemaAction missingSchemaAction) {
this.dataSet = dataSet;
this.preserveChanges = preserveChanges;
// map AddWithKey -> Add
if (missingSchemaAction == MissingSchemaAction.AddWithKey)
this.missingSchemaAction = MissingSchemaAction.Add;
else
this.missingSchemaAction = missingSchemaAction;
}
internal Merger(DataTable dataTable, bool preserveChanges, MissingSchemaAction missingSchemaAction) {
isStandAlonetable = true;
this.dataTable = dataTable;
this.preserveChanges = preserveChanges;
// map AddWithKey -> Add
if (missingSchemaAction == MissingSchemaAction.AddWithKey)
this.missingSchemaAction = MissingSchemaAction.Add;
else
this.missingSchemaAction = missingSchemaAction;
}
internal void MergeDataSet(DataSet source) {
if (source == dataSet) return; //somebody is doing an 'automerge'
bool fEnforce = dataSet.EnforceConstraints;
dataSet.EnforceConstraints = false;
_IgnoreNSforTableLookup = (dataSet.namespaceURI != source.namespaceURI); // if two DataSets have different
// Namespaces, ignore NS for table lookups as we wont be able to find the right tables which inherits its NS
List<DataColumn> existingColumns = null;// need to cache existing columns
if (MissingSchemaAction.Add == missingSchemaAction) {
existingColumns = new List<DataColumn>(); // need to cache existing columns
foreach(DataTable dt in dataSet.Tables) {
foreach(DataColumn dc in dt.Columns) {
existingColumns.Add(dc);
}
}
}
for (int i = 0; i < source.Tables.Count; i++) {
MergeTableData(source.Tables[i]); // since column expression might have dependency on relation, we do not set
//column expression at this point. We need to set it after adding relations
}
if (MissingSchemaAction.Ignore != missingSchemaAction) {
// Add all independent constraints
MergeConstraints(source);
// Add all relationships
for (int i = 0; i < source.Relations.Count; i++) {
MergeRelation(source.Relations[i]);
}
}
// WebData 88234
if (MissingSchemaAction.Add == missingSchemaAction) { // for which other options we should add expressions also?
foreach (DataTable sourceTable in source.Tables) {
DataTable targetTable;
if (_IgnoreNSforTableLookup) {
targetTable = dataSet.Tables[sourceTable.TableName];
}
else {
targetTable = dataSet.Tables[sourceTable.TableName, sourceTable.Namespace];// we know that target table wont be null since MissingSchemaAction is Add , we have already added it!
}
foreach(DataColumn dc in sourceTable.Columns) { // Should we overwrite the previous expression column? No, refer to spec, if it is new column we need to add the schema
if (dc.Computed) {
DataColumn targetColumn = targetTable.Columns[dc.ColumnName];
if (!existingColumns.Contains(targetColumn)) {
targetColumn.Expression = dc.Expression;
}
}
}
}
}
MergeExtendedProperties(source.ExtendedProperties, dataSet.ExtendedProperties);
foreach(DataTable dt in dataSet.Tables)
dt.EvaluateExpressions();
dataSet.EnforceConstraints = fEnforce;
}
internal void MergeTable(DataTable src) {
bool fEnforce = false;
if (!isStandAlonetable) {
if (src.DataSet == dataSet) return; //somebody is doing an 'automerge'
fEnforce = dataSet.EnforceConstraints;
dataSet.EnforceConstraints = false;
}
else {
if (src == dataTable) return; //somebody is doing an 'automerge'
dataTable.SuspendEnforceConstraints = true;
}
if (this.dataSet != null) { // this is ds.Merge
// if source does not have a DS, or if NS of both DS does not match, ignore the NS
if (src.DataSet == null || src.DataSet.namespaceURI != this.dataSet.namespaceURI) {
_IgnoreNSforTableLookup = true;
}
}
else { // this is dt.Merge
if (this.dataTable.DataSet == null || src.DataSet == null ||
src.DataSet.namespaceURI != this.dataTable.DataSet.namespaceURI) {
_IgnoreNSforTableLookup = true;
}
}
MergeTableData(src);
DataTable dt = dataTable;
if (dt == null && dataSet != null) {
if (_IgnoreNSforTableLookup) {
dt = dataSet.Tables[src.TableName];
}
else {
dt = dataSet.Tables[src.TableName, src.Namespace];
}
}
if (dt != null) {
dt.EvaluateExpressions();
}
if (!isStandAlonetable) {
dataSet.EnforceConstraints = fEnforce;
}
else {
dataTable.SuspendEnforceConstraints = false;
try {
if (dataTable.EnforceConstraints) {
dataTable.EnableConstraints();
}
}
catch(ConstraintException) {
if (dataTable.DataSet != null) {
dataTable.DataSet.EnforceConstraints = false;
}
throw;
}
}
}
private void MergeTable(DataTable src, DataTable dst) {
int rowsCount = src.Rows.Count;
bool wasEmpty = dst.Rows.Count == 0;
if(0 < rowsCount) {
Index ndxSearch = null;
DataKey key = default(DataKey);
dst.SuspendIndexEvents();
try {
if(! wasEmpty && dst.primaryKey != null) {
key = GetSrcKey(src, dst);
if (key.HasValue)
ndxSearch = dst.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added );
}
// SQLBU 414992: Serious performance issue when calling Merge
// this improves performance by iterating over the rows instead of computing their position
foreach(DataRow sourceRow in src.Rows) {
DataRow targetRow = null;
if(ndxSearch != null) {
targetRow = dst.FindMergeTarget(sourceRow, key, ndxSearch);
}
dst.MergeRow(sourceRow, targetRow, preserveChanges, ndxSearch);
}
}
finally {
dst.RestoreIndexEvents(true);
}
}
MergeExtendedProperties(src.ExtendedProperties, dst.ExtendedProperties);
}
internal void MergeRows(DataRow[] rows) {
DataTable src = null;
DataTable dst = null;
DataKey key = default(DataKey);
Index ndxSearch = null;
bool fEnforce = dataSet.EnforceConstraints;
dataSet.EnforceConstraints = false;
for (int i = 0; i < rows.Length; i++) {
DataRow row = rows[i];
if (row == null) {
throw ExceptionBuilder.ArgumentNull("rows[" + i + "]");
}
if (row.Table == null) {
throw ExceptionBuilder.ArgumentNull("rows[" + i + "].Table");
}
//somebody is doing an 'automerge'
if (row.Table.DataSet == dataSet)
continue;
if (src != row.Table) { // row.Table changed from prev. row.
src = row.Table;
dst = MergeSchema(row.Table);
if (dst == null) {
Debug.Assert(MissingSchemaAction.Ignore == missingSchemaAction, "MergeSchema failed");
dataSet.EnforceConstraints = fEnforce;
return;
}
if(dst.primaryKey != null) {
key = GetSrcKey(src, dst);
}
if (key.HasValue) {
// Getting our own copy instead. ndxSearch = dst.primaryKey.Key.GetSortIndex();
// IMO, Better would be to reuse index
// ndxSearch = dst.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added );
if (null != ndxSearch) {
ndxSearch.RemoveRef();
ndxSearch = null;
}
ndxSearch = new Index(dst, dst.primaryKey.Key.GetIndexDesc(), DataViewRowState.OriginalRows | DataViewRowState.Added, (IFilter)null);
ndxSearch.AddRef(); // need to addref twice, otherwise it will be collected
ndxSearch.AddRef(); // in past first adref was done in const
}
}
if (row.newRecord == -1 && row.oldRecord == -1)
continue;
DataRow targetRow = null;
if(0 < dst.Rows.Count && ndxSearch != null) {
targetRow = dst.FindMergeTarget(row, key, ndxSearch);
}
targetRow = dst.MergeRow(row, targetRow, preserveChanges, ndxSearch);
if (targetRow.Table.dependentColumns != null && targetRow.Table.dependentColumns.Count > 0)
targetRow.Table.EvaluateExpressions(targetRow, DataRowAction.Change, null);
}
if (null != ndxSearch) {
ndxSearch.RemoveRef();
ndxSearch = null;
}
dataSet.EnforceConstraints = fEnforce;
}
private DataTable MergeSchema(DataTable table) {
DataTable targetTable = null;
if (!isStandAlonetable) {
if (dataSet.Tables.Contains(table.TableName, true))
if (_IgnoreNSforTableLookup) {
targetTable = dataSet.Tables[table.TableName];
}
else {
targetTable = dataSet.Tables[table.TableName, table.Namespace];
}
}
else {
targetTable = dataTable;
}
if (targetTable == null) { // in case of standalone table, we make sure that targetTable is not null, so if this check passes, it will be when it is called via detaset
if (MissingSchemaAction.Add == missingSchemaAction) {
targetTable = table.Clone(table.DataSet); // if we are here mainly we are called from DataSet.Merge at this point we don't set
//expression columns, since it might have refer to other columns via relation, so it wont find the table and we get exception;
// do it after adding relations.
dataSet.Tables.Add(targetTable);
}
else if (MissingSchemaAction.Error == missingSchemaAction) {
throw ExceptionBuilder.MergeMissingDefinition(table.TableName);
}
}
else {
if (MissingSchemaAction.Ignore != missingSchemaAction) {
// Do the columns
int oldCount = targetTable.Columns.Count;
for (int i = 0; i < table.Columns.Count; i++) {
DataColumn src = table.Columns[i];
DataColumn dest = (targetTable.Columns.Contains(src.ColumnName, true)) ? targetTable.Columns[src.ColumnName] : null;
if (dest == null) {
if (MissingSchemaAction.Add == missingSchemaAction) {
dest = src.Clone();
targetTable.Columns.Add(dest);
}
else {
if (!isStandAlonetable)
dataSet.RaiseMergeFailed(targetTable, Res.GetString(Res.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName), missingSchemaAction);
else
throw ExceptionBuilder.MergeFailed(Res.GetString(Res.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName));
}
}
else {
if (dest.DataType != src.DataType ||
((dest.DataType == typeof(DateTime)) && (dest.DateTimeMode != src.DateTimeMode) && ((dest.DateTimeMode & src.DateTimeMode) != DataSetDateTime.Unspecified))) {
if (!isStandAlonetable)
dataSet.RaiseMergeFailed(targetTable, Res.GetString(Res.DataMerge_DataTypeMismatch, src.ColumnName), MissingSchemaAction.Error);
else
throw ExceptionBuilder.MergeFailed(Res.GetString(Res.DataMerge_DataTypeMismatch, src.ColumnName));
}
//
MergeExtendedProperties(src.ExtendedProperties, dest.ExtendedProperties);
}
}
// Set DataExpression
if (isStandAlonetable) {
for (int i = oldCount; i < targetTable.Columns.Count; i++) {
targetTable.Columns[i].Expression = table.Columns[targetTable.Columns[i].ColumnName].Expression;
}
}
// check the PrimaryKey
DataColumn[] targetPKey = targetTable.PrimaryKey;
DataColumn[] tablePKey = table.PrimaryKey;
if (targetPKey.Length != tablePKey.Length) {
// special case when the target table does not have the PrimaryKey
if (targetPKey.Length == 0) {
DataColumn[] key = new DataColumn[tablePKey.Length];
for (int i = 0; i < tablePKey.Length; i++) {
key[i] = targetTable.Columns[tablePKey[i].ColumnName];
}
targetTable.PrimaryKey = key;
}
else if (tablePKey.Length != 0) {
dataSet.RaiseMergeFailed(targetTable, Res.GetString(Res.DataMerge_PrimaryKeyMismatch), missingSchemaAction);
}
}
else {
for (int i = 0; i < targetPKey.Length; i++) {
if (String.Compare(targetPKey[i].ColumnName, tablePKey[i].ColumnName, false, targetTable.Locale) != 0) {
dataSet.RaiseMergeFailed(table,
Res.GetString(Res.DataMerge_PrimaryKeyColumnsMismatch, targetPKey[i].ColumnName, tablePKey[i].ColumnName),
missingSchemaAction
);
}
}
}
}
MergeExtendedProperties(table.ExtendedProperties, targetTable.ExtendedProperties);
}
return targetTable;
}
private void MergeTableData(DataTable src) {
DataTable dest = MergeSchema(src);
if (dest == null) return;
dest.MergingData = true;
try {
MergeTable(src, dest);
}
finally {
dest.MergingData = false;
}
}
private void MergeConstraints(DataSet source) {
for (int i = 0; i < source.Tables.Count; i ++) {
MergeConstraints(source.Tables[i]);
}
}
private void MergeConstraints(DataTable table) {
// Merge constraints
for (int i = 0; i < table.Constraints.Count; i++) {
Constraint src = table.Constraints[i];
Constraint dest = src.Clone(dataSet, _IgnoreNSforTableLookup);
if (dest == null) {
dataSet.RaiseMergeFailed(table,
Res.GetString(Res.DataMerge_MissingConstraint, src.GetType().FullName, src.ConstraintName),
missingSchemaAction
);
}
else {
Constraint cons = dest.Table.Constraints.FindConstraint(dest);
if (cons == null) {
if (MissingSchemaAction.Add == missingSchemaAction) {
try {
// try to keep the original name
dest.Table.Constraints.Add(dest);
}
catch (DuplicateNameException) {
// if fail, assume default name
dest.ConstraintName = "";
dest.Table.Constraints.Add(dest);
}
}
else if (MissingSchemaAction.Error == missingSchemaAction) {
dataSet.RaiseMergeFailed(table,
Res.GetString(Res.DataMerge_MissingConstraint, src.GetType().FullName, src.ConstraintName),
missingSchemaAction
);
}
}
else {
MergeExtendedProperties(src.ExtendedProperties, cons.ExtendedProperties);
}
}
}
}
private void MergeRelation(DataRelation relation) {
Debug.Assert(MissingSchemaAction.Error == missingSchemaAction ||
MissingSchemaAction.Add == missingSchemaAction,
"Unexpected value of MissingSchemaAction parameter : " + ((Enum) missingSchemaAction).ToString());
DataRelation destRelation = null;
// try to find given relation in this dataSet
int iDest = dataSet.Relations.InternalIndexOf(relation.RelationName);
if (iDest >= 0) {
// check the columns and Relation properties..
destRelation = dataSet.Relations[iDest];
if (relation.ParentKey.ColumnsReference.Length != destRelation.ParentKey.ColumnsReference.Length) {
dataSet.RaiseMergeFailed(null,
Res.GetString(Res.DataMerge_MissingDefinition, relation.RelationName),
missingSchemaAction
);
}
for (int i = 0; i < relation.ParentKey.ColumnsReference.Length; i++) {
DataColumn dest = destRelation.ParentKey.ColumnsReference[i];
DataColumn src = relation.ParentKey.ColumnsReference[i];
if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table.Locale)) {
dataSet.RaiseMergeFailed(null,
Res.GetString(Res.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName),
missingSchemaAction
);
}
dest = destRelation.ChildKey.ColumnsReference[i];
src = relation.ChildKey.ColumnsReference[i];
if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table.Locale)) {
dataSet.RaiseMergeFailed(null,
Res.GetString(Res.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName),
missingSchemaAction
);
}
}
}
else {
if (MissingSchemaAction.Add == missingSchemaAction) {
// create identical realtion in the current dataset
DataTable parent;
if (_IgnoreNSforTableLookup){
parent = dataSet.Tables[relation.ParentTable.TableName];
}
else {
parent = dataSet.Tables[relation.ParentTable.TableName, relation.ParentTable.Namespace];
}
DataTable child;
if (_IgnoreNSforTableLookup) {
child = dataSet.Tables[relation.ChildTable.TableName];
}
else {
child = dataSet.Tables[relation.ChildTable.TableName,relation.ChildTable.Namespace];
}
DataColumn[] parentColumns = new DataColumn[relation.ParentKey.ColumnsReference.Length];
DataColumn[] childColumns = new DataColumn[relation.ParentKey.ColumnsReference.Length];
for (int i = 0; i < relation.ParentKey.ColumnsReference.Length; i++) {
parentColumns[i] = parent.Columns[relation.ParentKey.ColumnsReference[i].ColumnName];
childColumns[i] = child.Columns[relation.ChildKey.ColumnsReference[i].ColumnName];
}
try {
destRelation = new DataRelation(relation.RelationName, parentColumns, childColumns, relation.createConstraints);
destRelation.Nested = relation.Nested;
dataSet.Relations.Add(destRelation);
}
catch (Exception e) {
//
if (!Common.ADP.IsCatchableExceptionType(e)) {
throw;
}
ExceptionBuilder.TraceExceptionForCapture(e);
dataSet.RaiseMergeFailed(null, e.Message, missingSchemaAction);
}
}
else {
Debug.Assert(MissingSchemaAction.Error == missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + ((Enum) missingSchemaAction).ToString());
throw ExceptionBuilder.MergeMissingDefinition(relation.RelationName);
}
}
MergeExtendedProperties(relation.ExtendedProperties, destRelation.ExtendedProperties);
return;
}
private void MergeExtendedProperties(PropertyCollection src, PropertyCollection dst) {
if (MissingSchemaAction.Ignore == missingSchemaAction) {
return;
}
IDictionaryEnumerator srcDE = src.GetEnumerator();
while (srcDE.MoveNext()) {
if (!preserveChanges || dst[srcDE.Key] == null)
dst[srcDE.Key] = srcDE.Value;
}
}
private DataKey GetSrcKey(DataTable src, DataTable dst) {
if (src.primaryKey != null)
return src.primaryKey.Key;
DataKey key = default(DataKey);
if (dst.primaryKey != null) {
DataColumn[] dstColumns = dst.primaryKey.Key.ColumnsReference;
DataColumn[] srcColumns = new DataColumn[dstColumns.Length];
for (int j = 0; j < dstColumns.Length; j++) {
srcColumns[j] = src.Columns[dstColumns[j].ColumnName];
}
key = new DataKey(srcColumns, false); // DataKey will take ownership of srcColumns
}
return key;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// CryptoConfig.cs
//
namespace System.Security.Cryptography {
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Threading;
using System.Globalization;
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public class CryptoConfig {
private static volatile Dictionary<string, string> defaultOidHT = null;
private static volatile Dictionary<string, object> defaultNameHT = null;
private static volatile Dictionary<string, string> machineOidHT = null;
private static volatile Dictionary<string, string> machineNameHT = null;
private static volatile Dictionary<string, Type> appNameHT = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
private static volatile Dictionary<string, string> appOidHT = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private const string MachineConfigFilename = "machine.config";
private static volatile string version = null;
#if FEATURE_CRYPTO
private static volatile bool s_fipsAlgorithmPolicy;
private static volatile bool s_haveFipsAlgorithmPolicy;
/// <summary>
/// Determine if the runtime should enforce that only FIPS certified algorithms are created. This
/// property returns true if this policy should be enforced, false if any algorithm may be created.
/// </summary>
public static bool AllowOnlyFipsAlgorithms {
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
get {
if (!s_haveFipsAlgorithmPolicy)
{
//
// If the user has not disabled FIPS enforcement in a config file, check the CNG settings
// on Vista and the FIPS registry key downlevel.
//
if (Utils._GetEnforceFipsPolicySetting()) {
if (Environment.OSVersion.Version.Major >= 6) {
bool fipsEnabled;
uint policyReadStatus = Win32Native.BCryptGetFipsAlgorithmMode(out fipsEnabled);
bool readPolicy = policyReadStatus == Win32Native.STATUS_SUCCESS ||
policyReadStatus == Win32Native.STATUS_OBJECT_NAME_NOT_FOUND;
s_fipsAlgorithmPolicy = !readPolicy || fipsEnabled;
s_haveFipsAlgorithmPolicy = true;
}
else {
s_fipsAlgorithmPolicy = Utils.ReadLegacyFipsPolicy();
s_haveFipsAlgorithmPolicy = true;
}
}
else {
s_fipsAlgorithmPolicy = false;
s_haveFipsAlgorithmPolicy = true;
}
}
return s_fipsAlgorithmPolicy;
}
}
#endif // FEATURE_CRYPTO
private static string Version
{
[System.Security.SecurityCritical] // auto-generated
get
{
if(version == null)
version = ((RuntimeType)typeof(CryptoConfig)).GetRuntimeAssembly().GetVersion().ToString();
return version;
}
}
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject {
get {
if (s_InternalSyncObject == null) {
Object o = new Object();
Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
private static Dictionary<string, string> DefaultOidHT {
get {
if (defaultOidHT == null) {
Dictionary<string, string> ht = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("SHA", Constants.OID_OIWSEC_SHA1);
ht.Add("SHA1", Constants.OID_OIWSEC_SHA1);
ht.Add("System.Security.Cryptography.SHA1", Constants.OID_OIWSEC_SHA1);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
ht.Add("System.Security.Cryptography.SHA1CryptoServiceProvider", Constants.OID_OIWSEC_SHA1);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("System.Security.Cryptography.SHA1Managed", Constants.OID_OIWSEC_SHA1);
ht.Add("SHA256", Constants.OID_OIWSEC_SHA256);
ht.Add("System.Security.Cryptography.SHA256", Constants.OID_OIWSEC_SHA256);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
ht.Add("System.Security.Cryptography.SHA256CryptoServiceProvider", Constants.OID_OIWSEC_SHA256);
ht.Add("System.Security.Cryptography.SHA256Cng", Constants.OID_OIWSEC_SHA256);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("System.Security.Cryptography.SHA256Managed", Constants.OID_OIWSEC_SHA256);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
ht.Add("SHA384", Constants.OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384", Constants.OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384CryptoServiceProvider", Constants.OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384Cng", Constants.OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384Managed", Constants.OID_OIWSEC_SHA384);
ht.Add("SHA512", Constants.OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512", Constants.OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512CryptoServiceProvider", Constants.OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512Cng", Constants.OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512Managed", Constants.OID_OIWSEC_SHA512);
ht.Add("RIPEMD160", Constants.OID_OIWSEC_RIPEMD160);
ht.Add("System.Security.Cryptography.RIPEMD160", Constants.OID_OIWSEC_RIPEMD160);
ht.Add("System.Security.Cryptography.RIPEMD160Managed", Constants.OID_OIWSEC_RIPEMD160);
ht.Add("MD5", Constants.OID_RSA_MD5);
ht.Add("System.Security.Cryptography.MD5", Constants.OID_RSA_MD5);
ht.Add("System.Security.Cryptography.MD5CryptoServiceProvider", Constants.OID_RSA_MD5);
ht.Add("System.Security.Cryptography.MD5Managed", Constants.OID_RSA_MD5);
ht.Add("TripleDESKeyWrap", Constants.OID_RSA_SMIMEalgCMS3DESwrap);
ht.Add("RC2", Constants.OID_RSA_RC2CBC);
ht.Add("System.Security.Cryptography.RC2CryptoServiceProvider", Constants.OID_RSA_RC2CBC);
ht.Add("DES", Constants.OID_OIWSEC_desCBC);
ht.Add("System.Security.Cryptography.DESCryptoServiceProvider", Constants.OID_OIWSEC_desCBC);
ht.Add("TripleDES", Constants.OID_RSA_DES_EDE3_CBC);
ht.Add("System.Security.Cryptography.TripleDESCryptoServiceProvider", Constants.OID_RSA_DES_EDE3_CBC);
#endif // FEATURE_CRYPTO
defaultOidHT = ht;
}
return defaultOidHT;
}
}
private static Dictionary<string, object> DefaultNameHT {
get {
if (defaultNameHT == null) {
Dictionary<string, object> ht = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
#if FEATURE_CRYPTO
Type SHA1CryptoServiceProviderType = typeof(System.Security.Cryptography.SHA1CryptoServiceProvider);
Type MD5CryptoServiceProviderType = typeof(System.Security.Cryptography.MD5CryptoServiceProvider);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
Type SHA256ManagedType = typeof(SHA256Managed);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
Type SHA384ManagedType = typeof(SHA384Managed);
Type SHA512ManagedType = typeof(SHA512Managed);
Type RIPEMD160ManagedType = typeof(System.Security.Cryptography.RIPEMD160Managed);
Type HMACMD5Type = typeof(System.Security.Cryptography.HMACMD5);
Type HMACRIPEMD160Type = typeof(System.Security.Cryptography.HMACRIPEMD160);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
Type HMACSHA1Type = typeof(System.Security.Cryptography.HMACSHA1);
Type HMACSHA256Type = typeof(System.Security.Cryptography.HMACSHA256);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
Type HMACSHA384Type = typeof(System.Security.Cryptography.HMACSHA384);
Type HMACSHA512Type = typeof(System.Security.Cryptography.HMACSHA512);
Type MAC3DESType = typeof(System.Security.Cryptography.MACTripleDES);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
Type RSACryptoServiceProviderType = typeof(System.Security.Cryptography.RSACryptoServiceProvider);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
Type DSACryptoServiceProviderType = typeof(System.Security.Cryptography.DSACryptoServiceProvider);
Type DESCryptoServiceProviderType = typeof(System.Security.Cryptography.DESCryptoServiceProvider);
Type TripleDESCryptoServiceProviderType = typeof(System.Security.Cryptography.TripleDESCryptoServiceProvider);
Type RC2CryptoServiceProviderType = typeof(System.Security.Cryptography.RC2CryptoServiceProvider);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
Type RijndaelManagedType = typeof(System.Security.Cryptography.RijndaelManaged);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
Type DSASignatureDescriptionType = typeof(System.Security.Cryptography.DSASignatureDescription);
Type RSAPKCS1SHA1SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
Type RNGCryptoServiceProviderType = typeof(System.Security.Cryptography.RNGCryptoServiceProvider);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
// Cryptography algorithms in System.Core are referenced by name rather than type so
// that we don't force System.Core to load if we don't need any of its algorithms
string AesCryptoServiceProviderType = "System.Security.Cryptography.AesCryptoServiceProvider, " + AssemblyRef.SystemCore;
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
string AesManagedType = "System.Security.Cryptography.AesManaged, " + AssemblyRef.SystemCore;
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
string ECDiffieHellmanCngType = "System.Security.Cryptography.ECDiffieHellmanCng, " + AssemblyRef.SystemCore;
string ECDsaCngType = "System.Security.Cryptography.ECDsaCng, " + AssemblyRef.SystemCore;
string MD5CngType = "System.Security.Cryptography.MD5Cng, " + AssemblyRef.SystemCore;
string SHA1CngType = "System.Security.Cryptography.SHA1Cng, " + AssemblyRef.SystemCore;
string SHA256CngType = "System.Security.Cryptography.SHA256Cng, " + AssemblyRef.SystemCore;
string SHA256CryptoServiceProviderType = "System.Security.Cryptography.SHA256CryptoServiceProvider, " + AssemblyRef.SystemCore;
string SHA384CngType = "System.Security.Cryptography.SHA384Cng, " + AssemblyRef.SystemCore;
string SHA384CryptoSerivceProviderType = "System.Security.Cryptography.SHA384CryptoServiceProvider, " + AssemblyRef.SystemCore;
string SHA512CngType = "System.Security.Cryptography.SHA512Cng, " + AssemblyRef.SystemCore;
string SHA512CryptoServiceProviderType = "System.Security.Cryptography.SHA512CryptoServiceProvider, " + AssemblyRef.SystemCore;
// Cryptography algorithms in System.Security
string DpapiDataProtectorType = "System.Security.Cryptography.DpapiDataProtector, " + AssemblyRef.SystemSecurity;
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// Random number generator
ht.Add("RandomNumberGenerator", RNGCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.RandomNumberGenerator", RNGCryptoServiceProviderType);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
// Hash functions
ht.Add("SHA", SHA1CryptoServiceProviderType);
ht.Add("SHA1", SHA1CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.SHA1", SHA1CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.SHA1Cng", SHA1CngType);
ht.Add("System.Security.Cryptography.HashAlgorithm", SHA1CryptoServiceProviderType);
ht.Add("MD5", MD5CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.MD5", MD5CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.MD5Cng", MD5CngType);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("SHA256", SHA256ManagedType);
ht.Add("SHA-256", SHA256ManagedType);
ht.Add("System.Security.Cryptography.SHA256", SHA256ManagedType);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
ht.Add("System.Security.Cryptography.SHA256Cng", SHA256CngType);
ht.Add("System.Security.Cryptography.SHA256CryptoServiceProvider", SHA256CryptoServiceProviderType);
ht.Add("SHA384", SHA384ManagedType);
ht.Add("SHA-384", SHA384ManagedType);
ht.Add("System.Security.Cryptography.SHA384", SHA384ManagedType);
ht.Add("System.Security.Cryptography.SHA384Cng", SHA384CngType);
ht.Add("System.Security.Cryptography.SHA384CryptoServiceProvider", SHA384CryptoSerivceProviderType);
ht.Add("SHA512", SHA512ManagedType);
ht.Add("SHA-512", SHA512ManagedType);
ht.Add("System.Security.Cryptography.SHA512", SHA512ManagedType);
ht.Add("System.Security.Cryptography.SHA512Cng", SHA512CngType);
ht.Add("System.Security.Cryptography.SHA512CryptoServiceProvider", SHA512CryptoServiceProviderType);
ht.Add("RIPEMD160", RIPEMD160ManagedType);
ht.Add("RIPEMD-160", RIPEMD160ManagedType);
ht.Add("System.Security.Cryptography.RIPEMD160", RIPEMD160ManagedType);
ht.Add("System.Security.Cryptography.RIPEMD160Managed", RIPEMD160ManagedType);
// Keyed Hash Algorithms
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("System.Security.Cryptography.HMAC", HMACSHA1Type);
ht.Add("System.Security.Cryptography.KeyedHashAlgorithm", HMACSHA1Type);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
ht.Add("HMACMD5", HMACMD5Type);
ht.Add("System.Security.Cryptography.HMACMD5", HMACMD5Type);
ht.Add("HMACRIPEMD160", HMACRIPEMD160Type);
ht.Add("System.Security.Cryptography.HMACRIPEMD160", HMACRIPEMD160Type);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("HMACSHA1", HMACSHA1Type);
ht.Add("System.Security.Cryptography.HMACSHA1", HMACSHA1Type);
ht.Add("HMACSHA256", HMACSHA256Type);
ht.Add("System.Security.Cryptography.HMACSHA256", HMACSHA256Type);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
ht.Add("HMACSHA384", HMACSHA384Type);
ht.Add("System.Security.Cryptography.HMACSHA384", HMACSHA384Type);
ht.Add("HMACSHA512", HMACSHA512Type);
ht.Add("System.Security.Cryptography.HMACSHA512", HMACSHA512Type);
ht.Add("MACTripleDES", MAC3DESType);
ht.Add("System.Security.Cryptography.MACTripleDES", MAC3DESType);
// Asymmetric algorithms
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("RSA", RSACryptoServiceProviderType);
ht.Add("System.Security.Cryptography.RSA", RSACryptoServiceProviderType);
ht.Add("System.Security.Cryptography.AsymmetricAlgorithm", RSACryptoServiceProviderType);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
ht.Add("DSA", DSACryptoServiceProviderType);
ht.Add("System.Security.Cryptography.DSA", DSACryptoServiceProviderType);
ht.Add("ECDsa", ECDsaCngType);
ht.Add("ECDsaCng", ECDsaCngType);
ht.Add("System.Security.Cryptography.ECDsaCng", ECDsaCngType);
ht.Add("ECDH", ECDiffieHellmanCngType);
ht.Add("ECDiffieHellman", ECDiffieHellmanCngType);
ht.Add("ECDiffieHellmanCng", ECDiffieHellmanCngType);
ht.Add("System.Security.Cryptography.ECDiffieHellmanCng", ECDiffieHellmanCngType);
// Symmetric algorithms
ht.Add("DES", DESCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.DES", DESCryptoServiceProviderType);
ht.Add("3DES", TripleDESCryptoServiceProviderType);
ht.Add("TripleDES", TripleDESCryptoServiceProviderType);
ht.Add("Triple DES", TripleDESCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.TripleDES", TripleDESCryptoServiceProviderType);
ht.Add("RC2", RC2CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.RC2", RC2CryptoServiceProviderType);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("Rijndael", RijndaelManagedType);
ht.Add("System.Security.Cryptography.Rijndael", RijndaelManagedType);
// Rijndael is the default symmetric cipher because (a) it's the strongest and (b) we know we have an implementation everywhere
ht.Add("System.Security.Cryptography.SymmetricAlgorithm", RijndaelManagedType);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
ht.Add("AES", AesCryptoServiceProviderType);
ht.Add("AesCryptoServiceProvider", AesCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.AesCryptoServiceProvider", AesCryptoServiceProviderType);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("AesManaged", AesManagedType);
ht.Add("System.Security.Cryptography.AesManaged", AesManagedType);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
// Data protectors
ht.Add("DpapiDataProtector", DpapiDataProtectorType);
ht.Add("System.Security.Cryptography.DpapiDataProtector", DpapiDataProtectorType);
// Asymmetric signature descriptions
ht.Add("http://www.w3.org/2000/09/xmldsig#dsa-sha1", DSASignatureDescriptionType);
ht.Add("System.Security.Cryptography.DSASignatureDescription", DSASignatureDescriptionType);
ht.Add("http://www.w3.org/2000/09/xmldsig#rsa-sha1", RSAPKCS1SHA1SignatureDescriptionType);
ht.Add("System.Security.Cryptography.RSASignatureDescription", RSAPKCS1SHA1SignatureDescriptionType);
// Xml Dsig/Enc Hash algorithms
ht.Add("http://www.w3.org/2000/09/xmldsig#sha1", SHA1CryptoServiceProviderType);
// Add the other hash algorithms introduced with XML Encryption
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("http://www.w3.org/2001/04/xmlenc#sha256", SHA256ManagedType);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
ht.Add("http://www.w3.org/2001/04/xmlenc#sha512", SHA512ManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#ripemd160", RIPEMD160ManagedType);
// Xml Encryption symmetric keys
ht.Add("http://www.w3.org/2001/04/xmlenc#des-cbc", DESCryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", TripleDESCryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-tripledes", TripleDESCryptoServiceProviderType);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("http://www.w3.org/2001/04/xmlenc#aes128-cbc", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes128", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#aes192-cbc", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes192", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#aes256-cbc", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes256", RijndaelManagedType);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
// Xml Dsig Transforms
// First arg must match the constants defined in System.Security.Cryptography.Xml.SignedXml
ht.Add("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", "System.Security.Cryptography.Xml.XmlDsigC14NTransform, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments", "System.Security.Cryptography.Xml.XmlDsigC14NWithCommentsTransform, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/2001/10/xml-exc-c14n#", "System.Security.Cryptography.Xml.XmlDsigExcC14NTransform, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/2001/10/xml-exc-c14n#WithComments", "System.Security.Cryptography.Xml.XmlDsigExcC14NWithCommentsTransform, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/2000/09/xmldsig#base64", "System.Security.Cryptography.Xml.XmlDsigBase64Transform, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/TR/1999/REC-xpath-19991116", "System.Security.Cryptography.Xml.XmlDsigXPathTransform, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/TR/1999/REC-xslt-19991116", "System.Security.Cryptography.Xml.XmlDsigXsltTransform, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/2000/09/xmldsig#enveloped-signature", "System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform, " + AssemblyRef.SystemSecurity);
// the decryption transform
ht.Add("http://www.w3.org/2002/07/decrypt#XML", "System.Security.Cryptography.Xml.XmlDecryptionTransform, " + AssemblyRef.SystemSecurity);
// Xml licence transform.
ht.Add("urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform", "System.Security.Cryptography.Xml.XmlLicenseTransform, " + AssemblyRef.SystemSecurity);
// Xml Dsig KeyInfo
// First arg (the key) is formed as elem.NamespaceURI + " " + elem.LocalName
ht.Add("http://www.w3.org/2000/09/xmldsig# X509Data", "System.Security.Cryptography.Xml.KeyInfoX509Data, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/2000/09/xmldsig# KeyName", "System.Security.Cryptography.Xml.KeyInfoName, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/2000/09/xmldsig# KeyValue/DSAKeyValue", "System.Security.Cryptography.Xml.DSAKeyValue, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/2000/09/xmldsig# KeyValue/RSAKeyValue", "System.Security.Cryptography.Xml.RSAKeyValue, " + AssemblyRef.SystemSecurity);
ht.Add("http://www.w3.org/2000/09/xmldsig# RetrievalMethod", "System.Security.Cryptography.Xml.KeyInfoRetrievalMethod, " + AssemblyRef.SystemSecurity);
// Xml EncryptedKey
ht.Add("http://www.w3.org/2001/04/xmlenc# EncryptedKey", "System.Security.Cryptography.Xml.KeyInfoEncryptedKey, " + AssemblyRef.SystemSecurity);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// Xml Dsig HMAC URIs from http://www.w3.org/TR/xmldsig-core/
ht.Add("http://www.w3.org/2000/09/xmldsig#hmac-sha1", HMACSHA1Type);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
// Xml Dsig-more Uri's as defined in http://www.ietf.org/rfc/rfc4051.txt
ht.Add("http://www.w3.org/2001/04/xmldsig-more#md5", MD5CryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#sha384", SHA384ManagedType);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-md5", HMACMD5Type);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160", HMACRIPEMD160Type);
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", HMACSHA256Type);
#endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
#if FEATURE_CRYPTO
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", HMACSHA384Type);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", HMACSHA512Type);
// X509 Extensions (custom decoders)
// Basic Constraints OID value
ht.Add("2.5.29.10", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyRef.System);
ht.Add("2.5.29.19", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyRef.System);
// Subject Key Identifier OID value
ht.Add("2.5.29.14", "System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension, " + AssemblyRef.System);
// Key Usage OID value
ht.Add("2.5.29.15", "System.Security.Cryptography.X509Certificates.X509KeyUsageExtension, " + AssemblyRef.System);
// Enhanced Key Usage OID value
ht.Add("2.5.29.37", "System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension, " + AssemblyRef.System);
// X509Chain class can be overridden to use a different chain engine.
ht.Add("X509Chain", "System.Security.Cryptography.X509Certificates.X509Chain, " + AssemblyRef.System);
// PKCS9 attributes
ht.Add("1.2.840.113549.1.9.3", "System.Security.Cryptography.Pkcs.Pkcs9ContentType, " + AssemblyRef.SystemSecurity);
ht.Add("1.2.840.113549.1.9.4", "System.Security.Cryptography.Pkcs.Pkcs9MessageDigest, " + AssemblyRef.SystemSecurity);
ht.Add("1.2.840.113549.1.9.5", "System.Security.Cryptography.Pkcs.Pkcs9SigningTime, " + AssemblyRef.SystemSecurity);
ht.Add("1.3.6.1.4.1.311.88.2.1", "System.Security.Cryptography.Pkcs.Pkcs9DocumentName, " + AssemblyRef.SystemSecurity);
ht.Add("1.3.6.1.4.1.311.88.2.2", "System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription, " + AssemblyRef.SystemSecurity);
#endif // FEATURE_CRYPTO
defaultNameHT = ht;
}
return defaultNameHT;
}
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static void InitializeConfigInfo()
{
#if FEATURE_CRYPTO
if (machineNameHT == null)
{
lock(InternalSyncObject)
{
if(machineNameHT == null)
{
ConfigNode cryptoConfig = OpenCryptoConfig();
if (cryptoConfig != null)
{
foreach (ConfigNode node in cryptoConfig.Children)
{
if (machineNameHT != null && machineOidHT != null)
{
break;
}
else if (machineNameHT == null &&
String.Compare(node.Name, "cryptoNameMapping", StringComparison.Ordinal) == 0)
{
machineNameHT = InitializeNameMappings(node);
}
else if (machineOidHT == null &&
String.Compare(node.Name, "oidMap", StringComparison.Ordinal) == 0)
{
machineOidHT = InitializeOidMappings(node);
}
}
}
// if we couldn't access the config file, or it didn't contain our config section
// just create empty tables so that we don't end up trying to read the file
// on every access to InitializeConfigInfo()
if (machineNameHT == null)
machineNameHT = new Dictionary<string, string>();
if (machineOidHT == null)
machineOidHT = new Dictionary<string, string>();
}
}
}
#else
if (machineNameHT == null)
machineNameHT = new Dictionary<string, string>();
if (machineOidHT == null)
machineOidHT = new Dictionary<string, string>();
#endif //FEATURE_CRYPTO
}
/// <summary>
/// Add a set of name -> algorithm mappings to be used for the current AppDomain. These mappings
/// take precidense over the built-in mappings and the mappings in machine.config. This API is
/// critical to prevent partial trust code from hooking trusted crypto operations.
/// </summary>
[SecurityCritical]
public static void AddAlgorithm(Type algorithm, params string[] names) {
if (algorithm == null)
throw new ArgumentNullException("algorithm");
if (!algorithm.IsVisible)
throw new ArgumentException(Environment.GetResourceString("Cryptography_AlgorithmTypesMustBeVisible"), "algorithm");
if (names == null)
throw new ArgumentNullException("names");
Contract.EndContractBlock();
string[] algorithmNames = new string[names.Length];
Array.Copy(names, algorithmNames, algorithmNames.Length);
// Pre-check the algorithm names for validity so that we don't add a few of the names and then
// throw an exception if we find an invalid name partway through the list.
foreach (string name in algorithmNames) {
if (String.IsNullOrEmpty(name)) {
throw new ArgumentException(Environment.GetResourceString("Cryptography_AddNullOrEmptyName"));
}
}
// Everything looks valid, so we're safe to take the table lock and add the name mappings.
lock (InternalSyncObject) {
foreach (string name in algorithmNames) {
appNameHT[name] = algorithm;
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static object CreateFromName (string name, params object[] args) {
if (name == null)
throw new ArgumentNullException("name");
Contract.EndContractBlock();
Type retvalType = null;
Object retval;
// First we'll do the machine-wide stuff, initializing if necessary
InitializeConfigInfo();
// Check to see if we have an applicaiton defined mapping
lock (InternalSyncObject) {
retvalType = appNameHT.GetValueOrDefault(name);
}
// If we don't have a application defined mapping, search the machine table
if (retvalType == null) {
BCLDebug.Assert(machineNameHT != null, "machineNameHT != null");
String retvalTypeString = machineNameHT.GetValueOrDefault(name);
if (retvalTypeString != null) {
retvalType = Type.GetType(retvalTypeString, false, false);
if (retvalType != null && !retvalType.IsVisible)
retvalType = null;
}
}
// If we didn't find it in the machine-wide table, look in the default table
if (retvalType == null) {
// We allow the default table to Types and Strings
// Types get used for other stuff in mscorlib.dll
// strings get used for delay-loaded stuff like System.Security.dll
Object retvalObj = DefaultNameHT.GetValueOrDefault(name);
if (retvalObj != null) {
if (retvalObj is Type) {
retvalType = (Type) retvalObj;
} else if (retvalObj is String) {
retvalType = Type.GetType((String) retvalObj, false, false);
if (retvalType != null && !retvalType.IsVisible)
retvalType = null;
}
}
}
// Maybe they gave us a classname.
if (retvalType == null) {
retvalType = Type.GetType(name, false, false);
if (retvalType != null && !retvalType.IsVisible)
retvalType = null;
}
// Still null? Then we didn't find it
if (retvalType == null)
return null;
// Perform a CreateInstance by hand so we can check that the
// constructor doesn't have a linktime demand attached (which would
// be incorrrectly applied against mscorlib otherwise).
RuntimeType rtType = retvalType as RuntimeType;
if (rtType == null)
return null;
if (args == null)
args = new Object[]{};
// Locate all constructors.
MethodBase[] cons = rtType.GetConstructors(Activator.ConstructorDefault);
if (cons == null)
return null;
List<MethodBase> candidates = new List<MethodBase>();
for (int i = 0; i < cons.Length; i ++) {
MethodBase con = cons[i];
if (con.GetParameters().Length == args.Length) {
candidates.Add(con);
}
}
if (candidates.Count == 0)
return null;
cons = candidates.ToArray();
// Bind to matching ctor.
Object state;
RuntimeConstructorInfo rci = Type.DefaultBinder.BindToMethod(Activator.ConstructorDefault,
cons,
ref args,
null,
null,
null,
out state) as RuntimeConstructorInfo;
// Check for ctor we don't like (non-existant, delegate or decorated
// with declarative linktime demand).
if (rci == null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType))
return null;
// Ctor invoke (actually causes the allocation as well).
retval = rci.Invoke(Activator.ConstructorDefault, Type.DefaultBinder, args, null);
// Reset any parameter re-ordering performed by the binder.
if (state != null)
Type.DefaultBinder.ReorderArgumentArray(ref args, state);
return retval;
}
public static object CreateFromName (string name) {
return CreateFromName(name, null);
}
/// <summary>
/// Add a set of name -> OID mappings to be used for the current AppDomain. These mappings
/// take precidense over the built-in mappings and the mappings in machine.config. This API is
/// critical to prevent partial trust code from hooking trusted crypto operations.
/// </summary>
[SecurityCritical]
public static void AddOID(string oid, params string[] names) {
if (oid == null)
throw new ArgumentNullException("oid");
if (names == null)
throw new ArgumentNullException("names");
Contract.EndContractBlock();
string[] oidNames = new string[names.Length];
Array.Copy(names, oidNames, oidNames.Length);
// Pre-check the input names for validity, so that we don't add a few of the names and throw an
// exception if an invalid name is found further down the array.
foreach (string name in oidNames) {
if (String.IsNullOrEmpty(name)) {
throw new ArgumentException(Environment.GetResourceString("Cryptography_AddNullOrEmptyName"));
}
}
// Everything is valid, so we're good to lock the hash table and add the application mappings
lock (InternalSyncObject) {
foreach (string name in oidNames) {
appOidHT[name] = oid;
}
}
}
public static string MapNameToOID (string name) {
return MapNameToOID(name, OidGroup.AllGroups);
}
[SecuritySafeCritical]
internal static string MapNameToOID(string name, OidGroup oidGroup) {
if (name == null)
throw new ArgumentNullException("name");
Contract.EndContractBlock();
// First we'll do the machine-wide stuff, initializing if necessary
InitializeConfigInfo();
string oid = null;
// Check to see if we have an application defined mapping
lock (InternalSyncObject) {
oid = appOidHT.GetValueOrDefault(name);
}
// If we didn't find an application defined mapping, search the machine table
if (oid == null)
oid = machineOidHT.GetValueOrDefault(name);
// If we didn't find it in the machine-wide table, look in the default table
if (oid == null)
oid = DefaultOidHT.GetValueOrDefault(name);
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// Try the CAPI table association
if (oid == null)
oid = X509Utils.GetOidFromFriendlyName(name, oidGroup);
#endif // FEATURE_CRYPTO
return oid;
}
static public byte[] EncodeOID (string str) {
if (str == null) {
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
char[] sepArray = { '.' }; // valid ASN.1 separators
String[] oidString = str.Split(sepArray);
uint[] oidNums = new uint[oidString.Length];
for (int i = 0; i < oidString.Length; i++) {
oidNums[i] = (uint) Int32.Parse(oidString[i], CultureInfo.InvariantCulture);
}
// Allocate the array to receive encoded oidNums
byte[] encodedOidNums = new byte[oidNums.Length * 5]; // this is guaranteed to be longer than necessary
int encodedOidNumsIndex = 0;
// Handle the first two oidNums special
if (oidNums.Length < 2) {
throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_InvalidOID"));
}
uint firstTwoOidNums = (oidNums[0] * 40) + oidNums[1];
byte[] retval = EncodeSingleOIDNum(firstTwoOidNums);
Array.Copy(retval, 0, encodedOidNums, encodedOidNumsIndex, retval.Length);
encodedOidNumsIndex += retval.Length;
for (int i = 2; i < oidNums.Length; i++) {
retval = EncodeSingleOIDNum(oidNums[i]);
Buffer.InternalBlockCopy(retval, 0, encodedOidNums, encodedOidNumsIndex, retval.Length);
encodedOidNumsIndex += retval.Length;
}
// final return value is 06 <length> || encodedOidNums
if (encodedOidNumsIndex > 0x7f) {
throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_Config_EncodedOIDError"));
}
retval = new byte[ encodedOidNumsIndex + 2];
retval[0] = (byte) 0x06;
retval[1] = (byte) encodedOidNumsIndex;
Buffer.InternalBlockCopy(encodedOidNums, 0, retval, 2, encodedOidNumsIndex);
return retval;
}
static private byte[] EncodeSingleOIDNum(uint dwValue) {
byte[] retval;
if ((int)dwValue < 0x80) {
retval = new byte[1];
retval[0] = (byte) dwValue;
return retval;
}
else if (dwValue < 0x4000) {
retval = new byte[2];
retval[0] = (byte) ((dwValue >> 7) | 0x80);
retval[1] = (byte) (dwValue & 0x7f);
return retval;
}
else if (dwValue < 0x200000) {
retval = new byte[3];
retval[0] = (byte) ((dwValue >> 14) | 0x80);
retval[1] = (byte) ((dwValue >> 7) | 0x80);
retval[2] = (byte) (dwValue & 0x7f);
return retval;
}
else if (dwValue < 0x10000000) {
retval = new byte[4];
retval[0] = (byte) ((dwValue >> 21) | 0x80);
retval[1] = (byte) ((dwValue >> 14) | 0x80);
retval[2] = (byte) ((dwValue >> 7) | 0x80);
retval[3] = (byte) (dwValue & 0x7f);
return retval;
}
else {
retval = new byte[5];
retval[0] = (byte) ((dwValue >> 28) | 0x80);
retval[1] = (byte) ((dwValue >> 21) | 0x80);
retval[2] = (byte) ((dwValue >> 14) | 0x80);
retval[3] = (byte) ((dwValue >> 7) | 0x80);
retval[4] = (byte) (dwValue & 0x7f);
return retval;
}
}
private static Dictionary<string, string> InitializeNameMappings(ConfigNode nameMappingNode)
{
Contract.Assert(nameMappingNode != null, "No name mappings");
Contract.Assert(String.Compare(nameMappingNode.Name, "cryptoNameMapping", StringComparison.Ordinal) == 0, "Invalid name mapping root");
Dictionary<string, string> nameMappings = new Dictionary<string, string>();
Dictionary<string, string> typeAliases = new Dictionary<string, string>();
// find the cryptoClases element
foreach (ConfigNode node in nameMappingNode.Children)
{
if (String.Compare(node.Name, "cryptoClasses", StringComparison.Ordinal) == 0)
{
foreach(ConfigNode cryptoClass in node.Children)
{
if (String.Compare(cryptoClass.Name, "cryptoClass", StringComparison.Ordinal) == 0)
{
if (cryptoClass.Attributes.Count > 0)
{
DictionaryEntry attribute = (DictionaryEntry)cryptoClass.Attributes[0];
typeAliases.Add((string)attribute.Key, (string)attribute.Value);
}
}
}
}
else if(String.Compare(node.Name, "nameEntry", StringComparison.Ordinal) == 0)
{
string friendlyName = null;
string className = null;
foreach(DictionaryEntry attribute in node.Attributes)
{
if(String.Compare((string)attribute.Key, "name", StringComparison.Ordinal) == 0)
friendlyName = (string)attribute.Value;
else if(String.Compare((string)attribute.Key, "class", StringComparison.Ordinal) == 0)
className = (string)attribute.Value;
}
if (friendlyName != null && className != null)
{
string typeName = typeAliases.GetValueOrDefault(className);
if (typeName != null)
nameMappings.Add(friendlyName, typeName);
}
}
}
return nameMappings;
}
private static Dictionary<string, string> InitializeOidMappings(ConfigNode oidMappingNode)
{
Contract.Assert(oidMappingNode != null, "No OID mappings");
Contract.Assert(String.Compare(oidMappingNode.Name, "oidMap", StringComparison.Ordinal) == 0, "Invalid OID mapping root");
Dictionary<string, string> oidMap = new Dictionary<string, string>();
foreach (ConfigNode node in oidMappingNode.Children)
{
if (String.Compare(node.Name, "oidEntry", StringComparison.Ordinal) == 0)
{
string oidString = null;
string friendlyName = null;
foreach (DictionaryEntry attribute in node.Attributes)
{
if (String.Compare((string)attribute.Key, "OID", StringComparison.Ordinal) == 0)
oidString = (string)attribute.Value;
else if (String.Compare((string)attribute.Key, "name", StringComparison.Ordinal) == 0)
friendlyName = (string)attribute.Value;
}
if ((friendlyName != null) && (oidString != null))
oidMap.Add(friendlyName, oidString);
}
}
return oidMap;
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static ConfigNode OpenCryptoConfig()
{
string machineConfigFile = System.Security.Util.Config.MachineDirectory + MachineConfigFilename;
new FileIOPermission(FileIOPermissionAccess.Read, machineConfigFile).Assert();
if (!File.Exists(machineConfigFile))
return null;
CodeAccessPermission.RevertAssert();
ConfigTreeParser parser = new ConfigTreeParser();
ConfigNode rootNode = parser.Parse(machineConfigFile, "configuration", true);
if (rootNode == null)
return null;
// now, find the mscorlib tag with our version
ConfigNode mscorlibNode = null;
foreach (ConfigNode node in rootNode.Children)
{
bool versionSpecificMscorlib = false;
if (String.Compare(node.Name, "mscorlib", StringComparison.Ordinal) == 0)
{
foreach (DictionaryEntry attribute in node.Attributes)
{
if (String.Compare((string)attribute.Key, "version", StringComparison.Ordinal) == 0)
{
versionSpecificMscorlib = true;
if (String.Compare((string)attribute.Value, Version, StringComparison.Ordinal) == 0)
{
mscorlibNode = node;
break;
}
}
}
// if this mscorlib element did not have a version attribute, then use it
if (!versionSpecificMscorlib)
mscorlibNode = node;
}
// use the first matching mscorlib we find
if (mscorlibNode != null)
break;
}
if (mscorlibNode == null)
return null;
// now look for the first crypto settings element
foreach (ConfigNode node in mscorlibNode.Children)
{
if (String.Compare(node.Name, "cryptographySettings", StringComparison.Ordinal) == 0)
return node;
}
return null;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.Page.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI
{
public partial class Page : TemplateControl, System.Web.IHttpHandler
{
#region Methods and constructors
protected internal void AddContentTemplate (string templateName, ITemplate template)
{
}
public void AddOnPreRenderCompleteAsync (System.Web.BeginEventHandler beginHandler, System.Web.EndEventHandler endHandler, Object state)
{
}
public void AddOnPreRenderCompleteAsync (System.Web.BeginEventHandler beginHandler, System.Web.EndEventHandler endHandler)
{
}
protected internal void AddWrappedFileDependencies (Object virtualFileDependencies)
{
}
protected IAsyncResult AspCompatBeginProcessRequest (System.Web.HttpContext context, AsyncCallback cb, Object extraData)
{
return default(IAsyncResult);
}
protected void AspCompatEndProcessRequest (IAsyncResult result)
{
}
protected IAsyncResult AsyncPageBeginProcessRequest (System.Web.HttpContext context, AsyncCallback callback, Object extraData)
{
return default(IAsyncResult);
}
protected void AsyncPageEndProcessRequest (IAsyncResult result)
{
}
protected internal virtual new HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
{
return default(HtmlTextWriter);
}
public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
{
return default(HtmlTextWriter);
}
public void DesignerInitialize ()
{
}
protected internal virtual new System.Collections.Specialized.NameValueCollection DeterminePostBackMode ()
{
Contract.Requires (this.Context != null);
return default(System.Collections.Specialized.NameValueCollection);
}
public void ExecuteRegisteredAsyncTasks ()
{
}
public override Control FindControl (string id)
{
return default(Control);
}
protected override void FrameworkInitialize ()
{
}
public Object GetDataItem ()
{
return default(Object);
}
public string GetPostBackClientEvent (Control control, string argument)
{
return default(string);
}
public string GetPostBackClientHyperlink (Control control, string argument)
{
return default(string);
}
public string GetPostBackEventReference (Control control)
{
return default(string);
}
public string GetPostBackEventReference (Control control, string argument)
{
return default(string);
}
public virtual new int GetTypeHashCode ()
{
return default(int);
}
public ValidatorCollection GetValidators (string validationGroup)
{
Contract.Ensures (Contract.Result<System.Web.UI.ValidatorCollection>() != null);
return default(ValidatorCollection);
}
protected Object GetWrappedFileDependencies (string[] virtualFileDependencies)
{
Contract.Ensures (Contract.Result<System.Object>() == virtualFileDependencies);
Contract.Ensures (virtualFileDependencies.Length >= 0);
return default(Object);
}
protected virtual new void InitializeCulture ()
{
}
protected virtual new void InitOutputCache (int duration, string varyByHeader, string varyByCustom, OutputCacheLocation location, string varyByParam)
{
}
protected virtual new void InitOutputCache (int duration, string varyByContentEncoding, string varyByHeader, string varyByCustom, OutputCacheLocation location, string varyByParam)
{
}
protected internal virtual new void InitOutputCache (OutputCacheParameters cacheSettings)
{
Contract.Requires (cacheSettings != null);
Contract.Requires (this.Response.Cache != null);
}
public bool IsClientScriptBlockRegistered (string key)
{
return default(bool);
}
public bool IsStartupScriptRegistered (string key)
{
return default(bool);
}
protected internal virtual new Object LoadPageStateFromPersistenceMedium ()
{
return default(Object);
}
public string MapPath (string virtualPath)
{
return default(string);
}
protected internal override void OnInit (EventArgs e)
{
}
protected virtual new void OnInitComplete (EventArgs e)
{
}
protected virtual new void OnLoadComplete (EventArgs e)
{
}
protected virtual new void OnPreInit (EventArgs e)
{
}
protected virtual new void OnPreLoad (EventArgs e)
{
}
protected virtual new void OnPreRenderComplete (EventArgs e)
{
}
protected virtual new void OnSaveStateComplete (EventArgs e)
{
}
public Page ()
{
}
public virtual new void ProcessRequest (System.Web.HttpContext context)
{
}
protected virtual new void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
{
Contract.Requires (sourceControl != null);
}
public void RegisterArrayDeclaration (string arrayName, string arrayValue)
{
}
public void RegisterAsyncTask (PageAsyncTask task)
{
}
public virtual new void RegisterClientScriptBlock (string key, string script)
{
}
public virtual new void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
{
}
public void RegisterOnSubmitStatement (string key, string script)
{
}
public void RegisterRequiresControlState (Control control)
{
}
public void RegisterRequiresPostBack (Control control)
{
Contract.Requires (control != null);
}
public virtual new void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
{
}
public void RegisterRequiresViewStateEncryption ()
{
}
public virtual new void RegisterStartupScript (string key, string script)
{
}
public void RegisterViewStateHandler ()
{
}
protected internal override void Render (HtmlTextWriter writer)
{
}
public bool RequiresControlState (Control control)
{
return default(bool);
}
protected internal virtual new void SavePageStateToPersistenceMedium (Object state)
{
}
public void SetFocus (Control control)
{
}
public void SetFocus (string clientID)
{
Contract.Ensures (clientID.Trim().Length >= 1);
}
public void UnregisterRequiresControlState (Control control)
{
}
public virtual new void Validate (string validationGroup)
{
}
public virtual new void Validate ()
{
}
public virtual new void VerifyRenderingInServerForm (Control control)
{
}
#endregion
#region Properties and indexers
public System.Web.HttpApplicationState Application
{
get
{
return default(System.Web.HttpApplicationState);
}
}
protected bool AspCompatMode
{
get
{
return default(bool);
}
set
{
}
}
protected bool AsyncMode
{
get
{
return default(bool);
}
set
{
}
}
public TimeSpan AsyncTimeout
{
get
{
return default(TimeSpan);
}
set
{
}
}
public Control AutoPostBackControl
{
get
{
return default(Control);
}
set
{
}
}
public bool Buffer
{
get
{
Contract.Ensures (Contract.Result<bool>() == this.Response.BufferOutput);
return default(bool);
}
set
{
Contract.Ensures (value == this.Response.BufferOutput);
}
}
public System.Web.Caching.Cache Cache
{
get
{
Contract.Ensures (Contract.Result<System.Web.Caching.Cache>() != null);
return default(System.Web.Caching.Cache);
}
}
public string ClientQueryString
{
get
{
return default(string);
}
}
public ClientScriptManager ClientScript
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.ClientScriptManager>() != null);
return default(ClientScriptManager);
}
}
public string ClientTarget
{
get
{
return default(string);
}
set
{
}
}
public int CodePage
{
get
{
Contract.Requires (this.Response.ContentEncoding != null);
Contract.Ensures (this.Response.ContentEncoding != null);
Contract.Ensures (Contract.Result<int>() == this.Response.ContentEncoding.CodePage);
return default(int);
}
set
{
Contract.Ensures (this.Response.ContentEncoding != null);
}
}
public string ContentType
{
get
{
Contract.Ensures (Contract.Result<string>() == this.Response.ContentType);
return default(string);
}
set
{
Contract.Ensures (value == this.Response.ContentType);
}
}
internal protected override System.Web.HttpContext Context
{
get
{
return default(System.Web.HttpContext);
}
}
public string Culture
{
get
{
Contract.Ensures (Contract.Result<string>() == System.Threading.Thread.CurrentThread.CurrentCulture.DisplayName);
return default(string);
}
set
{
Contract.Requires (value != null);
}
}
public virtual new bool EnableEventValidation
{
get
{
return default(bool);
}
set
{
}
}
public override bool EnableViewState
{
get
{
return default(bool);
}
set
{
}
}
public bool EnableViewStateMac
{
get
{
return default(bool);
}
set
{
}
}
public string ErrorPage
{
get
{
return default(string);
}
set
{
}
}
protected System.Collections.ArrayList FileDependencies
{
set
{
}
}
public System.Web.UI.HtmlControls.HtmlForm Form
{
get
{
return default(System.Web.UI.HtmlControls.HtmlForm);
}
}
public System.Web.UI.HtmlControls.HtmlHead Header
{
get
{
return default(System.Web.UI.HtmlControls.HtmlHead);
}
}
public override string ID
{
get
{
return default(string);
}
set
{
}
}
public virtual new char IdSeparator
{
get
{
Contract.Requires (this.PageAdapter != null);
return default(char);
}
}
public bool IsAsync
{
get
{
return default(bool);
}
}
public bool IsCallback
{
get
{
return default(bool);
}
}
public bool IsCrossPagePostBack
{
get
{
return default(bool);
}
}
public bool IsPostBack
{
get
{
return default(bool);
}
}
public bool IsPostBackEventControlRegistered
{
get
{
return default(bool);
}
}
public bool IsReusable
{
get
{
return default(bool);
}
}
public bool IsValid
{
get
{
return default(bool);
}
}
public System.Collections.IDictionary Items
{
get
{
Contract.Ensures (Contract.Result<System.Collections.IDictionary>() != null);
return default(System.Collections.IDictionary);
}
}
public int LCID
{
get
{
Contract.Ensures (Contract.Result<int>() == System.Threading.Thread.CurrentThread.CurrentCulture.LCID);
return default(int);
}
set
{
}
}
public bool MaintainScrollPositionOnPostBack
{
get
{
return default(bool);
}
set
{
}
}
public MasterPage Master
{
get
{
return default(MasterPage);
}
}
public virtual new string MasterPageFile
{
get
{
return default(string);
}
set
{
}
}
public int MaxPageStateFieldLength
{
get
{
return default(int);
}
set
{
}
}
#if NETFRAMEWORK_4_0
public string MetaDescription
{
get
{
Contract.Requires (this.Page != null);
Contract.Requires (this.Page.Header != null);
return default(string);
}
set
{
Contract.Requires (this.Page != null);
}
}
public string MetaKeywords
{
get
{
Contract.Requires (this.Page != null);
Contract.Requires (this.Page.Header != null);
return default(string);
}
set
{
Contract.Requires (this.Page != null);
}
}
#endif
public System.Web.UI.Adapters.PageAdapter PageAdapter
{
get
{
return default(System.Web.UI.Adapters.PageAdapter);
}
}
protected virtual new PageStatePersister PageStatePersister
{
get
{
return default(PageStatePersister);
}
}
public System.Web.UI.Page PreviousPage
{
get
{
return default(System.Web.UI.Page);
}
}
public System.Web.HttpRequest Request
{
get
{
Contract.Ensures(Contract.Result<HttpRequest>() != null);
return default(System.Web.HttpRequest);
}
}
public System.Web.HttpResponse Response
{
get
{
Contract.Ensures (Contract.Result<System.Web.HttpResponse>() != null);
return default(System.Web.HttpResponse);
}
}
public string ResponseEncoding
{
get
{
Contract.Requires (this.Response.ContentEncoding != null);
Contract.Ensures (this.Response.ContentEncoding != null);
Contract.Ensures (this.Response.ContentEncoding.EncodingName != null);
Contract.Ensures (Contract.Result<string>() == this.Response.ContentEncoding.EncodingName);
return default(string);
}
set
{
Contract.Ensures (this.Response.ContentEncoding != null);
}
}
#if NETFRAMEWORK_4_0
public System.Web.Routing.RouteData RouteData
{
get
{
return default(System.Web.Routing.RouteData);
}
}
#endif
public System.Web.HttpServerUtility Server
{
get
{
Contract.Ensures (Contract.Result<System.Web.HttpServerUtility>() == this.Context.Server);
return default(System.Web.HttpServerUtility);
}
}
public virtual new System.Web.SessionState.HttpSessionState Session
{
get
{
return default(System.Web.SessionState.HttpSessionState);
}
}
public bool SmartNavigation
{
get
{
return default(bool);
}
set
{
}
}
public virtual new string StyleSheetTheme
{
get
{
return default(string);
}
set
{
}
}
public virtual new string Theme
{
get
{
return default(string);
}
set
{
}
}
public string Title
{
get
{
Contract.Requires (this.Page != null);
Contract.Requires (this.Page.Header != null);
return default(string);
}
set
{
Contract.Requires (this.Page != null);
}
}
public System.Web.TraceContext Trace
{
get
{
Contract.Ensures (Contract.Result<System.Web.TraceContext>() == this.Context.Trace);
return default(System.Web.TraceContext);
}
}
public bool TraceEnabled
{
get
{
Contract.Requires (this.Trace != null);
Contract.Ensures (Contract.Result<bool>() == this.Trace.IsEnabled);
Contract.Ensures (this.Trace == this.Context.Trace);
return default(bool);
}
set
{
Contract.Requires (this.Trace != null);
Contract.Ensures (this.Trace == this.Context.Trace);
Contract.Ensures (value == this.Trace.IsEnabled);
}
}
public System.Web.TraceMode TraceModeValue
{
get
{
Contract.Requires (this.Trace != null);
Contract.Ensures (Contract.Result<System.Web.TraceMode>() == this.Trace.TraceMode);
Contract.Ensures (this.Trace == this.Context.Trace);
return default(System.Web.TraceMode);
}
set
{
Contract.Requires (this.Trace != null);
Contract.Ensures (this.Trace == this.Context.Trace);
Contract.Ensures (value == this.Trace.TraceMode);
}
}
protected int TransactionMode
{
get
{
return default(int);
}
set
{
}
}
public string UICulture
{
get
{
Contract.Ensures (Contract.Result<string>() == System.Threading.Thread.CurrentThread.CurrentUICulture.DisplayName);
return default(string);
}
set
{
Contract.Requires (value != null);
}
}
internal protected virtual new string UniqueFilePathSuffix
{
get
{
return default(string);
}
}
public System.Security.Principal.IPrincipal User
{
get
{
Contract.Ensures (Contract.Result<System.Security.Principal.IPrincipal>() == this.Context.User);
return default(System.Security.Principal.IPrincipal);
}
}
public ValidatorCollection Validators
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.ValidatorCollection>() != null);
return default(ValidatorCollection);
}
}
public ViewStateEncryptionMode ViewStateEncryptionMode
{
get
{
return default(ViewStateEncryptionMode);
}
set
{
}
}
public string ViewStateUserKey
{
get
{
return default(string);
}
set
{
}
}
public override bool Visible
{
get
{
return default(bool);
}
set
{
}
}
#endregion
#region Fields
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
public class AIScript : MonoBehaviour {
public static Cell.CellOcc AIType = Cell.CellOcc.X;
public static Cell.CellOcc HumanType = Cell.CellOcc.O;
[HideInInspector]
private int DIFFICULTY = 2;
public int Difficulty { get { return DIFFICULTY; } }
private int DEEP_MAX = 2;
/// <summary>
/// What's the chance that the ai simply skips a place where it could place, it just doesn't examine it.
/// It will also add some depending on the points in game (heuristic for the game's complexity)
/// </summary>
private float leaveOutChance = 0.25f;
/// <summary>
/// After how many sign the AI should miss 100%
/// </summary>
private int afterSignCountMiss = 200;
private Grid grid;
private AITTTGameLogic gameLogic;
private System.Random rand;
/// <summary>
/// All the signPos in aiLocalPos in the game
/// </summary>
private List<IntVector2> pointsInGame;
/// <summary>
/// The first point in current game, used for exchanging gridPos to aiLocalPos<para />
/// This is 0, 0
/// </summary>
private IntVector2 firstPointInGame;
/// <summary>
/// Stores the current gamefield<para />
/// if there is no sign there it is NONE<para />
/// At first it is a 51 * 51 array, if it is exceeded then it will be replaced in a (x + 50) * (x + 50)<para />
/// 0, 0 is at [length / 2, length / 2]<para />
/// </summary>
private EvaluationField[,] gameField;
/// <summary>
/// Where the field's botleft is in gameField
/// </summary>
private IntVector2 bottomLeftPosOfField;
/// <summary>
/// Where the field's topright is in gameField
/// </summary>
private IntVector2 topRightPosOfField;
/// <summary>
/// Top right position of all the signs so far
/// </summary>
private IntVector2 topRightAll = new IntVector2();
/// <summary>
/// Bottom left position of all the signs so far
/// </summary>
private IntVector2 bottomLeftAll = new IntVector2();
private bool gameInProgress = false;
void Start() {
rand = new System.Random();
grid = GetComponent<Grid>();
gameLogic = GetComponent<AITTTGameLogic>();
Reset();
// subscribe to events
grid.SignWasPlacedEvent += SignWasAdded;
grid.SignWasRemovedEvent += SignWasRemoved;
gameLogic.SomeoneWonGameEvent += SomeoneWonGame;
}
/// <summary>
/// Returns whether the game is currently in progress
/// </summary>
/// <returns></returns>
public bool IsGameInProgress() {
return pointsInGame.Count > 1 && gameInProgress;
}
/// <summary>
/// Event for when someone has won the game
/// </summary>
private void SomeoneWonGame(Cell.CellOcc type) {
gameInProgress = false;
if (type == HumanType) {
PreferencesScript.Instance.PullExpBarThenAdd((int) GetGameWonExp());
} else {
PreferencesScript.Instance.PullExpBarThenAdd((int) GetGameLostExp());
}
}
private int[,] playerExpTable = new int[,] {
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 75, 20, 5 },
{ 100, 45, 15 }
};
/// <summary>
/// How much exp the player gets for winning this game
/// </summary>
private float GetGameWonExp() {
// Add for every sign in the game
float exp = pointsInGame.Count * 1.7f;
// Add for base for playing/winning
exp += 270;
// Add for every player's signinarow
for (int i = 0; i < pointsInGame.Count; i++) {
foreach (SignInARow signInARow in gameField[pointsInGame[i].x, pointsInGame[i].y].signsInARow) {
int length = signInARow.Length;
if (signInARow.Type == HumanType) {
if (length >= 3 && length <= 4) exp += playerExpTable[length, signInARow.BlockCount()];
} else {
exp += signInARow.BlockCount() * 0.5f * length; // Add for every blocked
}
}
}
// Difficulty
return exp * (1f - Mathf.Min(leaveOutChance * 1.6f, 1f));
}
/// <summary>
/// How much exp the player gets for losing this game
/// </summary>
/// <returns></returns>
private float GetGameLostExp() {
return GetGameWonExp() * 0.3f;
}
/// <summary>
/// 0 - Baby; 1 - Easy; 2 - Normal; 3 - Hard; 4 - Impossible
/// </summary>
public void SetDifficulty(int diff) {
DIFFICULTY = diff;
switch (diff) {
case 0:
leaveOutChance = 0.8f;
break;
case 1:
leaveOutChance = 0.57f;
break;
case 2:
leaveOutChance = 0.25f;
break;
case 3:
leaveOutChance = 0.05f;
break;
case 4:
leaveOutChance = 0f;
break;
}
}
/// <summary>
/// Called from grid in event when a sign was removed
/// </summary>
private void SignWasRemoved(int[] gridPos) {
// RemoveLastPoint();
}
/// <summary>
/// Called from grid in event when sign was placed
/// </summary>
private void SignWasAdded(int[] gridPos, Cell.CellOcc type) {
// first point placed in this game
if (firstPointInGame == null) {
gameInProgress = true;
SetLocalGridDisabled(new int[] { gridPos[0] - gameField.GetLength(0) / 2, gridPos[1] - gameField.GetLength(1) / 2 });
}
// Set the all bounds if needed
if (gridPos[0] < bottomLeftAll.x) bottomLeftAll.x = gridPos[0];
if (gridPos[1] < bottomLeftAll.y) bottomLeftAll.y = gridPos[1];
if (gridPos[0] > topRightAll.x) topRightAll.x = gridPos[0];
if (gridPos[1] > topRightAll.y) topRightAll.y = gridPos[1];
IntVector2 pos = GridToLocalAIPos(gridPos);
AddPoint(pos, type);
}
/// <summary>
/// Adds a point to both the gameField and pointsingame list
/// </summary>
/// <param name="pos"></param>
private void AddPoint(IntVector2 pos, Cell.CellOcc type) {
// We already have a pos there so just return
// This shouldn't happen but just in case it does we are ready
if (gameField[pos.x, pos.y].type != Cell.CellOcc.NONE) return;
gameField[pos.x, pos.y].type = type;
pointsInGame.Add(pos);
// Set the bound of our game correctly
if (pos.x < bottomLeftPosOfField.x) bottomLeftPosOfField.x = pos.x;
if (pos.y < bottomLeftPosOfField.y) bottomLeftPosOfField.y = pos.y;
if (pos.x > topRightPosOfField.x) topRightPosOfField.x = pos.x;
if (pos.y > topRightPosOfField.y) topRightPosOfField.y = pos.y;
List<PlaceData> placeData;
NewSignPlaced(gameField, pos, out placeData, out placeData);
}
/// <summary>
/// Returns the signsinarow points summed up in the gamefield we give it
/// </summary>
private float GetPointsFromSignsInARow(EvaluationField[,] field, List<IntVector2> pointsInGame, IntVector2 lastPlaced, out float aiPoint, out float humanPoint) {
for (int i = lastPlaced.x - Grid.WIN_CONDITION; i <= lastPlaced.x + Grid.WIN_CONDITION; i++) {
for (int j = lastPlaced.y - Grid.WIN_CONDITION; j <= lastPlaced.y + Grid.WIN_CONDITION; j++) {
foreach (SignInARow signInARow in field[i, j].signsInARow) {
signInARow.UpdatePoints();
}
}
}
// Update end blocks
float aiP = 0f, humP = 0f;
for (int i = 0; i < pointsInGame.Count; i++) {
foreach (SignInARow signInARow in field[pointsInGame[i].x, pointsInGame[i].y].signsInARow)
if (signInARow.Type == AIType)
aiP += signInARow.PointsWorth;
else
humP += signInARow.PointsWorth;
}
aiPoint = aiP; humanPoint = humP;
return aiP + humP;
}
/// <summary>
/// If there is no firstPointInGame it will assign the given gridPos as that
/// </summary>
/// <param name="gridPos"></param>
private IntVector2 GridToLocalAIPos(int[] gridPos) {
if (firstPointInGame == null) {
firstPointInGame = new IntVector2(gridPos[0], gridPos[1]);
}
// Get the point relative to firstpointingame then add the half of the array length in order to have 0, 0 at the middle of array
return new IntVector2(gridPos[0] - firstPointInGame.x + gameField.GetLength(0) / 2, gridPos[1] - firstPointInGame.y + gameField.GetLength(1) / 2);
}
/// <summary>
/// Disables int the local gameField the points, which are disabled in grid<para />
/// Requires the (0,0) point in gridPos of the gameField
/// </summary>
private void SetLocalGridDisabled(int[] zerozero) {
for (int i = 0; i < gameField.GetLength(0); i++) {
for (int k = 0; k < gameField.GetLength(1); k++) {
if (i == gameField.GetLength(0) / 2 && k == gameField.GetLength(1) / 2) continue;
CellHolder ch = grid.GetCellHolderAtGridPos(new int[] { zerozero[0] + i, zerozero[1] + k });
if (!(ch == null || ch.CurrentTemplate.cellOcc == Cell.CellOcc.NONE)) {
gameField[i, k].type = Cell.CellOcc.BLOCKED; // Because it checks for NONEs in algorithm
}
}
}
}
private int[] LocalAIToGridPos(IntVector2 pos) {
return LocalAIToGridPos(pos.x, pos.y);
}
private int[] LocalAIToGridPos(int x, int y) {
return new int[] {
x + firstPointInGame.x - gameField.GetLength(0) / 2,
y + firstPointInGame.y - gameField.GetLength(1) / 2
};
}
private int[,] checkDirections = new int[,] {
{ -1, 1 },
{ -1, 0 },
{ -1, -1 },
{ 0, -1 }
};
/// <summary>
/// Adds the new signsInARow and removes the ones which overlap
/// </summary>
private void NewSignPlaced(EvaluationField[,] field, IntVector2 where, out List<PlaceData> placed, out List<PlaceData> removed) {
Cell.CellOcc currentType = field[where.x, where.y].type;
List<PlaceData> _placed = new List<PlaceData>();
List<PlaceData> _removed = new List<PlaceData>();
// Check how many signs there are in a row that contains the where sign
for (int i = 0; i < checkDirections.GetLength(0); i++) {
int count = 1;
IntVector2 endOne = new IntVector2(where), endTwo = new IntVector2(where);
// Go through the checkdirection direction
for (int j = 1; j < Grid.WIN_CONDITION; j++) {
int examineX = where.x + checkDirections[i, 0] * j;
int examineY = where.y + checkDirections[i, 1] * j;
// We are in bounds
//if (examineX >= 0 && examineX < field.GetLength(0) && examineY >= 0 && examineY < field.GetLength(1)) {
// It is the same sign
if (field[examineX, examineY].type == currentType) {
count++;
endOne = new IntVector2(examineX, examineY);
} else {
break;
}
}
// Go through the opposite of checkdirection direction
for (int j = 1; j < Grid.WIN_CONDITION; j++) {
int examineX = where.x + -checkDirections[i, 0] * j;
int examineY = where.y + -checkDirections[i, 1] * j;
// We are in bounds
//if (examineX >= 0 && examineX < field.GetLength(0) && examineY >= 0 && examineY < field.GetLength(1)) {
// It is the same sign
if (field[examineX, examineY].type == currentType) {
count++;
endTwo = new IntVector2(examineX, examineY);
} else {
break;
}
}
if (count < 2) continue;
// Now we have the endpoints of this checkdirection in endpoint one and endpoint two
// We also have if there are blocks at the end if there is not then the block variables are null
SignInARow signsInARow = new SignInARow(endOne, endTwo, currentType);
IntVector2 end1 = signsInARow.From - signsInARow.Steepness, end2 = signsInARow.To + signsInARow.Steepness;
signsInARow.SetEndEvaluationFields(field[end1.x, end1.y], field[end2.x, end2.y]);
SignInARow removedSignInARow = null;
field[where.x, where.y].AddSignInARow(signsInARow, out removedSignInARow);
_placed.Add(new PlaceData(new IntVector2(where), signsInARow));
if (removedSignInARow != null) _removed.Add(new PlaceData(new IntVector2(where), removedSignInARow));
}
placed = _placed; removed = _removed;
}
/// <summary>
/// A recursive minimax algorithm with alpha beta pruning
/// </summary>
private EvaluationResult EvaluateField(EvaluationField[,] field, Cell.CellOcc whoseTurn, int deepCount, List<IntVector2> pointsInGame, float alpha, float beta) {
EvaluationResult result = new EvaluationResult(whoseTurn == HumanType ? int.MaxValue : int.MinValue, new IntVector2());
List<IntVector2> been = new List<IntVector2>();
int pointsInGameLength = pointsInGame.Count;
bool alphaBetaEnd = false;
// Go through the places where we can place
// Call NewSignPlaced with field and position where we want to place
for (int j = pointsInGame.Count - 1; j >= 0; j--) {
// In each direction
for (int i = -1; i <= 1 && !alphaBetaEnd; i++) {
for (int k = -1; k <= 1 && !alphaBetaEnd; k++) {
// we just skip a place if we feel like, just to make AI a bit easier
if (rand.NextDouble() <= leaveOutChance + pointsInGame.Count / (float) afterSignCountMiss) continue;
IntVector2 pos = new IntVector2(pointsInGame[j].x + i, pointsInGame[j].y + k);
// Not 0 0 and in bounds
if (!(i == 0 && k == 0) /*&& pos.x >= 0 && pos.x < field.GetLength(0) && pos.y >= 0 && pos.y < field.GetLength(1)*/
&& field[pos.x, pos.y].type == Cell.CellOcc.NONE && !been.Contains(pos)) { // if we haven't checked this position and the type of cell we are examining is NONE, so empty
been.Add(pos);
// Data so we can revert the field back (because recursive algorithm)
List<PlaceData> placed;
List<PlaceData> removed;
// Set the examined cell to the current's sign
field[pos.x, pos.y].type = whoseTurn;
// Place that sign and while that's happening determine signsinarow
NewSignPlaced(field, pos, out placed, out removed);
pointsInGame.Add(new IntVector2(pos));
// Go recursively until DIFFICULTY
EvaluationResult evalResult;
if (deepCount == DEEP_MAX) {
float aiPoint, humanPoint;
GetPointsFromSignsInARow(field, pointsInGame, pos, out aiPoint, out humanPoint);
if (whoseTurn == AIType)
evalResult.points = aiPoint + humanPoint * 1.5f;
else
evalResult.points = aiPoint * 1.5f + humanPoint;
evalResult.fieldPos = new IntVector2(pos);
} else {
evalResult = EvaluateField(field, SignResourceStorage.GetOppositeOfSign(whoseTurn), deepCount + 1, pointsInGame, alpha, beta);
}
// If it is human's turn we search for min value - MINIMIZER
if (whoseTurn == HumanType) {
if (result.points > evalResult.points) {
result.points = evalResult.points;
result.fieldPos = new IntVector2(pos);
}
beta = Mathf.Min(beta, result.points);
// If the points here is smaller than the best value for the parent maximizer then we don't have to search further because this minimizer
// potentially has the chance of picking this minimum value, which the parent maximizer will never pick otherwise if this minimizer
// doesn't pick this vaue it's only gonna pick a smaller one which is even worse for the maximizer
// so just stop the search
if (result.points <= alpha) {
alphaBetaEnd = true;
}
}
// Otherwise if it is AI's turn we search for the max points - MAXIMIZER
else if (whoseTurn == AIType) {
if (result.points < evalResult.points) {
result.points = evalResult.points;
result.fieldPos = new IntVector2(pos);
}
alpha = Mathf.Max(alpha, result.points);
// if the point is higher then the minimizer minimum then we don't need to search further because this maximizer
// will surely pick a greater value for the parent minimizer, than it already has
if (result.points >= beta) {
alphaBetaEnd = true;
}
}
// Revert the field back
for (int l = 0; l < placed.Count; l++)
field[placed[l].fieldPos.x, placed[l].fieldPos.y].signsInARow.Remove(placed[l].signInARow);
for (int l = 0; l < removed.Count; l++)
field[removed[l].fieldPos.x, removed[l].fieldPos.y].signsInARow.Add(removed[l].signInARow);
field[pos.x, pos.y].type = Cell.CellOcc.NONE;
pointsInGame.RemoveAt(pointsInGame.Count - 1);
}
}
}
}
return result;
}
private IntVector2 WhichIsBetter(IntVector2 first, IntVector2 second, Cell.CellOcc placeType) {
float[] points = new float[2];
for (int j = 0; j < 2; j++) {
IntVector2 pos = j == 0 ? first : second;
// Data so we can revert the field back (because recursive algorithm)
List<PlaceData> placed;
List<PlaceData> removed;
// Set the examined cell to the current's sign
gameField[pos.x, pos.y].type = placeType;
NewSignPlaced(gameField, pos, out placed, out removed);
pointsInGame.Add(new IntVector2(pos));
float aiPoints, humPoints;
points[j] = GetPointsFromSignsInARow(gameField, pointsInGame, pos, out aiPoints, out humPoints);
// Revert the field back
for (int l = 0; l < placed.Count; l++)
gameField[placed[l].fieldPos.x, placed[l].fieldPos.y].signsInARow.Remove(placed[l].signInARow);
for (int l = 0; l < removed.Count; l++)
gameField[removed[l].fieldPos.x, removed[l].fieldPos.y].signsInARow.Add(removed[l].signInARow);
gameField[pos.x, pos.y].type = Cell.CellOcc.NONE;
pointsInGame.RemoveAt(pointsInGame.Count - 1);
}
if (placeType == AIType) // We are maximizing
return points[0] > points[1] ? first : second;
else // We are minimizing
return points[0] > points[1] ? second : first;
}
public int[] StartEvaluation() {
// ________________________________________ FIRST POINT __________________________________________________
// There is only one placed in the game so just randomize it because otherwise it only places where we examine first
if (pointsInGame.Count < 2) {
System.Random rand = new System.Random();
IntVector2 random;
do {
random = new IntVector2(rand.Next(0, 3) - 1, rand.Next(0, 3) - 1);
} while (random.x == 0 && random.y == 0);
return LocalAIToGridPos(pointsInGame[0] + random);
}
// _____________________________________ DEFENSE EVAL __________________________________________
// It' only a defending mechanism so only checks for human pointsinrow
// try places where we surely have to place
// it has a smaller chance that it skips that position
SignInARow humThree = null, humFour = null;
SignInARow aiThree = null, aiFour = null;
int tillI = pointsInGame.Count;
float exponentialChance = Mathf.Pow(leaveOutChance, 1.55f);
for (int i = 0; i < tillI; i++) {
List<SignInARow> list = gameField[pointsInGame[i].x, pointsInGame[i].y].signsInARow;
for (int k = 0; k < list.Count; k++) {
// skip at random
if (rand.NextDouble() < exponentialChance) continue;
int length = list[k].Length;
int blockCount = list[k].BlockCount();
if (length == 3 && blockCount == 0) {
// Store it so if after this loop we don't find a four (we don't return) place there
if (list[k].Type == HumanType)
humThree = list[k];
else
aiThree = list[k];
} else if (length == 4 && blockCount != 2) {
// It prioritizes the fours so if it finds one place there
if (list[k].Type == HumanType) {
humFour = list[k];
} else { // There is a 4 length that is AIType so place there
aiFour = list[k];
}
}
}
}
// First if there is a four type ai where we can place win the game
if (aiFour != null) return LocalAIToGridPos(aiFour.GetUnblockedPos());
// If there is a four that is type of human we should really place there
if (humFour != null) return LocalAIToGridPos(humFour.GetUnblockedPos());
// If there is a signinarow with aitype that is length of three decide which is better and return that
if (aiThree != null) {
return LocalAIToGridPos(WhichIsBetter(aiThree.GetBlockField1Pos(), aiThree.GetBlockField2Pos(), AIType));
}
// If there is no three with AI type but there is one for the human decide which is better
if (humThree != null) { // We are going to decide which position is better
return LocalAIToGridPos(WhichIsBetter(humThree.GetBlockField1Pos(), humThree.GetBlockField2Pos(), AIType));
}
// Come here is everything else fails
// ___________________ NORMAL EVAL _____________________________-
EvaluationResult result = new EvaluationResult();
try {
result = EvaluateField(gameField, AIType, 1, pointsInGame, int.MinValue, int.MaxValue);
} catch (Exception e) {
UnityEngine.Debug.Log(e.Message + "\n" + e.StackTrace);
}
return LocalAIToGridPos(result.fieldPos);
}
/// <summary>
/// Places down a random sign in world while taking the already placed signs into consideration
/// </summary>
/// <returns></returns>
public int[] PlaceDownRandom() {
IntVector2 pos; CellHolder ch;
do {
// It allocates a rectangle for the game, so it doesn't place it in another game (thats innerR) but just for good measures we put it in a dowhile
float r = 20f;
Vector2 vect = UnityEngine.Random.insideUnitCircle * r;
pos = topRightAll + new IntVector2((int) vect.x, (int) vect.y);
ch = grid.GetCellHolderAtGridPos(LocalAIToGridPos(pos.x, pos.y));
} while (!(ch == null || ch.CurrentTemplate.cellOcc == Cell.CellOcc.NONE));
return LocalAIToGridPos(pos);
}
/// <summary>
/// It is called from AITTTGL StartNewGame
/// </summary>
public void Reset() {
bottomLeftPosOfField = new IntVector2(int.MaxValue, int.MaxValue);
topRightPosOfField = new IntVector2(int.MinValue, int.MinValue);
gameField = new EvaluationField[100, 100];
pointsInGame = new List<IntVector2>();
for (int i = 0; i < gameField.GetLength(0); i++)
for (int k = 0; k < gameField.GetLength(1); k++)
gameField[i, k] = new EvaluationField(new IntVector2(i, k));
firstPointInGame = null;
}
}
internal struct EvaluationResult {
public float points;
public IntVector2 fieldPos;
public EvaluationResult(float points, IntVector2 fieldPos) {
this.points = points;
this.fieldPos = fieldPos;
}
}
/// <summary>
/// Used for storing which signinarows we removed or added so we can revert the field back while going through the field tree
/// </summary>
internal struct PlaceData {
public IntVector2 fieldPos;
public SignInARow signInARow;
public PlaceData(IntVector2 pos, SignInARow signInARow) {
this.fieldPos = pos;
this.signInARow = signInARow;
}
}
internal class EvaluationField {
public Cell.CellOcc type = Cell.CellOcc.NONE;
public IntVector2 posInGameField;
/// <summary>
/// Stores signs next to each other that star from this sign
/// </summary>
public List<SignInARow> signsInARow;
public EvaluationField(IntVector2 posInGameField) {
this.posInGameField = posInGameField;
signsInARow = new List<SignInARow>();
type = Cell.CellOcc.NONE;
}
public EvaluationField(Cell.CellOcc type, IntVector2 posInGameField) : this(posInGameField) {
this.type = type;
}
/// <summary>
/// If there is a signInARow that has the same steepness then it will remove that first then add this
/// </summary>
public void AddSignInARow(SignInARow inARow, out SignInARow removed) {
removed = null;
// We remove the one with the same steepness because they overlap and so the longer one should be added (which we think is the new InARow)
for (int i = signsInARow.Count - 1; i >= 0; i--) {
// We have a signinarow which has the same steepness so
if (signsInARow[i].Steepness == inARow.Steepness) {
removed = signsInARow[i];
signsInARow.RemoveAt(i);
break;
}
}
signsInARow.Add(inARow);
}
}
internal class IntVector2 : IEquatable<IntVector2> {
public int x;
public int y;
public IntVector2(IntVector2 vector) {
this.x = vector.x;
this.y = vector.y;
}
public IntVector2(int x, int y) {
this.x = x;
this.y = y;
}
public IntVector2() {
x = 0; y = 0;
}
//________________________________OPERATORS______________________________
public static IntVector2 operator +(IntVector2 first, IntVector2 second) {
return new IntVector2(first.x + second.x, first.y + second.y);
}
public static IntVector2 operator +(IntVector2 vect, int number) {
return new IntVector2(vect.x + number, vect.y + number);
}
public static IntVector2 operator -(IntVector2 vect1, IntVector2 vect2) {
return new IntVector2(vect1.x - vect2.x, vect1.y - vect2.y);
}
public static IntVector2 operator /(IntVector2 vect, int number) {
return new IntVector2(vect.x / number, vect.y / number);
}
public static bool operator ==(IntVector2 vect1, IntVector2 vect2) {
if (object.ReferenceEquals(vect1, null)) {
return object.ReferenceEquals(vect2, null);
}
if (object.ReferenceEquals(vect2, null)) {
return object.ReferenceEquals(vect1, null);
}
return vect1.x == vect2.x && vect1.y == vect2.y;
}
public static bool operator !=(IntVector2 vect1, IntVector2 vect2) {
if (object.ReferenceEquals(vect1, null)) {
return !object.ReferenceEquals(vect1, null);
}
if (object.ReferenceEquals(vect2, null)) {
return !object.ReferenceEquals(vect2, null);
}
return vect1.x != vect2.x || vect1.y != vect2.y;
}
/// <summary>
/// Returns the smaller vector of the two
/// </summary>
public static IntVector2 GetSmaller(IntVector2 one, IntVector2 two) {
if (one.y != two.y) {
if (one.x < two.x) {
return one;
} else {
return two;
}
} else {
if (one.y < two.y) {
return one;
} else {
return two;
}
}
}
public bool Equals(IntVector2 other) {
return other == this;
}
public override int GetHashCode() {
return string.Format("{0}--{1]", x, y).GetHashCode();
}
public override bool Equals(object obj) {
if (obj is IntVector2) {
return (IntVector2) obj == this;
}
return base.Equals(obj);
}
public override string ToString() {
return string.Format("X: {0} and Y: {1}", x, y);
}
}
internal class SignInARow : IEquatable<SignInARow> {
private IntVector2 from;
public IntVector2 From { get { return from; } }
private IntVector2 to;
public IntVector2 To { get { return to; } }
private IntVector2 steepness;
public IntVector2 Steepness { get { return steepness; } }
private EvaluationField blockField1;
public IntVector2 GetBlockField1Pos() { return blockField1.posInGameField; }
private EvaluationField blockField2;
public IntVector2 GetBlockField2Pos() { return blockField2.posInGameField; }
/// <summary>
/// Returns the first unblocked pos it finds. Otherwise just a (-1, -1) vector.
/// </summary>
/// <returns></returns>
public IntVector2 GetUnblockedPos() {
if (blockField1.type == Cell.CellOcc.NONE) return blockField1.posInGameField;
else if (blockField2.type == Cell.CellOcc.NONE) return blockField2.posInGameField;
return new IntVector2(-1, -1);
}
private float points;
public float PointsWorth { get { return points; } }
public float PointsWorthRecounted {
get {
int length = Length;
points = (type == AIScript.AIType ? pointTable[length > 5 ? 5 : length, BlockCount()] : pointTableHuman[length > 5 ? 5 : length, BlockCount()]);
return points;
}
}
public int Length { get { return Mathf.Max(Mathf.Abs(to.x - from.x), Mathf.Abs(to.y - from.y)) + 1; } }
private Cell.CellOcc type = Cell.CellOcc.NONE;
public Cell.CellOcc Type { get { return type; } }
private float[,] pointTable = new float[,] {
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 15, 6, 0.5f },
{ 10000, 50, 10 },
{ 50000, 15000, 200 },
{ 999999, 999999, 999999 }
};
private float[,] pointTableHuman = new float[,] {
{ 0, 0, 0 },
{ 0, 0, 0 },
{ -15, -6, -0.5f },
{ -25000, -50, -10 },
{ -100000, -50000, -200 },
{ -999999, -999999, -999999 }
};
public SignInARow(IntVector2 one, IntVector2 two, Cell.CellOcc type) {
this.type = type;
SetPoints(one, two, type);
}
public void SetEndEvaluationFields(EvaluationField one, EvaluationField two) {
this.blockField1 = one;
this.blockField2 = two;
}
public int BlockCount() {
Cell.CellOcc oppType = SignResourceStorage.GetOppositeOfSign(type);
bool block1 = blockField1.type == oppType || blockField1.type == Cell.CellOcc.BLOCKED;
bool block2 = blockField2.type == oppType || blockField2.type == Cell.CellOcc.BLOCKED;
if (block1 && block2) return 2;
else if (block1 || block2) return 1;
else return 0;
}
/// <summary>
/// DYDD<para />
/// DYXD<para />
/// DYYD<para />
/// All ys are smaller than x<para />
/// Always sets the smaller of the to vectors to be in the from vector<para />
/// Also sets the steepness as well<para />
/// Also updates points and length<para />
/// </summary>
public void SetPoints(IntVector2 from, IntVector2 to, Cell.CellOcc type) {
if (from.y == to.y) {
if (from.x < to.x) {
this.from = new IntVector2(from);
this.to = new IntVector2(to);
} else {
this.from = new IntVector2(to);
this.to = new IntVector2(from);
}
} else {
if (from.y < to.y) {
this.from = new IntVector2(from);
this.to = new IntVector2(to);
} else {
this.from = new IntVector2(to);
this.to = new IntVector2(from);
}
}
steepness = new IntVector2((this.to.x - this.from.x), (this.to.y - this.from.y));
steepness = steepness / Mathf.Max(Mathf.Abs(steepness.x), Mathf.Abs(steepness.y));
}
public void UpdatePoints(Cell.CellOcc type) {
int length = Length;
points = (type == AIScript.AIType ? pointTable[Mathf.Min(5, length), BlockCount()] : pointTableHuman[Mathf.Min(5, length), BlockCount()]);
}
public void UpdatePoints() {
UpdatePoints(type);
}
private float GetLengthMultiplier(int length) {
switch (length) {
case 2: return 0.5f;
case 3: return 1.5f;
case 4: return 3f;
}
return 1f;
}
public bool Equals(SignInARow other) {
return from == other.from && to == other.to;
}
}
| |
//==============================================================================
// TorqueLab -> ShapeLab -> Shape Selection
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
function ShapeLab::updateCollisionMesh( %this, %type, %target, %depth, %merge, %concavity,
%maxVerts, %boxMax, %sphereMax, %capsuleMax ) {
%colDetailSize = -1;
%colNode = "Col" @ %colDetailSize;
// TreeView items are case sensitive, but TSShape names are not, so fixup case
// if needed
%index = ShapeLab.shape.getNodeIndex( %colNode );
if ( %index != -1 )
%colNode = ShapeLab.shape.getNodeName( %index );
// First remove the old detail and collision nodes
%meshList = ShapeLab.getDetailMeshList( %colDetailSize );
%meshCount = getFieldCount( %meshList );
if ( %meshCount > 0 ) {
ShapeLab.shape.removeDetailLevel( %colDetailSize );
for ( %i = 0; %i < %meshCount; %i++ )
ShapeLab.onMeshRemoved( getField( %meshList, %i ) );
}
%nodeList = ShapeLab.getNodeNames("Col-1", "" );
%nodeCount = getFieldCount( %nodeList );
if ( %nodeCount > 0 ) {
for ( %i = 0; %i < %nodeCount; %i++ )
ShapeLab.shape.removeNode( getField( %nodeList, %i ) );
ShapeLab.onNodeRemoved( %nodeList, %nodeCount );
}
devLog("Collision type to be created", %type);
// Add the new node and geometry
if ( %type $= "" )
return;
if ( !ShapeLab.shape.addCollisionDetail( %colDetailSize, %type, %target,
%depth, %merge, %concavity, %maxVerts,
%boxMax, %sphereMax, %capsuleMax ) )
return false;
devLog("Collision created", %type, %target,
%depth, %merge, %concavity, %maxVerts,
%boxMax, %sphereMax, %capsuleMax);
// Update UI
%meshList = ShapeLab.getDetailMeshList( %colDetailSize );
ShapeLab.onNodeAdded( %colNode, ShapeLab.shape.getNodeCount() ); // will also add child nodes
%count = getFieldCount( %meshList );
for ( %i = 0; %i < %count; %i++ )
ShapeLab.onMeshAdded( getField( %meshList, %i ) );
ShapeLabCollisions.lastColSettings = %type TAB %target TAB %depth TAB %merge TAB
%concavity TAB %maxVerts TAB %boxMax TAB %sphereMax TAB %capsuleMax;
ShapeLabCollisions.onCollisionChanged();
return true;
}
//==============================================================================
function ShapeLabCollisions::revertChanges( %this ) {
devLog("ShapeLabCollisions::revertChanges(%this)",%this);
}
//------------------------------------------------------------------------------
//==============================================================================
function ShapeLabCollisions::updateHulls( %this ) {
devLog("ShapeLabCollisions::updateHulls(%this)",%this);
}
//------------------------------------------------------------------------------
//==============================================================================
function ShapeLabCollisions::editCollision( %this ) {
// If the shape already contains a collision detail size-1, warn the user
// that it will be removed
if ( ( ShapeLab.shape.getDetailLevelIndex( -1 ) >= 0 ) &&
( getField(%this.lastColSettings, 0) $= "" ) ) {
LabMsgYesNo( "Warning", "Existing collision geometry at detail size " @
"-1 will be removed, and this cannot be undone. Do you want to continue?",
"ShapeLabCollisions.editCollisionOK();", "" );
} else {
%this.editCollisionOK();
}
}
//------------------------------------------------------------------------------
//==============================================================================
$NoColUndo = true;
function ShapeLabCollisions::editCollisionOK( %this ) {
%type = %this-->colType.getText();
%target = %this-->colTarget.getText();
%depth = %this-->hullDepth.getValue();
%merge = %this-->hullMergeThreshold.getValue();
%concavity = %this-->hullConcaveThreshold.getValue();
%maxVerts = %this-->hullMaxVerts.getValue();
%maxBox = %this-->hullMaxBoxError.getValue();
%maxSphere = %this-->hullMaxSphereError.getValue();
%maxCapsule = %this-->hullMaxCapsuleError.getValue();
if (%type $= "convex hulls"){
devLog("convex hulls-- %target, %depth, %merge, %concavity, %maxVerts, %maxBox, %maxSphere, %maxCapsule");
devLog( %target, %depth, %merge, %concavity, %maxVerts, %maxBox, %maxSphere, %maxCapsule);
}
if ($NoColUndo)
ShapeLab.updateCollisionMesh( %type, %target, %depth, %merge, %concavity, %maxVerts,
%maxBox, %maxSphere, %maxCapsule );
else
ShapeLab.doEditCollision( %type, %target, %depth, %merge, %concavity, %maxVerts,
%maxBox, %maxSphere, %maxCapsule );
}
//------------------------------------------------------------------------------
//==============================================================================
// ShapeLab Action -> Update the collision mesh
//==============================================================================
//==============================================================================
// Build the action object
function ShapeLab::doEditCollision( %this, %type, %target, %depth, %merge, %concavity,
%maxVerts, %boxMax, %sphereMax, %capsuleMax ) {
%colData = ShapeLabCollisions.lastColSettings;
%action = %this.createAction( ActionEditCollision, "Edit shape collision" );
%action.oldType = getField( %colData, 0 );
%action.oldTarget = getField( %colData, 1 );
%action.oldDepth = getField( %colData, 2 );
%action.oldMerge = getField( %colData, 3 );
%action.oldConcavity = getField( %colData, 4 );
%action.oldMaxVerts = getField( %colData, 5 );
%action.oldBoxMax = getField( %colData, 6 );
%action.oldSphereMax = getField( %colData, 7 );
%action.oldCapsuleMax = getField( %colData, 8 );
%action.newType = %type;
%action.newTarget = %target;
%action.newDepth = %depth;
%action.newMerge = %merge;
%action.newConcavity = %concavity;
%action.newMaxVerts = %maxVerts;
%action.newBoxMax = %boxMax;
%action.newSphereMax = %sphereMax;
%action.newCapsuleMax = %capsuleMax;
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
//Update the collision mesh using TSShapeConstructor::addCollisionDetail
/*------------------------------------------------------------------------------
DefineTSShapeConstructorMethod( addCollisionDetail, bool, ( S32 size, const char* type, const char* target, S32 depth, F32 merge, F32 concavity, S32 maxVerts, F32 boxMaxError, F32 sphereMaxError, F32 capsuleMaxError ), ( 4, 30, 30, 32, 0, 0, 0 ),
( size, type, target, depth, merge, concavity, maxVerts, boxMaxError, sphereMaxError, capsuleMaxError ), false,
"Autofit a mesh primitive or set of convex hulls to the shape geometry. Hulls "
"may optionally be converted to boxes, spheres and/or capsules based on their "
"volume.\n"
"@param size size for this detail level\n"
"@param type one of: box, sphere, capsule, 10-dop x, 10-dop y, 10-dop z, 18-dop, "
"26-dop, convex hulls. See the Shape Lab documentation for more details "
"about these types.\n"
"@param target geometry to fit collision mesh(es) to; either \"bounds\" (for the "
"whole shape), or the name of an object in the shape\n"
"@param depth maximum split recursion depth (hulls only)\n"
"@param merge volume % threshold used to merge hulls together (hulls only)\n"
"@param concavity volume % threshold used to detect concavity (hulls only)\n"
"@param maxVerts maximum number of vertices per hull (hulls only)\n"
"@param boxMaxError max % volume difference for a hull to be converted to a "
"box (hulls only)\n"
"@param sphereMaxError max % volume difference for a hull to be converted to "
"a sphere (hulls only)\n"
"@param capsuleMaxError max % volume difference for a hull to be converted to "
"a capsule (hulls only)\n"
"@return true if successful, false otherwise\n\n"
"@tsexample\n"
"%this.addCollisionDetail( -1, \"box\", \"bounds\" );\n"
"%this.addCollisionDetail( -1, \"convex hulls\", \"bounds\", 4, 30, 30, 32, 0, 0, 0 );\n"
"%this.addCollisionDetail( -1, \"convex hulls\", \"bounds\", 4, 30, 30, 32, 50, 50, 50 );\n"
"@endtsexample\n" )
//----------------------------------------------------------------------------*/
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditCollision::updateCollision( %this, %type, %target, %depth, %merge, %concavity,
%maxVerts, %boxMax, %sphereMax, %capsuleMax ) {
%colDetailSize = -1;
%colNode = "Col" @ %colDetailSize;
// TreeView items are case sensitive, but TSShape names are not, so fixup case
// if needed
%index = ShapeLab.shape.getNodeIndex( %colNode );
if ( %index != -1 )
%colNode = ShapeLab.shape.getNodeName( %index );
// First remove the old detail and collision nodes
%meshList = ShapeLab.getDetailMeshList( %colDetailSize );
%meshCount = getFieldCount( %meshList );
if ( %meshCount > 0 ) {
ShapeLab.shape.removeDetailLevel( %colDetailSize );
for ( %i = 0; %i < %meshCount; %i++ )
ShapeLab.onMeshRemoved( getField( %meshList, %i ) );
}
%nodeList = ShapeLab.getNodeNames("Col-1", "" );
%nodeCount = getFieldCount( %nodeList );
if ( %nodeCount > 0 ) {
for ( %i = 0; %i < %nodeCount; %i++ )
ShapeLab.shape.removeNode( getField( %nodeList, %i ) );
ShapeLab.onNodeRemoved( %nodeList, %nodeCount );
}
devLog("Collision type to be created", %type);
// Add the new node and geometry
if ( %type $= "" )
return;
if ( !ShapeLab.shape.addCollisionDetail( %colDetailSize, %type, %target,
%depth, %merge, %concavity, %maxVerts,
%boxMax, %sphereMax, %capsuleMax ) )
return false;
devLog("Collision created", %type, %target,
%depth, %merge, %concavity, %maxVerts,
%boxMax, %sphereMax, %capsuleMax);
// Update UI
%meshList = ShapeLab.getDetailMeshList( %colDetailSize );
ShapeLab.onNodeAdded( %colNode, ShapeLab.shape.getNodeCount() ); // will also add child nodes
%count = getFieldCount( %meshList );
for ( %i = 0; %i < %count; %i++ )
ShapeLab.onMeshAdded( getField( %meshList, %i ) );
ShapeLabCollisions.lastColSettings = %type TAB %target TAB %depth TAB %merge TAB
%concavity TAB %maxVerts TAB %boxMax TAB %sphereMax TAB %capsuleMax;
ShapeLabCollisions.onCollisionChanged();
return true;
}
//------------------------------------------------------------------------------
//==============================================================================
// Do the Edit Collision Action
function ActionEditCollision::doit( %this ) {
//ShapeLabWaitGui.show( "Generating collision geometry..." );
%success = %this.updateCollision( %this.newType, %this.newTarget, %this.newDepth, %this.newMerge,
%this.newConcavity, %this.newMaxVerts, %this.newBoxMax,
%this.newSphereMax, %this.newCapsuleMax );
//ShapeLabWaitGui.hide();
return %success;
}
//------------------------------------------------------------------------------
//==============================================================================
// UnDo the Edit Collision Action
function ActionEditCollision::undo( %this ) {
Parent::undo( %this );
//ShapeLabWaitGui.show( "Generating collision geometry..." );
%this.updateCollision( %this.oldType, %this.oldTarget, %this.oldDepth, %this.oldMerge,
%this.oldConcavity, %this.oldMaxVerts, %this.oldBoxMax,
%this.oldSphereMax, %this.oldCapsuleMax );
//ShapeLabWaitGui.hide();
}
//------------------------------------------------------------------------------
| |
// 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
//
// 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;
#if UNITY_5_3_OR_NEWER
// Use UnityEngine.CoreModule.AOT
#else
namespace AOT
{
/// <summary>
/// Implementation of Mono.Util.MonoPInvokeCallbackAttribute
/// mono/src/mcs/class/System/Mono.Util/MonoPInvokeCallbackAttribute.cs
/// In the AOT namespace for compatibility with Unity.
/// This should be applied to methods that are called from unmanaged code so that the ahead of
/// time compiler doesn't strip them.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class MonoPInvokeCallbackAttribute : Attribute
{
/// <summary>
/// Construct the callback attribute.
/// </summary>
public MonoPInvokeCallbackAttribute(Type type) {}
}
}
#endif // UNITY_5_3_OR_NEWER
namespace Falken
{
/// <summary>
/// Log level of messages.
/// </summary>
/// <remarks>
/// Verbosity of log messages from Debug (most verbose, least important), to Fatal
/// (least verbose, most important).
/// </remarks>
public enum LogLevel
{
/// <summary>
/// Debug message.
/// </summary>
Debug,
/// <summary>
/// Verbose message.
/// </summary>
Verbose,
/// <summary>
/// Informational message.
/// </summary>
Info,
/// <summary>
/// Warning message.
/// </summary>
Warning,
/// <summary>
/// Error message.
/// </summary>
Error,
/// <summary>
/// Fatal message.
/// </summary>
Fatal
}
/// <summary>
/// Configures Falken logging.
/// </summary>
public class Log
{
/// <summary>
/// Registers for log message callbacks from C/C++ on creation, and unregisters itself when
/// disposed.
/// </summary>
internal class Logger : FalkenInternal.falken.SystemLogger
{
// Log callback handle.
private uint callbackHandle = 0;
// Delegate that wraps LogMessage().
private FalkenInternal.falken.LoggerNotifier.LogMessageDelegate logMessageDelegate;
// Logger singleton.
private static Logger defaultInstance = null;
/// <summary>
/// Register LogMessage as a log callback for the C/C++ layer.
/// </summary>
public Logger() : base()
{
// Throw C# exceptions instead of aborting the application when a fatal
// error occurs.
set_abort_on_fatal_error(false);
// Call LogMessage when a message is logged.
logMessageDelegate = LogMessage;
callbackHandle = GetLoggerNotifier().AddLogCallback(logMessageDelegate,
IntPtr.Zero);
AppDomain.CurrentDomain.DomainUnload += (object sender, EventArgs e) => {
Dispose(false);
};
}
/// <summary>
/// Finalize the logger.
/// </summary>
~Logger()
{
Dispose(false);
}
/// <summary>
/// Unregister the logger from the C/C++ layer.
/// </summary>
protected override void Dispose(bool disposing)
{
if (callbackHandle > 0)
{
GetLoggerNotifier().RemoveLogCallback(callbackHandle);
set_abort_on_fatal_error(true);
callbackHandle = 0;
}
base.Dispose(disposing);
}
/// <summary>
/// Log a message from C/C++.
/// </summary>
/// <param name="logLevel">Log level of the message.</param>
/// <param name="message">Message to log.</param>
/// <param name="context">Context of the logger (unused).</param>
[AOT.MonoPInvokeCallback(
typeof(FalkenInternal.falken.LoggerNotifier.LogMessageDelegate))]
private static void LogMessage(
FalkenInternal.falken.LogLevel logLevel, string message,
System.IntPtr context)
{
// Explicitly keep a reference to logger to prevent GC.
var logger = DefaultInstance;
var loggerBase = logger.GetLoggerBase();
if (loggerBase != null && logLevel >= loggerBase.log_level())
{
#if UNITY_5_3_OR_NEWER
switch (logLevel)
{
case FalkenInternal.falken.LogLevel.kLogLevelDebug:
case FalkenInternal.falken.LogLevel.kLogLevelVerbose:
case FalkenInternal.falken.LogLevel.kLogLevelInfo:
UnityEngine.Debug.Log(message);
break;
case FalkenInternal.falken.LogLevel.kLogLevelWarning:
UnityEngine.Debug.LogWarning(message);
break;
case FalkenInternal.falken.LogLevel.kLogLevelError:
case FalkenInternal.falken.LogLevel.kLogLevelFatal:
UnityEngine.Debug.LogError(message);
break;
}
#else
System.Console.WriteLine(message);
#endif // UNITY_5_3_OR_NEWER
}
Exception logMessageException = null;
try
{
Falken.Log.NotifyLoggedMessage(logLevel, message);
}
catch (Exception exception)
{
// Exceptions can't be thrown in this context as this callback is called
// from unmanaged code so instead set the exception as pending on this thread
// if a fatal error didn't occur.
logMessageException = exception;
}
if (!FalkenInternal.falken_modulePINVOKE.SWIGPendingException.Pending)
{
if (logLevel == FalkenInternal.falken.LogLevel.kLogLevelFatal)
{
FalkenInternal.falken_modulePINVOKE.SWIGPendingException.Set(
new ApplicationException(message));
}
else if (logMessageException != null)
{
FalkenInternal.falken_modulePINVOKE.SWIGPendingException.Set(
logMessageException);
}
}
}
/// <summary>
/// Get the logger.
/// </summary>
internal static Logger DefaultInstance
{
get
{
lock (typeof(Logger))
{
if (defaultInstance == null)
{
// The P/Invoke module creates a logger on construction so firstly
// force construction of the module by creating a SystemLogger proxy.
using (var systemLogger = new FalkenInternal.falken.SystemLogger())
{
// If the P/Invoke module constructor is called, defaultInstance
// will be set.
if (defaultInstance == null)
{
defaultInstance = new Logger();
}
}
}
return defaultInstance;
}
}
}
}
/// <summary>
/// Initialize the log class.
/// </summary>
static Log()
{
// Create the logger.
var logger = Logger.DefaultInstance;
}
/// <summary>
/// Arguments passed to a log event.
/// </summary>
public class MessageArgs : System.EventArgs
{
/// <summary>
/// Log level of the message.
/// </summary>
public LogLevel LogLevel
{
get; set;
}
/// <summary>
/// Log message.
/// </summary>
public string Message
{
get; set;
}
}
/// <summary>
/// Event that is notified when messages are logged.
/// </summary>
public static event System.EventHandler<MessageArgs> OnMessage;
/// <summary>
/// Set / get the log level.
/// </summary>
/// <remarks>
/// All log message below or at the specified log level will be logged.
/// </remarks>
public static LogLevel Level
{
set
{
// Explicitly keep a reference to logger to prevent GC.
var logger = Logger.DefaultInstance;
var loggerBase = logger?.GetLoggerBase();
if (loggerBase != null)
{
loggerBase.set_log_level(ToInternalLogLevel(value));
}
}
get
{
// Explicitly keep a reference to logger to prevent GC.
var logger = Logger.DefaultInstance;
var loggerBase = logger?.GetLoggerBase();
return loggerBase != null ? FromInternalLogLevel(loggerBase.log_level()) :
LogLevel.Info;
}
}
/// <summary>
/// Set / get the log filename.
/// </summary>
public static string Filename
{
set
{
var logger = Logger.DefaultInstance;
if (logger != null)
{
logger.file_logger().set_filename(value);
}
}
get
{
var logger = Logger.DefaultInstance;
return logger != null ? logger.file_logger().filename() : null;
}
}
/// <summary>
/// Notify event listeners of a logged message.
/// </summary>
/// <param name="logLevel">Internal log level.</param>
/// <param name="message">Message to log.</param>
private static void NotifyLoggedMessage(FalkenInternal.falken.LogLevel logLevel,
string message)
{
var handler = OnMessage;
if (handler != null)
{
handler(null,
new MessageArgs()
{
LogLevel = FromInternalLogLevel(logLevel),
Message = message
});
}
}
/// <summary>
/// Convert from an internal LogLevel to public LogLevel enum.
/// </summary>
/// <param name="logLevel">Internal log level to convert.</param>
/// <returns>Public log level.</returns>
internal static LogLevel FromInternalLogLevel(FalkenInternal.falken.LogLevel logLevel)
{
switch (logLevel)
{
case FalkenInternal.falken.LogLevel.kLogLevelDebug:
return LogLevel.Debug;
case FalkenInternal.falken.LogLevel.kLogLevelVerbose:
return LogLevel.Verbose;
case FalkenInternal.falken.LogLevel.kLogLevelInfo:
return LogLevel.Info;
case FalkenInternal.falken.LogLevel.kLogLevelWarning:
return LogLevel.Warning;
case FalkenInternal.falken.LogLevel.kLogLevelError:
return LogLevel.Error;
case FalkenInternal.falken.LogLevel.kLogLevelFatal:
return LogLevel.Fatal;
}
return LogLevel.Debug;
}
/// <summary>
/// Convert from a public to internal LogLevel.
/// </summary>
/// <param name="logLevel">Public log level to convert.</param>
/// <returns>Internal log level.</returns>
internal static FalkenInternal.falken.LogLevel ToInternalLogLevel(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Debug:
return FalkenInternal.falken.LogLevel.kLogLevelDebug;
case LogLevel.Verbose:
return FalkenInternal.falken.LogLevel.kLogLevelVerbose;
case LogLevel.Info:
return FalkenInternal.falken.LogLevel.kLogLevelInfo;
case LogLevel.Warning:
return FalkenInternal.falken.LogLevel.kLogLevelWarning;
case LogLevel.Error:
return FalkenInternal.falken.LogLevel.kLogLevelError;
case LogLevel.Fatal:
return FalkenInternal.falken.LogLevel.kLogLevelFatal;
}
return FalkenInternal.falken.LogLevel.kLogLevelDebug;
}
/// <summary>
/// Log a message.
/// </summary>
/// <param name="logLevel">Log level of the message.</param>
/// <param name="message">Message to log.</param>
internal static void LogMessage(LogLevel logLevel, string message)
{
// Explicitly keep a reference to logger to prevent GC.
var logger = Logger.DefaultInstance;
var loggerBase = logger?.GetLoggerBase();
if (loggerBase != null)
{
loggerBase.Log(ToInternalLogLevel(logLevel), message);
}
// If an exception was set on this thread, raise it.
if (FalkenInternal.falken_modulePINVOKE.SWIGPendingException.Pending)
{
throw FalkenInternal.falken_modulePINVOKE.SWIGPendingException.Retrieve();
}
}
/// <summary>
/// Log a debug message.
/// </summary>
/// <param name="message">Message to log.</param>
internal static void Debug(string message)
{
LogMessage(LogLevel.Debug, message);
}
/// <summary>
/// Log a verbose message.
/// </summary>
/// <param name="message">Message to log.</param>
internal static void Verbose(string message)
{
LogMessage(LogLevel.Verbose, message);
}
/// <summary>
/// Log an info message.
/// </summary>
/// <param name="message">Message to log.</param>
internal static void Info(string message)
{
LogMessage(LogLevel.Info, message);
}
/// <summary>
/// Log a warning message.
/// </summary>
/// <param name="message">Message to log.</param>
internal static void Warning(string message)
{
LogMessage(LogLevel.Warning, message);
}
/// <summary>
/// Log an error message.
/// </summary>
/// <param name="message">Message to log.</param>
internal static void Error(string message)
{
LogMessage(LogLevel.Error, message);
}
/// <summary>
/// Log a fatal message.
/// </summary>
/// <param name="message">Message to log.</param>
internal static void Fatal(string message)
{
LogMessage(LogLevel.Fatal, message);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** CustomAttributeBuilder is a helper class to help building custom attribute.
**
**
===========================================================*/
namespace System.Reflection.Emit {
using System;
using System.Reflection;
using System.IO;
using System.Text;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics.Contracts;
[HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_CustomAttributeBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public class CustomAttributeBuilder : _CustomAttributeBuilder
{
// public constructor to form the custom attribute with constructor and constructor
// parameters.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs)
{
InitCustomAttributeBuilder(con, constructorArgs,
new PropertyInfo[]{}, new Object[]{},
new FieldInfo[]{}, new Object[]{});
}
// public constructor to form the custom attribute with constructor, constructor
// parameters and named properties.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
PropertyInfo[] namedProperties, Object[] propertyValues)
{
InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
propertyValues, new FieldInfo[]{}, new Object[]{});
}
// public constructor to form the custom attribute with constructor and constructor
// parameters.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
FieldInfo[] namedFields, Object[] fieldValues)
{
InitCustomAttributeBuilder(con, constructorArgs, new PropertyInfo[]{},
new Object[]{}, namedFields, fieldValues);
}
// public constructor to form the custom attribute with constructor and constructor
// parameters.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
PropertyInfo[] namedProperties, Object[] propertyValues,
FieldInfo[] namedFields, Object[] fieldValues)
{
InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
propertyValues, namedFields, fieldValues);
}
// Check that a type is suitable for use in a custom attribute.
private bool ValidateType(Type t)
{
if (t.IsPrimitive || t == typeof(String) || t == typeof(Type))
return true;
if (t.IsEnum)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(t)))
{
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
if (t.IsArray)
{
if (t.GetArrayRank() != 1)
return false;
return ValidateType(t.GetElementType());
}
return t == typeof(Object);
}
internal void InitCustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
PropertyInfo[] namedProperties, Object[] propertyValues,
FieldInfo[] namedFields, Object[] fieldValues)
{
if (con == null)
throw new ArgumentNullException("con");
if (constructorArgs == null)
throw new ArgumentNullException("constructorArgs");
if (namedProperties == null)
throw new ArgumentNullException("namedProperties");
if (propertyValues == null)
throw new ArgumentNullException("propertyValues");
if (namedFields == null)
throw new ArgumentNullException("namedFields");
if (fieldValues == null)
throw new ArgumentNullException("fieldValues");
if (namedProperties.Length != propertyValues.Length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedProperties, propertyValues");
if (namedFields.Length != fieldValues.Length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedFields, fieldValues");
Contract.EndContractBlock();
if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
(con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructor"));
if ((con.CallingConvention & CallingConventions.Standard) != CallingConventions.Standard)
throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructorCallConv"));
// Cache information used elsewhere.
m_con = con;
m_constructorArgs = new Object[constructorArgs.Length];
Array.Copy(constructorArgs, m_constructorArgs, constructorArgs.Length);
Type[] paramTypes;
int i;
// Get the types of the constructor's formal parameters.
paramTypes = con.GetParameterTypes();
// Since we're guaranteed a non-var calling convention, the number of arguments must equal the number of parameters.
if (paramTypes.Length != constructorArgs.Length)
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterCountsForConstructor"));
// Verify that the constructor has a valid signature (custom attributes only support a subset of our type system).
for (i = 0; i < paramTypes.Length; i++)
if (!ValidateType(paramTypes[i]))
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Now verify that the types of the actual parameters are compatible with the types of the formal parameters.
for (i = 0; i < paramTypes.Length; i++)
{
if (constructorArgs[i] == null)
continue;
TypeCode paramTC = Type.GetTypeCode(paramTypes[i]);
if (paramTC != Type.GetTypeCode(constructorArgs[i].GetType()))
if (paramTC != TypeCode.Object || !ValidateType(constructorArgs[i].GetType()))
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForConstructor", i));
}
// Allocate a memory stream to represent the CA blob in the metadata and a binary writer to help format it.
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
// Write the blob protocol version (currently 1).
writer.Write((ushort)1);
// Now emit the constructor argument values (no need for types, they're inferred from the constructor signature).
for (i = 0; i < constructorArgs.Length; i++)
EmitValue(writer, paramTypes[i], constructorArgs[i]);
// Next a short with the count of properties and fields.
writer.Write((ushort)(namedProperties.Length + namedFields.Length));
// Emit all the property sets.
for (i = 0; i < namedProperties.Length; i++)
{
// Validate the property.
if (namedProperties[i] == null)
throw new ArgumentNullException("namedProperties[" + i + "]");
// Allow null for non-primitive types only.
Type propType = namedProperties[i].PropertyType;
if (propertyValues[i] == null && propType.IsPrimitive)
throw new ArgumentNullException("propertyValues[" + i + "]");
// Validate property type.
if (!ValidateType(propType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Property has to be writable.
if (!namedProperties[i].CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_NotAWritableProperty"));
// Property has to be from the same class or base class as ConstructorInfo.
if (namedProperties[i].DeclaringType != con.DeclaringType
&& (!(con.DeclaringType is TypeBuilderInstantiation))
&& !con.DeclaringType.IsSubclassOf(namedProperties[i].DeclaringType))
{
// Might have failed check because one type is a XXXBuilder
// and the other is not. Deal with these special cases
// separately.
if (!TypeBuilder.IsTypeEqual(namedProperties[i].DeclaringType, con.DeclaringType))
{
// IsSubclassOf is overloaded to do the right thing if
// the constructor is a TypeBuilder, but we still need
// to deal with the case where the property's declaring
// type is one.
if (!(namedProperties[i].DeclaringType is TypeBuilder) ||
!con.DeclaringType.IsSubclassOf(((TypeBuilder)namedProperties[i].DeclaringType).BakedRuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadPropertyForConstructorBuilder"));
}
}
// Make sure the property's type can take the given value.
// Note that there will be no coersion.
if (propertyValues[i] != null &&
propType != typeof(Object) &&
Type.GetTypeCode(propertyValues[i].GetType()) != Type.GetTypeCode(propType))
throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
// First a byte indicating that this is a property.
writer.Write((byte)CustomAttributeEncoding.Property);
// Emit the property type, name and value.
EmitType(writer, propType);
EmitString(writer, namedProperties[i].Name);
EmitValue(writer, propType, propertyValues[i]);
}
// Emit all the field sets.
for (i = 0; i < namedFields.Length; i++)
{
// Validate the field.
if (namedFields[i] == null)
throw new ArgumentNullException("namedFields[" + i + "]");
// Allow null for non-primitive types only.
Type fldType = namedFields[i].FieldType;
if (fieldValues[i] == null && fldType.IsPrimitive)
throw new ArgumentNullException("fieldValues[" + i + "]");
// Validate field type.
if (!ValidateType(fldType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Field has to be from the same class or base class as ConstructorInfo.
if (namedFields[i].DeclaringType != con.DeclaringType
&& (!(con.DeclaringType is TypeBuilderInstantiation))
&& !con.DeclaringType.IsSubclassOf(namedFields[i].DeclaringType))
{
// Might have failed check because one type is a XXXBuilder
// and the other is not. Deal with these special cases
// separately.
if (!TypeBuilder.IsTypeEqual(namedFields[i].DeclaringType, con.DeclaringType))
{
// IsSubclassOf is overloaded to do the right thing if
// the constructor is a TypeBuilder, but we still need
// to deal with the case where the field's declaring
// type is one.
if (!(namedFields[i].DeclaringType is TypeBuilder) ||
!con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldForConstructorBuilder"));
}
}
// Make sure the field's type can take the given value.
// Note that there will be no coersion.
if (fieldValues[i] != null &&
fldType != typeof(Object) &&
Type.GetTypeCode(fieldValues[i].GetType()) != Type.GetTypeCode(fldType))
throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
// First a byte indicating that this is a field.
writer.Write((byte)CustomAttributeEncoding.Field);
// Emit the field type, name and value.
EmitType(writer, fldType);
EmitString(writer, namedFields[i].Name);
EmitValue(writer, fldType, fieldValues[i]);
}
// Create the blob array.
m_blob = ((MemoryStream)writer.BaseStream).ToArray();
}
private void EmitType(BinaryWriter writer, Type type)
{
if (type.IsPrimitive)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.SByte:
writer.Write((byte)CustomAttributeEncoding.SByte);
break;
case TypeCode.Byte:
writer.Write((byte)CustomAttributeEncoding.Byte);
break;
case TypeCode.Char:
writer.Write((byte)CustomAttributeEncoding.Char);
break;
case TypeCode.Boolean:
writer.Write((byte)CustomAttributeEncoding.Boolean);
break;
case TypeCode.Int16:
writer.Write((byte)CustomAttributeEncoding.Int16);
break;
case TypeCode.UInt16:
writer.Write((byte)CustomAttributeEncoding.UInt16);
break;
case TypeCode.Int32:
writer.Write((byte)CustomAttributeEncoding.Int32);
break;
case TypeCode.UInt32:
writer.Write((byte)CustomAttributeEncoding.UInt32);
break;
case TypeCode.Int64:
writer.Write((byte)CustomAttributeEncoding.Int64);
break;
case TypeCode.UInt64:
writer.Write((byte)CustomAttributeEncoding.UInt64);
break;
case TypeCode.Single:
writer.Write((byte)CustomAttributeEncoding.Float);
break;
case TypeCode.Double:
writer.Write((byte)CustomAttributeEncoding.Double);
break;
default:
Contract.Assert(false, "Invalid primitive type");
break;
}
}
else if (type.IsEnum)
{
writer.Write((byte)CustomAttributeEncoding.Enum);
EmitString(writer, type.AssemblyQualifiedName);
}
else if (type == typeof(String))
{
writer.Write((byte)CustomAttributeEncoding.String);
}
else if (type == typeof(Type))
{
writer.Write((byte)CustomAttributeEncoding.Type);
}
else if (type.IsArray)
{
writer.Write((byte)CustomAttributeEncoding.Array);
EmitType(writer, type.GetElementType());
}
else
{
// Tagged object case.
writer.Write((byte)CustomAttributeEncoding.Object);
}
}
private void EmitString(BinaryWriter writer, String str)
{
// Strings are emitted with a length prefix in a compressed format (1, 2 or 4 bytes) as used internally by metadata.
byte[] utf8Str = Encoding.UTF8.GetBytes(str);
uint length = (uint)utf8Str.Length;
if (length <= 0x7f)
{
writer.Write((byte)length);
}
else if (length <= 0x3fff)
{
writer.Write((byte)((length >> 8) | 0x80));
writer.Write((byte)(length & 0xff));
}
else
{
writer.Write((byte)((length >> 24) | 0xc0));
writer.Write((byte)((length >> 16) & 0xff));
writer.Write((byte)((length >> 8) & 0xff));
writer.Write((byte)(length & 0xff));
}
writer.Write(utf8Str);
}
private void EmitValue(BinaryWriter writer, Type type, Object value)
{
if (type.IsEnum)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(type)))
{
case TypeCode.SByte:
writer.Write((sbyte)value);
break;
case TypeCode.Byte:
writer.Write((byte)value);
break;
case TypeCode.Int16:
writer.Write((short)value);
break;
case TypeCode.UInt16:
writer.Write((ushort)value);
break;
case TypeCode.Int32:
writer.Write((int)value);
break;
case TypeCode.UInt32:
writer.Write((uint)value);
break;
case TypeCode.Int64:
writer.Write((long)value);
break;
case TypeCode.UInt64:
writer.Write((ulong)value);
break;
default:
Contract.Assert(false, "Invalid enum base type");
break;
}
}
else if (type == typeof(String))
{
if (value == null)
writer.Write((byte)0xff);
else
EmitString(writer, (String)value);
}
else if (type == typeof(Type))
{
if (value == null)
writer.Write((byte)0xff);
else
{
String typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName);
if (typeName == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForCA",
value.GetType()));
EmitString(writer, typeName);
}
}
else if (type.IsArray)
{
if (value == null)
writer.Write((uint)0xffffffff);
else
{
Array a = (Array)value;
Type et = type.GetElementType();
writer.Write(a.Length);
for (int i = 0; i < a.Length; i++)
EmitValue(writer, et, a.GetValue(i));
}
}
else if (type.IsPrimitive)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.SByte:
writer.Write((sbyte)value);
break;
case TypeCode.Byte:
writer.Write((byte)value);
break;
case TypeCode.Char:
writer.Write(Convert.ToUInt16((char)value));
break;
case TypeCode.Boolean:
writer.Write((byte)((bool)value ? 1 : 0));
break;
case TypeCode.Int16:
writer.Write((short)value);
break;
case TypeCode.UInt16:
writer.Write((ushort)value);
break;
case TypeCode.Int32:
writer.Write((int)value);
break;
case TypeCode.UInt32:
writer.Write((uint)value);
break;
case TypeCode.Int64:
writer.Write((long)value);
break;
case TypeCode.UInt64:
writer.Write((ulong)value);
break;
case TypeCode.Single:
writer.Write((float)value);
break;
case TypeCode.Double:
writer.Write((double)value);
break;
default:
Contract.Assert(false, "Invalid primitive type");
break;
}
}
else if (type == typeof(object))
{
// Tagged object case. Type instances aren't actually Type, they're some subclass (such as RuntimeType or
// TypeBuilder), so we need to canonicalize this case back to Type. If we have a null value we follow the convention
// used by C# and emit a null typed as a string (it doesn't really matter what type we pick as long as it's a
// reference type).
Type ot = value == null ? typeof(String) : value is Type ? typeof(Type) : value.GetType();
// value cannot be a "System.Object" object.
// If we allow this we will get into an infinite recursion
if (ot == typeof(object))
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", ot.ToString()));
EmitType(writer, ot);
EmitValue(writer, ot, value);
}
else
{
string typename = "null";
if (value != null)
typename = value.GetType().ToString();
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", typename));
}
}
// return the byte interpretation of the custom attribute
[System.Security.SecurityCritical] // auto-generated
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner)
{
CreateCustomAttribute(mod, tkOwner, mod.GetConstructorToken(m_con).Token, false);
}
//*************************************************
// Upon saving to disk, we need to create the memberRef token for the custom attribute's type
// first of all. So when we snap the in-memory module for on disk, this token will be there.
// We also need to enforce the use of MemberRef. Because MemberDef token might move.
// This function has to be called before we snap the in-memory module for on disk (i.e. Presave on
// ModuleBuilder.
//*************************************************
[System.Security.SecurityCritical] // auto-generated
internal int PrepareCreateCustomAttributeToDisk(ModuleBuilder mod)
{
return mod.InternalGetConstructorToken(m_con, true).Token;
}
//*************************************************
// Call this function with toDisk=1, after on disk module has been snapped.
//*************************************************
[System.Security.SecurityCritical] // auto-generated
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk)
{
TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk,
typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType);
}
#if !FEATURE_CORECLR
void _CustomAttributeBuilder.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _CustomAttributeBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _CustomAttributeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _CustomAttributeBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
internal ConstructorInfo m_con;
internal Object[] m_constructorArgs;
internal byte[] m_blob;
}
}
| |
// 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.ComponentModel;
using Xunit;
namespace System.Collections.ObjectModel.Tests
{
/// <summary>
/// Tests that the INotifyCollectionChanged and IPropertyChanged events are fired
/// when an item is changed in the underlying ObservableCollection<T>.
/// </summary>
public class ReadOnlyObservableCollection_EventsTests
{
/// <summary>
/// Tests for an Add action.
/// </summary>
[Fact]
public static void AddTest()
{
string[] anArray = { "one", "two", "three" };
ObservableCollection<string> col = new ObservableCollection<string>(anArray);
ReadOnlyObservableCollection<string> readonlyCol = new ReadOnlyObservableCollection<string>(col);
ReadOnlyCollectionAndPropertyChangedTester helper = new ReadOnlyCollectionAndPropertyChangedTester();
helper.AddOrInsertItemTest(readonlyCol, col, "four");
}
/// <summary>
/// Tests that it is possible to remove an item from the collection and the events
/// are forwarded.
/// - Removing an item from the collection results in a false.
/// - Removing null from collection returns a false.
/// - Removing an item that has duplicates only takes out the first instance.
/// </summary>
[Fact]
public static void RemoveTest()
{
// trying to remove item in collection.
string[] anArray = { "one", "two", "three", "four" };
ObservableCollection<string> col = new ObservableCollection<string>(anArray);
ReadOnlyObservableCollection<string> readonlyCol = new ReadOnlyObservableCollection<string>(col);
ReadOnlyCollectionAndPropertyChangedTester helper = new ReadOnlyCollectionAndPropertyChangedTester();
helper.RemoveItemTest(readonlyCol, col, 2, "three", true, hasDuplicates: false);
// trying to remove item not in collection.
anArray = new string[] { "one", "two", "three", "four" };
col = new ObservableCollection<string>(anArray);
readonlyCol = new ReadOnlyObservableCollection<string>(col);
helper = new ReadOnlyCollectionAndPropertyChangedTester();
helper.RemoveItemTest(readonlyCol, col, -1, "three2", false, hasDuplicates: false);
// removing null
anArray = new string[] { "one", "two", "three", "four" };
col = new ObservableCollection<string>(anArray);
readonlyCol = new ReadOnlyObservableCollection<string>(col);
helper = new ReadOnlyCollectionAndPropertyChangedTester();
helper.RemoveItemTest(readonlyCol, col, -1, null, false, hasDuplicates: false);
// trying to remove item in collection that has duplicates.
anArray = new string[] { "one", "three", "two", "three", "four" };
col = new ObservableCollection<string>(anArray);
readonlyCol = new ReadOnlyObservableCollection<string>(col);
helper = new ReadOnlyCollectionAndPropertyChangedTester();
helper.RemoveItemTest(readonlyCol, col, 1, "three", true, hasDuplicates: true);
// want to ensure that there is one "three" left in collection and not both were removed.
int occurrencesThree = 0;
foreach (var item in col)
{
if (item.Equals("three"))
occurrencesThree++;
}
Assert.Equal(1, occurrencesThree);
}
/// <summary>
/// Tests that a collection can be cleared and its events are forwarded.
/// </summary>
[Fact]
public static void ClearTest()
{
string[] anArray = { "one", "two", "three", "four" };
//tests that the collectionChanged events are fired.
ReadOnlyCollectionAndPropertyChangedTester helper = new ReadOnlyCollectionAndPropertyChangedTester();
ObservableCollection<string> col = new ObservableCollection<string>(anArray);
ReadOnlyObservableCollection<string> readonlyCol = new ReadOnlyObservableCollection<string>(col);
helper.ClearTest(readonlyCol, col);
}
/// <summary>
/// Tests that we can remove items at a specific index, at the middle beginning and end.
/// And its events are forwarded.
/// </summary>
[Fact]
public static void RemoveAtTest()
{
string[] anArrayString = { "one", "two", "three", "four" };
ObservableCollection<string> col = new ObservableCollection<string>(anArrayString);
ReadOnlyObservableCollection<string> readonlyCol = new ReadOnlyObservableCollection<string>(col);
ReadOnlyCollectionAndPropertyChangedTester helper = new ReadOnlyCollectionAndPropertyChangedTester();
helper.RemoveItemAtTest(readonlyCol, col, 1);
}
/// <summary>
/// Tests that exceptions are thrown:
/// ArgumentOutOfRangeException when index < 0 or index >= collection.Count.
/// And that the collection does not change.
/// And no events are forwarded to the collection.
/// </summary>
[Fact]
public static void RemoveAtTest_Negative()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> collection = new ObservableCollection<Guid>(anArray);
ReadOnlyObservableCollection<Guid> readonlyCol = new ReadOnlyObservableCollection<Guid>(collection);
((INotifyCollectionChanged)readonlyCol).CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); };
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
foreach (var index in iArrInvalidValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(index));
Assert.Equal(anArray.Length, readonlyCol.Count);
}
int[] iArrLargeValues = new Int32[] { collection.Count, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrLargeValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(index));
Assert.Equal(anArray.Length, readonlyCol.Count);
}
}
/// <summary>
/// Tests that items can be moved throughout a collection whether from
/// beginning to end, etc. And the events are forwarded.
/// </summary>
[Fact]
public static void MoveTest()
{
ReadOnlyCollectionAndPropertyChangedTester helper = new ReadOnlyCollectionAndPropertyChangedTester();
string[] anArrayString = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>(anArrayString);
ReadOnlyObservableCollection<string> readonlyCol = new ReadOnlyObservableCollection<string>(collection);
helper.MoveItemTest(readonlyCol, collection, 0, 2);
helper.MoveItemTest(readonlyCol, collection, 3, 0);
helper.MoveItemTest(readonlyCol, collection, 1, 2);
}
/// <summary>
/// Tests that:
/// ArgumentOutOfRangeException is thrown when the source or destination
/// Index is >= collection.Count or Index < 0.
/// And the events are not forwarded.
/// </summary>
/// <remarks>
/// When the sourceIndex is valid, the item actually is removed from the list.
/// </remarks>
[Fact]
public static void MoveTest_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>(anArray);
ReadOnlyObservableCollection<string> readonlyCol = new ReadOnlyObservableCollection<string>(collection);
((INotifyCollectionChanged)readonlyCol).CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); };
int validIndex = 2;
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
int[] iArrLargeValues = new Int32[] { anArray.Length, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrInvalidValues)
{
// invalid startIndex, valid destination index.
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Move(index, validIndex));
Assert.Equal(anArray.Length, collection.Count);
}
foreach (var index in iArrLargeValues)
{
// invalid startIndex, valid destination index.
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Move(index, validIndex));
Assert.Equal(anArray.Length, collection.Count);
}
}
/// <summary>
/// Tests that an item can be inserted throughout the collection.
/// And the events are forwarded.
/// </summary>
[Fact]
public static void InsertTest()
{
string[] anArrayString = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>(anArrayString);
ReadOnlyObservableCollection<string> readonlyCol = new ReadOnlyObservableCollection<string>(collection);
ReadOnlyCollectionAndPropertyChangedTester helper = new ReadOnlyCollectionAndPropertyChangedTester();
helper.AddOrInsertItemTest(readonlyCol, collection, "seven", 2);
helper.AddOrInsertItemTest(readonlyCol, collection, "zero", 0);
helper.AddOrInsertItemTest(readonlyCol, collection, "eight", collection.Count);
}
/// <summary>
/// Tests that:
/// ArgumentOutOfRangeException is thrown when the Index is >= collection.Count
/// or Index < 0. And ensures that the collection does not change.
/// And the events are not forwarded.
/// </summary>
[Fact]
public static void InsertTest_Negative()
{
Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
ObservableCollection<Guid> collection = new ObservableCollection<Guid>(anArray);
ReadOnlyObservableCollection<Guid> readonlyCol = new ReadOnlyObservableCollection<Guid>(collection);
((INotifyCollectionChanged)readonlyCol).CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); };
Guid itemToInsert = Guid.NewGuid();
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
foreach (var index in iArrInvalidValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(index, itemToInsert));
Assert.Equal(anArray.Length, collection.Count);
}
int[] iArrLargeValues = new Int32[] { collection.Count + 1, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrLargeValues)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(index, itemToInsert));
Assert.Equal(anArray.Length, collection.Count);
}
}
/// <summary>
/// Tests that the appropriate collectionchanged and propertychanged events are
/// fired when an item is replaced in the collection.
/// </summary>
[Fact]
public static void ReplaceItemTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ObservableCollection<string> collection = new ObservableCollection<string>(anArray);
ReadOnlyObservableCollection<string> readonlyCol = new ReadOnlyObservableCollection<string>(collection);
ReadOnlyCollectionAndPropertyChangedTester helper = new ReadOnlyCollectionAndPropertyChangedTester();
helper.ReplaceItemTest(readonlyCol, collection, 1, "seven");
helper.ReplaceItemTest(readonlyCol, collection, 3, "zero");
}
}
/// <summary>
/// Helper class to test the CollectionChanged and PropertyChanged Events.
/// </summary>
public class ReadOnlyCollectionAndPropertyChangedTester
{
#region Properties
private const string COUNT = "Count";
private const string ITEMARRAY = "Item[]";
// Number of collection changed events that were ACTUALLY fired.
private int _numCollectionChangedFired;
// Number of collection changed events that are EXPECTED to be fired.
private int _expectedCollectionChangedFired;
private int _expectedNewStartingIndex;
private NotifyCollectionChangedAction _expectedAction;
private IList _expectedNewItems;
private IList _expectedOldItems;
private int _expectedOldStartingIndex;
private PropertyNameExpected[] _expectedPropertyChanged;
#endregion
/// <summary>
/// Will perform an Add or Insert on the given Collection depending on whether the
/// insertIndex is null or not. If it is null, will Add, otherwise, will Insert.
/// </summary>
public void AddOrInsertItemTest(ReadOnlyObservableCollection<string> readOnlyCol, ObservableCollection<string> collection,
string itemToAdd, int? insertIndex = null)
{
INotifyPropertyChanged readOnlyPropertyChanged = readOnlyCol;
readOnlyPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
INotifyCollectionChanged readOnlyCollectionChanged = readOnlyCol;
readOnlyCollectionChanged.CollectionChanged += Collection_CollectionChanged;
_expectedCollectionChangedFired++;
_expectedAction = NotifyCollectionChangedAction.Add;
_expectedNewItems = new string[] { itemToAdd };
if (insertIndex.HasValue)
_expectedNewStartingIndex = insertIndex.Value;
else
_expectedNewStartingIndex = collection.Count;
_expectedOldItems = null;
_expectedOldStartingIndex = -1;
int expectedCount = collection.Count + 1;
if (insertIndex.HasValue)
{
collection.Insert(insertIndex.Value, itemToAdd);
Assert.Equal(itemToAdd, readOnlyCol[insertIndex.Value]);
}
else
{
collection.Add(itemToAdd);
Assert.Equal(itemToAdd, readOnlyCol[collection.Count - 1]);
}
Assert.Equal(expectedCount, readOnlyCol.Count);
Assert.Equal(_expectedCollectionChangedFired, _numCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just added an item");
readOnlyCollectionChanged.CollectionChanged -= Collection_CollectionChanged;
readOnlyPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Clears the given Collection.
/// </summary>
public void ClearTest(ReadOnlyObservableCollection<string> readOnlyCol, ObservableCollection<string> collection)
{
INotifyPropertyChanged readOnlyPropertyChanged = readOnlyCol;
readOnlyPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
INotifyCollectionChanged readOnlyCollectionChange = readOnlyCol;
readOnlyCollectionChange.CollectionChanged += Collection_CollectionChanged;
_expectedCollectionChangedFired++;
_expectedAction = NotifyCollectionChangedAction.Reset;
_expectedNewItems = null;
_expectedNewStartingIndex = -1;
_expectedOldItems = null;
_expectedOldStartingIndex = -1;
collection.Clear();
Assert.Equal(0, readOnlyCol.Count);
Assert.Equal(_expectedCollectionChangedFired, _numCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just cleared the collection.");
readOnlyCollectionChange.CollectionChanged -= Collection_CollectionChanged;
readOnlyPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Given a collection, will move an item from the oldIndex to the newIndex.
/// </summary>
public void MoveItemTest(ReadOnlyObservableCollection<string> readOnlyCol, ObservableCollection<string> collection,
int oldIndex, int newIndex)
{
INotifyPropertyChanged readOnlyPropertyChanged = readOnlyCol;
readOnlyPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[] { new PropertyNameExpected(ITEMARRAY) };
INotifyCollectionChanged readOnlyCollectionChange = readOnlyCol;
readOnlyCollectionChange.CollectionChanged += Collection_CollectionChanged;
string itemAtOldIndex = collection[oldIndex];
_expectedCollectionChangedFired++;
_expectedAction = NotifyCollectionChangedAction.Move;
_expectedNewItems = new string[] { itemAtOldIndex };
_expectedNewStartingIndex = newIndex;
_expectedOldItems = new string[] { itemAtOldIndex };
_expectedOldStartingIndex = oldIndex;
collection.Move(oldIndex, newIndex);
Assert.Equal(collection.Count, readOnlyCol.Count);
Assert.Equal(itemAtOldIndex, readOnlyCol[newIndex]);
Assert.Equal(_expectedCollectionChangedFired, _numCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we moved an item.");
readOnlyCollectionChange.CollectionChanged -= Collection_CollectionChanged;
readOnlyPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Will set that new item at the specified index in the given collection.
/// </summary>
public void ReplaceItemTest(ReadOnlyObservableCollection<string> readOnlyCol, ObservableCollection<string> collection,
int index, string newItem)
{
INotifyPropertyChanged readOnlyPropertyChanged = readOnlyCol;
readOnlyPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[] { new PropertyNameExpected(ITEMARRAY) };
INotifyCollectionChanged readOnlyCollectionChange = readOnlyCol;
readOnlyCollectionChange.CollectionChanged += Collection_CollectionChanged;
string itemAtOldIndex = collection[index];
_expectedCollectionChangedFired++;
_expectedAction = NotifyCollectionChangedAction.Replace;
_expectedNewItems = new string[] { newItem };
_expectedNewStartingIndex = index;
_expectedOldItems = new string[] { itemAtOldIndex };
_expectedOldStartingIndex = index;
int expectedCount = collection.Count;
collection[index] = newItem;
Assert.Equal(expectedCount, readOnlyCol.Count);
Assert.Equal(newItem, readOnlyCol[index]);
Assert.Equal(_expectedCollectionChangedFired, _numCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we replaced an item");
readOnlyCollectionChange.CollectionChanged -= Collection_CollectionChanged;
readOnlyPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Given a collection, index and item to remove, will try to remove that item
/// from the index. If the item has duplicates, will verify that only the first
/// instance was removed.
/// </summary>
public void RemoveItemTest(ReadOnlyObservableCollection<string> readOnlyCol, ObservableCollection<string> collection,
int itemIndex, string itemToRemove, bool isSuccessfulRemove, bool hasDuplicates)
{
INotifyPropertyChanged readOnlyPropertyChanged = readOnlyCol;
readOnlyPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
INotifyCollectionChanged readOnlyCollectionChange = readOnlyCol;
readOnlyCollectionChange.CollectionChanged += Collection_CollectionChanged;
if (isSuccessfulRemove)
_expectedCollectionChangedFired++;
_expectedAction = NotifyCollectionChangedAction.Remove;
_expectedNewItems = null;
_expectedNewStartingIndex = -1;
_expectedOldItems = new string[] { itemToRemove };
_expectedOldStartingIndex = itemIndex;
int expectedCount = isSuccessfulRemove ? collection.Count - 1 : collection.Count;
bool removedItem = collection.Remove(itemToRemove);
Assert.Equal(expectedCount, readOnlyCol.Count);
Assert.Equal(_expectedCollectionChangedFired, _numCollectionChangedFired);
if (isSuccessfulRemove)
{
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since an item was removed");
Assert.True(removedItem, "Should have been successful in removing the item.");
}
else
{
foreach (var item in _expectedPropertyChanged)
Assert.False(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since no items were removed.");
Assert.False(removedItem, "Should not have been successful in removing the item.");
}
if (hasDuplicates)
return;
Assert.DoesNotContain(itemToRemove, collection);
readOnlyCollectionChange.CollectionChanged -= Collection_CollectionChanged;
readOnlyPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
/// <summary>
/// Verifies that the item is removed from a given index in the collection.
/// </summary>
public void RemoveItemAtTest(ReadOnlyObservableCollection<string> readOnlyCol, ObservableCollection<string> collection,
int itemIndex)
{
INotifyPropertyChanged readOnlyPropertyChanged = readOnlyCol;
readOnlyPropertyChanged.PropertyChanged += Collection_PropertyChanged;
_expectedPropertyChanged = new[]
{
new PropertyNameExpected(COUNT),
new PropertyNameExpected(ITEMARRAY)
};
INotifyCollectionChanged readOnlyCollectionChange = readOnlyCol;
readOnlyCollectionChange.CollectionChanged += Collection_CollectionChanged;
string itemAtOldIndex = collection[itemIndex];
_expectedCollectionChangedFired++;
_expectedAction = NotifyCollectionChangedAction.Remove;
_expectedNewItems = null;
_expectedNewStartingIndex = -1;
_expectedOldItems = new string[] { itemAtOldIndex };
_expectedOldStartingIndex = itemIndex;
int expectedCount = collection.Count - 1;
collection.RemoveAt(itemIndex);
Assert.Equal(expectedCount, readOnlyCol.Count);
Assert.Equal(_expectedCollectionChangedFired, _numCollectionChangedFired);
foreach (var item in _expectedPropertyChanged)
Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we replaced an item");
readOnlyCollectionChange.CollectionChanged -= Collection_CollectionChanged;
readOnlyPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
}
#region Helper Methods / Classes
/// <summary>
/// Verifies that the eventargs fired matches the expected results.
/// </summary>
private void VerifyEventArgs(NotifyCollectionChangedEventArgs e)
{
Assert.Equal(_expectedNewStartingIndex, e.NewStartingIndex);
Assert.Equal(_expectedOldStartingIndex, e.OldStartingIndex);
if (_expectedNewItems != null)
{
foreach (var newItem in e.NewItems)
Assert.True(_expectedNewItems.Contains(newItem), "newItem was not in the ExpectedNewItems. newItem: " + newItem);
foreach (var expectedItem in _expectedNewItems)
Assert.True(e.NewItems.Contains(expectedItem), "expectedItem was not in e.NewItems. expectedItem: " + expectedItem);
}
else
{
Assert.Null(e.NewItems);
}
if (_expectedOldItems != null)
{
foreach (var oldItem in e.OldItems)
Assert.True(_expectedOldItems.Contains(oldItem), "oldItem was not in the ExpectedOldItems. oldItem: " + oldItem);
foreach (var expectedItem in _expectedOldItems)
Assert.True(e.OldItems.Contains(expectedItem), "expectedItem was not in e.OldItems. expectedItem: " + expectedItem);
}
else
{
Assert.Null(e.OldItems);
}
}
private void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Assert.True(sender is ReadOnlyObservableCollection<string>, "The sender of this event should be the ReadOnlyObservableCollection.");
_numCollectionChangedFired++;
Assert.Equal(_expectedAction, e.Action);
switch (_expectedAction)
{
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
case NotifyCollectionChangedAction.Move:
case NotifyCollectionChangedAction.Reset:
case NotifyCollectionChangedAction.Replace:
VerifyEventArgs(e);
break;
default:
throw new NotSupportedException("Does not support this action yet.");
}
}
private void Collection_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Assert.True(sender is ReadOnlyObservableCollection<string>, "The sender of this event should be the ReadOnlyObservableCollection.");
foreach (var item in _expectedPropertyChanged)
{
if (item.Name == e.PropertyName)
item.IsFound = true;
}
}
/// <summary>
/// Helper class to keep track of what propertychanges we expect and whether they were found or not.
/// </summary>
private class PropertyNameExpected
{
internal PropertyNameExpected(string name)
{
Name = name;
}
internal string Name { get; private set; }
internal bool IsFound { get; set; }
}
#endregion
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using Voxalia.Shared;
namespace Voxalia.ServerGame.WorldSystem
{
[Flags]
public enum BlockFlags: byte
{
/// <summary>
/// The block has nothing special about it.
/// </summary>
NONE = 0,
/// <summary>
/// The block has been edited by a user.
/// </summary>
EDITED = 1,
/// <summary>
/// The block is powered.
/// </summary>
POWERED = 2,
/// <summary>
/// The block has some form of filling.
/// </summary>
FILLED = 4,
/// <summary>
/// The block has some form of filling.
/// </summary>
FILLED2 = 8,
/// <summary>
/// The block has some form of filling.
/// </summary>
FILLED3 = 16,
/// <summary>
/// The block has some form of filling.
/// </summary>
FILLED4 = 32,
/// <summary>
/// The block needs to be recalculated (physics, liquid movement, etc. could be relevant.)
/// </summary>
NEEDS_RECALC = 64,
/// <summary>
/// The block cannot be edited by users.
/// </summary>
PROTECTED = 128
}
public static class BlockInternalExtensions
{
public static bool IsFilled(this BlockInternal bi)
{
return ((BlockFlags)bi.BlockLocalData).HasFlag(BlockFlags.FILLED)
|| ((BlockFlags)bi.BlockLocalData).HasFlag(BlockFlags.FILLED2)
|| ((BlockFlags)bi.BlockLocalData).HasFlag(BlockFlags.FILLED3)
|| ((BlockFlags)bi.BlockLocalData).HasFlag(BlockFlags.FILLED4);
}
public static bool WasEdited(this BlockInternal bi)
{
return ((BlockFlags)bi.BlockLocalData).HasFlag(BlockFlags.EDITED);
}
public static bool IsPowered(this BlockInternal bi)
{
return ((BlockFlags)bi.BlockLocalData).HasFlag(BlockFlags.POWERED);
}
public static FillType GetFillType(this BlockInternal bi)
{
bool f1 = ((BlockFlags)bi.BlockLocalData).HasFlag(BlockFlags.FILLED);
bool f2 = ((BlockFlags)bi.BlockLocalData).HasFlag(BlockFlags.FILLED2);
bool f3 = ((BlockFlags)bi.BlockLocalData).HasFlag(BlockFlags.FILLED3);
bool f4 = ((BlockFlags)bi.BlockLocalData).HasFlag(BlockFlags.FILLED4);
if (f4)
{
if (f1)
{
if (f2)
{
if (f3)
{
return FillType.MUD;
}
else
{
return FillType.STEAM;
}
}
else
{
if (f3)
{
return FillType.HEAVY_GAS;
}
else
{
return FillType.POISON_GAS;
}
}
}
else
{
if (f2)
{
if (f3)
{
return FillType.FRESH_WATER;
}
else
{
return FillType.HELIUM_GAS;
}
}
else
{
if (f3)
{
return FillType.LIQUID_NITROGEN;
}
else
{
return FillType.BOILING_WATER;
}
}
}
}
else
{
if (f1)
{
if (f2)
{
if (f3)
{
return FillType.SALT_WATER;
}
else
{
return FillType.BAD_WATER;
}
}
else
{
if (f3)
{
return FillType.OIL;
}
else
{
return FillType.LAVA;
}
}
}
else
{
if (f2)
{
if (f3)
{
return FillType.POISON;
}
else
{
return FillType.BLOOD;
}
}
else
{
if (f3)
{
return FillType.HONEY;
}
else
{
return FillType.NONE;
}
}
}
}
}
}
public enum FillType : byte
{
NONE = 0,
SALT_WATER = 1,
BAD_WATER = 2,
OIL = 3,
LAVA = 4,
POISON = 5,
BLOOD = 6,
HONEY = 7,
MUD = 8,
STEAM = 9,
HEAVY_GAS = 10,
POISON_GAS = 11,
FRESH_WATER = 12,
HELIUM_GAS = 13,
LIQUID_NITROGEN = 14,
BOILING_WATER = 15
}
}
| |
using UnityEngine;
public static class tk2dSpriteGeomGen
{
// Common
public static void SetSpriteColors(Color32[] dest, int offset, int numVertices, Color c, bool premulAlpha)
{
if (premulAlpha) { c.r *= c.a; c.g *= c.a; c.b *= c.a; }
Color32 c32 = c;
for (int i = 0; i < numVertices; ++i)
dest[offset + i] = c32;
}
public static Vector2 GetAnchorOffset( tk2dBaseSprite.Anchor anchor, float width, float height ) {
Vector2 anchorOffset = Vector2.zero;
switch (anchor) {
case tk2dBaseSprite.Anchor.LowerLeft: case tk2dBaseSprite.Anchor.MiddleLeft: case tk2dBaseSprite.Anchor.UpperLeft:
break;
case tk2dBaseSprite.Anchor.LowerCenter: case tk2dBaseSprite.Anchor.MiddleCenter: case tk2dBaseSprite.Anchor.UpperCenter:
anchorOffset.x = (int)(width / 2.0f); break;
case tk2dBaseSprite.Anchor.LowerRight: case tk2dBaseSprite.Anchor.MiddleRight: case tk2dBaseSprite.Anchor.UpperRight:
anchorOffset.x = (int)(width); break;
}
switch (anchor) {
case tk2dBaseSprite.Anchor.UpperLeft: case tk2dBaseSprite.Anchor.UpperCenter: case tk2dBaseSprite.Anchor.UpperRight:
break;
case tk2dBaseSprite.Anchor.MiddleLeft: case tk2dBaseSprite.Anchor.MiddleCenter: case tk2dBaseSprite.Anchor.MiddleRight:
anchorOffset.y = (int)(height / 2.0f); break;
case tk2dBaseSprite.Anchor.LowerLeft: case tk2dBaseSprite.Anchor.LowerCenter: case tk2dBaseSprite.Anchor.LowerRight:
anchorOffset.y = (int)height; break;
}
return anchorOffset;
}
// Sprite
public static void GetSpriteGeomDesc(out int numVertices, out int numIndices, tk2dSpriteDefinition spriteDef)
{
numVertices = spriteDef.positions.Length;
numIndices = spriteDef.indices.Length;
}
public static void SetSpriteGeom(Vector3[] pos, Vector2[] uv, Vector3[] norm, Vector4[] tang, int offset, tk2dSpriteDefinition spriteDef, Vector3 scale)
{
for (int i = 0; i < spriteDef.positions.Length; ++i)
{
pos[offset + i] = Vector3.Scale(spriteDef.positions[i], scale);
}
for (int i = 0; i < spriteDef.uvs.Length; ++i)
{
uv[offset + i] = spriteDef.uvs[i];
}
if (norm != null && spriteDef.normals != null)
{
for (int i = 0; i < spriteDef.normals.Length; ++i)
{
norm[offset + i] = spriteDef.normals[i];
}
}
if (tang != null && spriteDef.tangents != null)
{
for (int i = 0; i < spriteDef.tangents.Length; ++i)
{
tang[offset + i] = spriteDef.tangents[i];
}
}
}
public static void SetSpriteIndices(int[] indices, int offset, int vStart, tk2dSpriteDefinition spriteDef)
{
for (int i = 0; i < spriteDef.indices.Length; ++i)
{
indices[offset + i] = vStart + spriteDef.indices[i];
}
}
// Clipped sprite
public static void GetClippedSpriteGeomDesc(out int numVertices, out int numIndices, tk2dSpriteDefinition spriteDef)
{
if (spriteDef.positions.Length == 4)
{
numVertices = 4;
numIndices = 6;
}
else {
numVertices = 0;
numIndices = 0;
}
}
public static void SetClippedSpriteGeom( Vector3[] pos, Vector2[] uv, int offset, out Vector3 boundsCenter, out Vector3 boundsExtents, tk2dSpriteDefinition spriteDef, Vector3 scale, Vector2 clipBottomLeft, Vector2 clipTopRight, float colliderOffsetZ, float colliderExtentZ )
{
boundsCenter = Vector3.zero;
boundsExtents = Vector3.zero;
if (spriteDef.positions.Length == 4)
{
// Transform clipped region from untrimmed -> trimmed region
Vector3 untrimmedMin = spriteDef.untrimmedBoundsData[0] - spriteDef.untrimmedBoundsData[1] * 0.5f;
Vector3 untrimmedMax = spriteDef.untrimmedBoundsData[0] + spriteDef.untrimmedBoundsData[1] * 0.5f;
// clipBottomLeft is the fraction to start from the bottom left (0,0 - full sprite)
// clipTopRight is the fraction to start from the top right (1,1 - full sprite)
float left = Mathf.Lerp( untrimmedMin.x, untrimmedMax.x, clipBottomLeft.x );
float right = Mathf.Lerp( untrimmedMin.x, untrimmedMax.x, clipTopRight.x );
float bottom = Mathf.Lerp( untrimmedMin.y, untrimmedMax.y, clipBottomLeft.y );
float top = Mathf.Lerp( untrimmedMin.y, untrimmedMax.y, clipTopRight.y );
Vector3 trimmedBounds = spriteDef.boundsData[1];
Vector3 trimmedOrigin = spriteDef.boundsData[0] - trimmedBounds * 0.5f;
float clipLeft = (left - trimmedOrigin.x) / trimmedBounds.x;
float clipRight = (right - trimmedOrigin.x) / trimmedBounds.x;
float clipBottom = (bottom - trimmedOrigin.y) / trimmedBounds.y;
float clipTop = (top - trimmedOrigin.y) / trimmedBounds.y;
// The fractional clip region relative to the trimmed region
Vector2 fracBottomLeft = new Vector2( Mathf.Clamp01( clipLeft ), Mathf.Clamp01( clipBottom ) );
Vector2 fracTopRight = new Vector2( Mathf.Clamp01( clipRight ), Mathf.Clamp01( clipTop ) );
// Default quad has index 0 = bottomLeft, index 3 = topRight
Vector3 c0 = spriteDef.positions[0];
Vector3 c1 = spriteDef.positions[3];
// find the fraction of positions, but fold in the scale multiply as well
Vector3 bottomLeft = new Vector3(Mathf.Lerp(c0.x, c1.x, fracBottomLeft.x) * scale.x,
Mathf.Lerp(c0.y, c1.y, fracBottomLeft.y) * scale.y,
c0.z * scale.z);
Vector3 topRight = new Vector3(Mathf.Lerp(c0.x, c1.x, fracTopRight.x) * scale.x,
Mathf.Lerp(c0.y, c1.y, fracTopRight.y) * scale.y,
c0.z * scale.z);
boundsCenter.Set( bottomLeft.x + (topRight.x - bottomLeft.x) * 0.5f, bottomLeft.y + (topRight.y - bottomLeft.y) * 0.5f, colliderOffsetZ );
boundsExtents.Set( (topRight.x - bottomLeft.x) * 0.5f, (topRight.y - bottomLeft.y) * 0.5f, colliderExtentZ );
// The z component only needs to be consistent
pos[offset + 0] = new Vector3(bottomLeft.x, bottomLeft.y, bottomLeft.z);
pos[offset + 1] = new Vector3(topRight.x, bottomLeft.y, bottomLeft.z);
pos[offset + 2] = new Vector3(bottomLeft.x, topRight.y, bottomLeft.z);
pos[offset + 3] = new Vector3(topRight.x, topRight.y, bottomLeft.z);
// find the fraction of UV
// This can be done without a branch, but will end up with loads of unnecessary interpolations
if (spriteDef.flipped == tk2dSpriteDefinition.FlipMode.Tk2d)
{
Vector2 v0 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracBottomLeft.y),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracBottomLeft.x));
Vector2 v1 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracTopRight.y),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracTopRight.x));
uv[offset + 0] = new Vector2(v0.x, v0.y);
uv[offset + 1] = new Vector2(v0.x, v1.y);
uv[offset + 2] = new Vector2(v1.x, v0.y);
uv[offset + 3] = new Vector2(v1.x, v1.y);
}
else if (spriteDef.flipped == tk2dSpriteDefinition.FlipMode.TPackerCW)
{
Vector2 v0 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracBottomLeft.y),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracBottomLeft.x));
Vector2 v1 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracTopRight.y),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracTopRight.x));
uv[offset + 0] = new Vector2(v0.x, v0.y);
uv[offset + 2] = new Vector2(v1.x, v0.y);
uv[offset + 1] = new Vector2(v0.x, v1.y);
uv[offset + 3] = new Vector2(v1.x, v1.y);
}
else
{
Vector2 v0 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracBottomLeft.x),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracBottomLeft.y));
Vector2 v1 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracTopRight.x),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracTopRight.y));
uv[offset + 0] = new Vector2(v0.x, v0.y);
uv[offset + 1] = new Vector2(v1.x, v0.y);
uv[offset + 2] = new Vector2(v0.x, v1.y);
uv[offset + 3] = new Vector2(v1.x, v1.y);
}
}
}
public static void SetClippedSpriteIndices( int[] indices, int offset, int vStart, tk2dSpriteDefinition spriteDef)
{
if (spriteDef.positions.Length == 4)
{
indices[offset + 0] = vStart + 0;
indices[offset + 1] = vStart + 3;
indices[offset + 2] = vStart + 1;
indices[offset + 3] = vStart + 2;
indices[offset + 4] = vStart + 3;
indices[offset + 5] = vStart + 0;
}
}
// Sliced sprite
public static void GetSlicedSpriteGeomDesc(out int numVertices, out int numIndices, tk2dSpriteDefinition spriteDef, bool borderOnly)
{
if (spriteDef.positions.Length == 4)
{
numVertices = 16;
numIndices = borderOnly ? (8 * 6) : (9 * 6);
} else {
numVertices = 0;
numIndices = 0;
}
}
public static void SetSlicedSpriteGeom(Vector3[] pos, Vector2[] uv, int offset, out Vector3 boundsCenter, out Vector3 boundsExtents, tk2dSpriteDefinition spriteDef, Vector3 scale, Vector2 dimensions, Vector2 borderBottomLeft, Vector2 borderTopRight, tk2dBaseSprite.Anchor anchor, float colliderOffsetZ, float colliderExtentZ)
{
boundsCenter = Vector3.zero;
boundsExtents = Vector3.zero;
if (spriteDef.positions.Length == 4)
{
float sx = spriteDef.texelSize.x;
float sy = spriteDef.texelSize.y;
Vector3[] srcVert = spriteDef.positions;
float dx = (srcVert[1].x - srcVert[0].x);
float dy = (srcVert[2].y - srcVert[0].y);
float borderTopPixels = borderTopRight.y * dy;
float borderBottomPixels = borderBottomLeft.y * dy;
float borderRightPixels = borderTopRight.x * dx;
float borderLeftPixels = borderBottomLeft.x * dx;
float dimXPixels = dimensions.x * sx;
float dimYPixels = dimensions.y * sy;
float anchorOffsetX = 0.0f;
float anchorOffsetY = 0.0f;
switch (anchor)
{
case tk2dBaseSprite.Anchor.LowerLeft: case tk2dBaseSprite.Anchor.MiddleLeft: case tk2dBaseSprite.Anchor.UpperLeft:
break;
case tk2dBaseSprite.Anchor.LowerCenter: case tk2dBaseSprite.Anchor.MiddleCenter: case tk2dBaseSprite.Anchor.UpperCenter:
anchorOffsetX = -(int)(dimensions.x / 2.0f); break;
case tk2dBaseSprite.Anchor.LowerRight: case tk2dBaseSprite.Anchor.MiddleRight: case tk2dBaseSprite.Anchor.UpperRight:
anchorOffsetX = -(int)(dimensions.x); break;
}
switch (anchor)
{
case tk2dBaseSprite.Anchor.LowerLeft: case tk2dBaseSprite.Anchor.LowerCenter: case tk2dBaseSprite.Anchor.LowerRight:
break;
case tk2dBaseSprite.Anchor.MiddleLeft: case tk2dBaseSprite.Anchor.MiddleCenter: case tk2dBaseSprite.Anchor.MiddleRight:
anchorOffsetY = -(int)(dimensions.y / 2.0f); break;
case tk2dBaseSprite.Anchor.UpperLeft: case tk2dBaseSprite.Anchor.UpperCenter: case tk2dBaseSprite.Anchor.UpperRight:
anchorOffsetY = -(int)dimensions.y; break;
}
// scale back to sprite coordinates
// do it after the cast above, as we're trying to align to pixel
anchorOffsetX *= sx;
anchorOffsetY *= sy;
boundsCenter.Set(scale.x * (dimXPixels * 0.5f + anchorOffsetX), scale.y * (dimYPixels * 0.5f + anchorOffsetY), colliderOffsetZ);
boundsExtents.Set(scale.x * (dimXPixels * 0.5f), scale.y * (dimYPixels * 0.5f), colliderExtentZ);
Vector2[] srcUv = spriteDef.uvs;
Vector2 duvx = srcUv[1] - srcUv[0];
Vector2 duvy = srcUv[2] - srcUv[0];
Vector3 origin = new Vector3(anchorOffsetX, anchorOffsetY, 0);
Vector3[] originPoints = new Vector3[4] {
origin,
origin + new Vector3(0, borderBottomPixels, 0),
origin + new Vector3(0, dimYPixels - borderTopPixels, 0),
origin + new Vector3(0, dimYPixels, 0),
};
Vector2[] originUvs = new Vector2[4] {
srcUv[0],
srcUv[0] + duvy * borderBottomLeft.y,
srcUv[0] + duvy * (1 - borderTopRight.y),
srcUv[0] + duvy,
};
for (int i = 0; i < 4; ++i)
{
pos[offset + i * 4 + 0] = originPoints[i];
pos[offset + i * 4 + 1] = originPoints[i] + new Vector3(borderLeftPixels, 0, 0);
pos[offset + i * 4 + 2] = originPoints[i] + new Vector3(dimXPixels - borderRightPixels, 0, 0);
pos[offset + i * 4 + 3] = originPoints[i] + new Vector3(dimXPixels, 0, 0);
for (int j = 0; j < 4; ++j) {
pos[offset + i * 4 + j] = Vector3.Scale(pos[offset + i * 4 + j], scale);
}
uv[offset + i * 4 + 0] = originUvs[i];
uv[offset + i * 4 + 1] = originUvs[i] + duvx * borderBottomLeft.x;
uv[offset + i * 4 + 2] = originUvs[i] + duvx * (1 - borderTopRight.x);
uv[offset + i * 4 + 3] = originUvs[i] + duvx;
}
}
}
public static void SetSlicedSpriteIndices(int[] indices, int offset, int vStart, tk2dSpriteDefinition spriteDef, bool borderOnly)
{
if (spriteDef.positions.Length == 4)
{
int[] inds = new int[9 * 6] {
0, 4, 1, 1, 4, 5,
1, 5, 2, 2, 5, 6,
2, 6, 3, 3, 6, 7,
4, 8, 5, 5, 8, 9,
6, 10, 7, 7, 10, 11,
8, 12, 9, 9, 12, 13,
9, 13, 10, 10, 13, 14,
10, 14, 11, 11, 14, 15,
5, 9, 6, 6, 9, 10 // middle bit
};
int n = inds.Length;
if (borderOnly) n -= 6; // take out middle
for (int i = 0; i < n; ++i) {
indices[offset + i] = vStart + inds[i];
}
}
}
// Tiled sprite
public static void GetTiledSpriteGeomDesc(out int numVertices, out int numIndices, tk2dSpriteDefinition spriteDef, Vector2 dimensions)
{
int numTilesX = (int)Mathf.Ceil( (dimensions.x * spriteDef.texelSize.x) / spriteDef.untrimmedBoundsData[1].x );
int numTilesY = (int)Mathf.Ceil( (dimensions.y * spriteDef.texelSize.y) / spriteDef.untrimmedBoundsData[1].y );
numVertices = numTilesX * numTilesY * 4;
numIndices = numTilesX * numTilesY * 6;
}
public static void SetTiledSpriteGeom(Vector3[] pos, Vector2[] uv, int offset, out Vector3 boundsCenter, out Vector3 boundsExtents, tk2dSpriteDefinition spriteDef, Vector3 scale, Vector2 dimensions, tk2dBaseSprite.Anchor anchor, float colliderOffsetZ, float colliderExtentZ)
{
boundsCenter = Vector3.zero;
boundsExtents = Vector3.zero;
int numTilesX = (int)Mathf.Ceil( (dimensions.x * spriteDef.texelSize.x) / spriteDef.untrimmedBoundsData[1].x );
int numTilesY = (int)Mathf.Ceil( (dimensions.y * spriteDef.texelSize.y) / spriteDef.untrimmedBoundsData[1].y );
Vector2 totalMeshSize = new Vector2( dimensions.x * spriteDef.texelSize.x * scale.x, dimensions.y * spriteDef.texelSize.y * scale.y );
// Anchor tweaks
Vector3 anchorOffset = Vector3.zero;
switch (anchor)
{
case tk2dBaseSprite.Anchor.LowerLeft: case tk2dBaseSprite.Anchor.MiddleLeft: case tk2dBaseSprite.Anchor.UpperLeft:
break;
case tk2dBaseSprite.Anchor.LowerCenter: case tk2dBaseSprite.Anchor.MiddleCenter: case tk2dBaseSprite.Anchor.UpperCenter:
anchorOffset.x = -(totalMeshSize.x / 2.0f); break;
case tk2dBaseSprite.Anchor.LowerRight: case tk2dBaseSprite.Anchor.MiddleRight: case tk2dBaseSprite.Anchor.UpperRight:
anchorOffset.x = -(totalMeshSize.x); break;
}
switch (anchor)
{
case tk2dBaseSprite.Anchor.LowerLeft: case tk2dBaseSprite.Anchor.LowerCenter: case tk2dBaseSprite.Anchor.LowerRight:
break;
case tk2dBaseSprite.Anchor.MiddleLeft: case tk2dBaseSprite.Anchor.MiddleCenter: case tk2dBaseSprite.Anchor.MiddleRight:
anchorOffset.y = -(totalMeshSize.y / 2.0f); break;
case tk2dBaseSprite.Anchor.UpperLeft: case tk2dBaseSprite.Anchor.UpperCenter: case tk2dBaseSprite.Anchor.UpperRight:
anchorOffset.y = -totalMeshSize.y; break;
}
Vector3 colliderAnchor = anchorOffset;
anchorOffset -= Vector3.Scale( spriteDef.positions[0], scale );
boundsCenter.Set(totalMeshSize.x * 0.5f + colliderAnchor.x, totalMeshSize.y * 0.5f + colliderAnchor.y, colliderOffsetZ );
boundsExtents.Set(totalMeshSize.x * 0.5f, totalMeshSize.y * 0.5f, colliderExtentZ);
int vert = 0;
Vector3 bounds = Vector3.Scale( spriteDef.untrimmedBoundsData[1], scale );
Vector3 baseOffset = Vector3.zero;
Vector3 p = baseOffset;
for (int y = 0; y < numTilesY; ++y) {
p.x = baseOffset.x;
for (int x = 0; x < numTilesX; ++x) {
float xClipFrac = 1;
float yClipFrac = 1;
if (Mathf.Abs(p.x + bounds.x) > Mathf.Abs(totalMeshSize.x) ) {
xClipFrac = ((totalMeshSize.x % bounds.x) / bounds.x);
}
if (Mathf.Abs(p.y + bounds.y) > Mathf.Abs(totalMeshSize.y)) {
yClipFrac = ((totalMeshSize.y % bounds.y) / bounds.y);
}
Vector3 geomOffset = p + anchorOffset;
if (xClipFrac != 1 || yClipFrac != 1) {
Vector2 fracBottomLeft = Vector2.zero;
Vector2 fracTopRight = new Vector2(xClipFrac, yClipFrac);
Vector3 bottomLeft = new Vector3(Mathf.Lerp(spriteDef.positions[0].x, spriteDef.positions[3].x, fracBottomLeft.x) * scale.x,
Mathf.Lerp(spriteDef.positions[0].y, spriteDef.positions[3].y, fracBottomLeft.y) * scale.y,
spriteDef.positions[0].z * scale.z);
Vector3 topRight = new Vector3(Mathf.Lerp(spriteDef.positions[0].x, spriteDef.positions[3].x, fracTopRight.x) * scale.x,
Mathf.Lerp(spriteDef.positions[0].y, spriteDef.positions[3].y, fracTopRight.y) * scale.y,
spriteDef.positions[0].z * scale.z);
pos[offset + vert + 0] = geomOffset + new Vector3(bottomLeft.x, bottomLeft.y, bottomLeft.z);
pos[offset + vert + 1] = geomOffset + new Vector3(topRight.x, bottomLeft.y, bottomLeft.z);
pos[offset + vert + 2] = geomOffset + new Vector3(bottomLeft.x, topRight.y, bottomLeft.z);
pos[offset + vert + 3] = geomOffset + new Vector3(topRight.x, topRight.y, bottomLeft.z);
// find the fraction of UV
// This can be done without a branch, but will end up with loads of unnecessary interpolations
if (spriteDef.flipped == tk2dSpriteDefinition.FlipMode.Tk2d)
{
Vector2 v0 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracBottomLeft.y),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracBottomLeft.x));
Vector2 v1 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracTopRight.y),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracTopRight.x));
uv[offset + vert + 0] = new Vector2(v0.x, v0.y);
uv[offset + vert + 1] = new Vector2(v0.x, v1.y);
uv[offset + vert + 2] = new Vector2(v1.x, v0.y);
uv[offset + vert + 3] = new Vector2(v1.x, v1.y);
}
else if (spriteDef.flipped == tk2dSpriteDefinition.FlipMode.TPackerCW)
{
Vector2 v0 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracBottomLeft.y),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracBottomLeft.x));
Vector2 v1 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracTopRight.y),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracTopRight.x));
uv[offset + vert + 0] = new Vector2(v0.x, v0.y);
uv[offset + vert + 2] = new Vector2(v1.x, v0.y);
uv[offset + vert + 1] = new Vector2(v0.x, v1.y);
uv[offset + vert + 3] = new Vector2(v1.x, v1.y);
}
else
{
Vector2 v0 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracBottomLeft.x),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracBottomLeft.y));
Vector2 v1 = new Vector2(Mathf.Lerp(spriteDef.uvs[0].x, spriteDef.uvs[3].x, fracTopRight.x),
Mathf.Lerp(spriteDef.uvs[0].y, spriteDef.uvs[3].y, fracTopRight.y));
uv[offset + vert + 0] = new Vector2(v0.x, v0.y);
uv[offset + vert + 1] = new Vector2(v1.x, v0.y);
uv[offset + vert + 2] = new Vector2(v0.x, v1.y);
uv[offset + vert + 3] = new Vector2(v1.x, v1.y);
}
}
else {
pos[offset + vert + 0] = geomOffset + Vector3.Scale( spriteDef.positions[0], scale );
pos[offset + vert + 1] = geomOffset + Vector3.Scale( spriteDef.positions[1], scale );
pos[offset + vert + 2] = geomOffset + Vector3.Scale( spriteDef.positions[2], scale );
pos[offset + vert + 3] = geomOffset + Vector3.Scale( spriteDef.positions[3], scale );
uv[offset + vert + 0] = spriteDef.uvs[0];
uv[offset + vert + 1] = spriteDef.uvs[1];
uv[offset + vert + 2] = spriteDef.uvs[2];
uv[offset + vert + 3] = spriteDef.uvs[3];
}
vert += 4;
p.x += bounds.x;
}
p.y += bounds.y;
}
}
public static void SetTiledSpriteIndices(int[] indices, int offset, int vStart, tk2dSpriteDefinition spriteDef, Vector2 dimensions)
{
int numVertices;
int numIndices;
GetTiledSpriteGeomDesc(out numVertices, out numIndices, spriteDef, dimensions);
int baseIndex = 0;
for (int i = 0; i < numIndices; i += 6) {
indices[offset + i + 0] = vStart + spriteDef.indices[0] + baseIndex;
indices[offset + i + 1] = vStart + spriteDef.indices[1] + baseIndex;
indices[offset + i + 2] = vStart + spriteDef.indices[2] + baseIndex;
indices[offset + i + 3] = vStart + spriteDef.indices[3] + baseIndex;
indices[offset + i + 4] = vStart + spriteDef.indices[4] + baseIndex;
indices[offset + i + 5] = vStart + spriteDef.indices[5] + baseIndex;
baseIndex += 4;
}
}
// Composite mesh for batched mesh. Box, and SpriteDefinition meshes.
// Does transform here too.
static readonly int[] boxIndicesBack = { 0, 1, 2, 2, 1, 3, 6, 5, 4, 7, 5, 6, 3, 7, 6, 2, 3, 6, 4, 5, 1, 4, 1, 0, 6, 4, 0, 6, 0, 2, 1, 7, 3, 5, 7, 1 };
static readonly int[] boxIndicesFwd = { 2, 1, 0, 3, 1, 2, 4, 5, 6, 6, 5, 7, 6, 7, 3, 6, 3, 2, 1, 5, 4, 0, 1, 4, 0, 4, 6, 2, 0, 6, 3, 7, 1, 1, 7, 5 };
static readonly Vector3[] boxUnitVertices = new Vector3[] { new Vector3(-1,-1,-1), new Vector3(-1,-1,1), new Vector3(1,-1,-1), new Vector3(1,-1,1),
new Vector3(-1,1,-1), new Vector3(-1,1,1), new Vector3(1,1,-1), new Vector3(1,1,1) };
static Matrix4x4 boxScaleMatrix = Matrix4x4.identity;
public static void SetBoxMeshData(Vector3[] pos, int[] indices, int posOffset, int indicesOffset, int vStart, Vector3 origin, Vector3 extents, Matrix4x4 mat, Vector3 baseScale)
{
boxScaleMatrix.m03 = origin.x * baseScale.x;
boxScaleMatrix.m13 = origin.y * baseScale.y;
boxScaleMatrix.m23 = origin.z * baseScale.z;
boxScaleMatrix.m00 = extents.x * baseScale.x;
boxScaleMatrix.m11 = extents.y * baseScale.y;
boxScaleMatrix.m22 = extents.z * baseScale.z;
Matrix4x4 boxFinalMatrix = mat * boxScaleMatrix;
for (int j = 0; j < 8; ++j) {
pos[posOffset + j] = boxFinalMatrix.MultiplyPoint(boxUnitVertices[j]);
}
float scl = mat.m00 * mat.m11 * mat.m22 * baseScale.x * baseScale.y * baseScale.z;
int[] srcIndices = ( scl >= 0 ) ? boxIndicesFwd : boxIndicesBack;
for (int i = 0; i < srcIndices.Length; ++i)
indices[indicesOffset + i] = vStart + srcIndices[i];
}
public static void SetSpriteDefinitionMeshData(Vector3[] pos, int[] indices, int posOffset, int indicesOffset, int vStart, tk2dSpriteDefinition spriteDef, Matrix4x4 mat, Vector3 baseScale)
{
for (int i = 0; i < spriteDef.colliderVertices.Length; ++i)
{
Vector3 p = Vector3.Scale (spriteDef.colliderVertices[i], baseScale);
p = mat.MultiplyPoint (p);
pos[posOffset + i] = p;
}
float scl = mat.m00 * mat.m11 * mat.m22;
int[] srcIndices = (scl >= 0)?spriteDef.colliderIndicesFwd:spriteDef.colliderIndicesBack;
for (int i = 0; i < srcIndices.Length; ++i)
indices[indicesOffset + i] = vStart + srcIndices[i];
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Authentication
{
public class AuthenticationMiddlewareTests
{
[Fact]
public async Task OnlyInvokesCanHandleRequestHandlers()
{
using var host = new HostBuilder()
.ConfigureWebHost(builder =>
builder.UseTestServer()
.Configure(app =>
{
app.UseAuthentication();
})
.ConfigureServices(services => services.AddAuthentication(o =>
{
o.AddScheme("Skip", s =>
{
s.HandlerType = typeof(SkipHandler);
});
// Won't get hit since CanHandleRequests is false
o.AddScheme("throws", s =>
{
s.HandlerType = typeof(ThrowsHandler);
});
o.AddScheme("607", s =>
{
s.HandlerType = typeof(SixOhSevenHandler);
});
// Won't get run since 607 will finish
o.AddScheme("305", s =>
{
s.HandlerType = typeof(ThreeOhFiveHandler);
});
})))
.Build();
await host.StartAsync();
using var server = host.GetTestServer();
var response = await server.CreateClient().GetAsync("http://example.com/");
Assert.Equal(607, (int)response.StatusCode);
}
[Fact]
public async Task IAuthenticateResultFeature_SetOnSuccessfulAuthenticate()
{
var authenticationService = new Mock<IAuthenticationService>();
authenticationService.Setup(s => s.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
.Returns(Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), "custom"))));
var schemeProvider = new Mock<IAuthenticationSchemeProvider>();
schemeProvider.Setup(p => p.GetDefaultAuthenticateSchemeAsync())
.Returns(Task.FromResult(new AuthenticationScheme("custom", "custom", typeof(JwtBearerHandler))));
var middleware = new AuthenticationMiddleware(c => Task.CompletedTask, schemeProvider.Object);
var context = GetHttpContext(authenticationService: authenticationService.Object);
// Act
await middleware.Invoke(context);
// Assert
var authenticateResultFeature = context.Features.Get<IAuthenticateResultFeature>();
Assert.NotNull(authenticateResultFeature);
Assert.NotNull(authenticateResultFeature.AuthenticateResult);
Assert.True(authenticateResultFeature.AuthenticateResult.Succeeded);
Assert.Same(context.User, authenticateResultFeature.AuthenticateResult.Principal);
}
[Fact]
public async Task IAuthenticateResultFeature_NotSetOnUnsuccessfulAuthenticate()
{
var authenticationService = new Mock<IAuthenticationService>();
authenticationService.Setup(s => s.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
.Returns(Task.FromResult(AuthenticateResult.Fail("not authenticated")));
var schemeProvider = new Mock<IAuthenticationSchemeProvider>();
schemeProvider.Setup(p => p.GetDefaultAuthenticateSchemeAsync())
.Returns(Task.FromResult(new AuthenticationScheme("custom", "custom", typeof(JwtBearerHandler))));
var middleware = new AuthenticationMiddleware(c => Task.CompletedTask, schemeProvider.Object);
var context = GetHttpContext(authenticationService: authenticationService.Object);
// Act
await middleware.Invoke(context);
// Assert
var authenticateResultFeature = context.Features.Get<IAuthenticateResultFeature>();
Assert.Null(authenticateResultFeature);
}
[Fact]
public async Task IAuthenticateResultFeature_NullResultWhenUserSetAfter()
{
var authenticationService = new Mock<IAuthenticationService>();
authenticationService.Setup(s => s.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
.Returns(Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), "custom"))));
var schemeProvider = new Mock<IAuthenticationSchemeProvider>();
schemeProvider.Setup(p => p.GetDefaultAuthenticateSchemeAsync())
.Returns(Task.FromResult(new AuthenticationScheme("custom", "custom", typeof(JwtBearerHandler))));
var middleware = new AuthenticationMiddleware(c => Task.CompletedTask, schemeProvider.Object);
var context = GetHttpContext(authenticationService: authenticationService.Object);
// Act
await middleware.Invoke(context);
// Assert
var authenticateResultFeature = context.Features.Get<IAuthenticateResultFeature>();
Assert.NotNull(authenticateResultFeature);
Assert.NotNull(authenticateResultFeature.AuthenticateResult);
Assert.True(authenticateResultFeature.AuthenticateResult.Succeeded);
Assert.Same(context.User, authenticateResultFeature.AuthenticateResult.Principal);
context.User = new ClaimsPrincipal();
Assert.Null(authenticateResultFeature.AuthenticateResult);
}
[Fact]
public async Task IAuthenticateResultFeature_SettingResultSetsUser()
{
var authenticationService = new Mock<IAuthenticationService>();
authenticationService.Setup(s => s.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
.Returns(Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), "custom"))));
var schemeProvider = new Mock<IAuthenticationSchemeProvider>();
schemeProvider.Setup(p => p.GetDefaultAuthenticateSchemeAsync())
.Returns(Task.FromResult(new AuthenticationScheme("custom", "custom", typeof(JwtBearerHandler))));
var middleware = new AuthenticationMiddleware(c => Task.CompletedTask, schemeProvider.Object);
var context = GetHttpContext(authenticationService: authenticationService.Object);
// Act
await middleware.Invoke(context);
// Assert
var authenticateResultFeature = context.Features.Get<IAuthenticateResultFeature>();
Assert.NotNull(authenticateResultFeature);
Assert.NotNull(authenticateResultFeature.AuthenticateResult);
Assert.True(authenticateResultFeature.AuthenticateResult.Succeeded);
Assert.Same(context.User, authenticateResultFeature.AuthenticateResult.Principal);
var newTicket = new AuthenticationTicket(new ClaimsPrincipal(), "");
authenticateResultFeature.AuthenticateResult = AuthenticateResult.Success(newTicket);
Assert.Same(context.User, newTicket.Principal);
}
private HttpContext GetHttpContext(
Action<IServiceCollection> registerServices = null,
IAuthenticationService authenticationService = null)
{
// ServiceProvider
var serviceCollection = new ServiceCollection();
authenticationService = authenticationService ?? Mock.Of<IAuthenticationService>();
serviceCollection.AddSingleton(authenticationService);
serviceCollection.AddOptions();
serviceCollection.AddLogging();
serviceCollection.AddAuthentication();
registerServices?.Invoke(serviceCollection);
var serviceProvider = serviceCollection.BuildServiceProvider();
//// HttpContext
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = serviceProvider;
return httpContext;
}
private class ThreeOhFiveHandler : StatusCodeHandler {
public ThreeOhFiveHandler() : base(305) { }
}
private class SixOhSevenHandler : StatusCodeHandler
{
public SixOhSevenHandler() : base(607) { }
}
private class SevenOhSevenHandler : StatusCodeHandler
{
public SevenOhSevenHandler() : base(707) { }
}
private class StatusCodeHandler : IAuthenticationRequestHandler
{
private HttpContext _context;
private readonly int _code;
public StatusCodeHandler(int code)
{
_code = code;
}
public Task<AuthenticateResult> AuthenticateAsync()
{
throw new NotImplementedException();
}
public Task ChallengeAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task ForbidAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task<bool> HandleRequestAsync()
{
_context.Response.StatusCode = _code;
return Task.FromResult(true);
}
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
_context = context;
return Task.FromResult(0);
}
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task SignOutAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
}
private class ThrowsHandler : IAuthenticationHandler
{
private HttpContext _context;
public Task<AuthenticateResult> AuthenticateAsync()
{
throw new NotImplementedException();
}
public Task ChallengeAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task ForbidAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task<bool> HandleRequestAsync()
{
throw new NotImplementedException();
}
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
_context = context;
return Task.FromResult(0);
}
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task SignOutAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
}
private class SkipHandler : IAuthenticationRequestHandler
{
private HttpContext _context;
public Task<AuthenticateResult> AuthenticateAsync()
{
throw new NotImplementedException();
}
public Task ChallengeAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task ForbidAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task<bool> HandleRequestAsync()
{
return Task.FromResult(false);
}
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
_context = context;
return Task.FromResult(0);
}
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task SignOutAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
}
}
}
| |
using Sandbox.ModAPI.Ingame;
using Sandbox.ModAPI.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace SpaceEngineersScripts.MiningStationAutomation
{
class MiningStationAutomation
{
#region programming environment essential inits, DO NOT COPY TO GAME
private static IMyGridTerminalSystem GridTerminalSystem;
private static IMyProgrammableBlock Me { get; }
private static void Echo(string message) { }
#endregion
#region Programmable block script
#region Config
//OPERATIONAL
const float ROTOR_RPM = 0.5f;
const float DRILL_DOWN_SPEED = 0.008f; //discovered that .008 is still not too fast for the drill down speed
static readonly List<float> DRILL_RADII = new List<float>() { 0f, 3.5f, 7f, 10f }; //Drills can technically do a 5 wide trench, to be sure no small floating rocks are left, do smaller intervals.
const bool DEBUG = true;
const bool DETAILEDDEBUG = false;
const bool FORCEROTOR_TORQUE = true;
const bool INIT_FLATTENING = false; //safety precaution
const bool END_FLATTENING = false; //flatten pit bottom to allow cars to drive more easily;
const float VERTICAL_OFFSET = 0f;
const float TRIGGER_DELAY = 1f; //after how many seconds the script should trigger again. (min 1)
const float CONTAINER_UPPER_THRESHOLD = 0.9f;
const float CONTAINER_LOWER_THRESHOLD = 0.5f;
//BLOCK SETUP
const string TIMER_NAME = "Timer";
const string PROGRAMMABLEBLOCK_NAME = "Programmable Block";
const string ROTOR_NAME = "Drill Rotor";
const string H_PISTON_NAME = "Horizontal Piston";
const string V_PISTON_NAME = "Vertical Piston";
const string DRILL_STATION_NAME = "Drill Station";
const string DEBUG_PANEL_NAME = "Debug Panel";
const string DRILL_STATION_CONTAINER = "Drill Station Container";
const string STORAGE_LIGHT = "FUNCTION=STORAGE";
const float TARGET_DEPTH = 20f;
#endregion
DrillStation station = null;
void Main(string arg)
{
var interiorLightTempList = new List<IMyTerminalBlock>();
GridTerminalSystem.GetBlocksOfType<IMyInteriorLight>(interiorLightTempList);
if (arg.Contains("resetststorage=true"))
{
BlockUtils.ResetStateStorageLights(interiorLightTempList.Cast<IMyInteriorLight>().ToList());
Echo(string.Format("Storage has been reset!"));
return;
}
if (station == null)
{
station = new DrillStation(GridTerminalSystem);
}
station.Request();
}
/// <summary>
/// The InitState
/// </summary>
class InitState : State
{
private StateDTO loadedPersistantStateDTO;
public InitState()
{
this.loadedPersistantStateDTO = null;
}
public StateDTO GetStateDTO(Context context)
{
BlockUtils.AppendDebugOut((context as DrillStation).DrillStationBlocks.DebugPanels, string.Format("Building State DTO with params {0}, {1}, {2}", typeof(InitState).Name, -1, -1));
return new StateDTO(typeof(InitState).Name, -1, -1);
}
public void Handle(Context context)
{
var drillStationBlocks = (context as DrillStation).DrillStationBlocks;
//turn on all blocks
drillStationBlocks.TurnOnAllBlocks();
//set the timer wait and start it
drillStationBlocks.Timer.SetValueFloat("TriggerDelay", TRIGGER_DELAY);
drillStationBlocks.Timer.GetActionWithName("Start").Apply(drillStationBlocks.Timer);
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Moving to start Position");
//move to the start position (pistons at 1m/s rotor at 1 rpm)
if (drillStationBlocks.ToPosition(drillStationBlocks.VerticalPistons, 0, 1, drillStationBlocks.HorizontalPiston, 0, 1, drillStationBlocks.Rotor, 0, 1))
{
if (this.loadedPersistantStateDTO != null)
{
context.State = this.loadedPersistantStateDTO.BuildState();
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("The following state was set on context:\n{0}", context.State.GetStateDTO(context).ToString()));
}
else
{
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "\nDid not find a state stored in persistant storage");
//when done proceed to the next state
if (INIT_FLATTENING)
{
context.State = new FlatteningState(VERTICAL_OFFSET);
}
else
{
context.State = new DeepeningState();
}
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Setting state on context: " + context.State.GetType().Name);
}
}
}
public void LoadFromStateDTO(StateDTO stateDTO)
{
//nothing to do here except set the stateDTO
this.loadedPersistantStateDTO = stateDTO;
return;
}
public string Status(Context context)
{
BlockUtils.AppendDebugOut((context as DrillStation).DrillStationBlocks.DebugPanels, "retrieving status");
return "INIT";
}
}
/// <summary>
/// The FlatteningState
/// </summary>
class FlatteningState : State
{
private int currentCircle = 0;
private float depth;
/// <summary>
/// initializes a new FlatteningState
/// </summary>
/// <param name="targetDepth"> the depth on wich the flattening needs to happen</param>
public FlatteningState(float targetDepth)
{
this.depth = targetDepth;
}
public StateDTO GetStateDTO(Context context)
{
BlockUtils.AppendDebugOut((context as DrillStation).DrillStationBlocks.DebugPanels, string.Format("Building State DTO with params {0}, {1}, {2}", typeof(FlatteningState).Name, currentCircle, depth));
return new StateDTO(typeof(FlatteningState).Name, currentCircle, depth);
}
public void Handle(Context context)
{
var drillStationBlocks = (context as DrillStation).DrillStationBlocks;
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("Flattening: currentCircle {0}", currentCircle));
//if currentCircle < the number of radii to flatten, else move to start, and proceed to next state
if (currentCircle < DRILL_RADII.Count)
{
//move the rotor to -360 degree on even circles, to 0 degree on uneven circles, with ROTOR_RPM
var targetDegree = (currentCircle % 2 == 0) ? -360 : 0;
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("Flattening: targetDegree = {0}", targetDegree));
if ((drillStationBlocks.ToPosition(drillStationBlocks.VerticalPistons, depth, 1, drillStationBlocks.HorizontalPiston, DRILL_RADII[currentCircle], 1, drillStationBlocks.Rotor, targetDegree, ROTOR_RPM)))
{
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("Flattening: currentCircle {0} end reached", currentCircle));
//when it is not there
currentCircle++;
}
}
else
{
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Flattening DONE");
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Moving to start Position");
//move to the start position (pistons at 1m/s rotor at 1 rpm)
if (drillStationBlocks.ToPosition(drillStationBlocks.VerticalPistons, 0, 1, drillStationBlocks.HorizontalPiston, 0, 1, drillStationBlocks.Rotor, 0, 1))
{
if (depth != TARGET_DEPTH)
{
context.State = new DeepeningState();
}
else
{
context.State = new DoneState();
}
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Setting state on context: " + context.State.GetType().Name);
}
}
}
public string Status(Context context)
{
BlockUtils.AppendDebugOut((context as DrillStation).DrillStationBlocks.DebugPanels, "retrieving status");
if (currentCircle == DRILL_RADII.Count)
{
return "Flattening DONE";
}
else
{
return string.Format("Flattening [{0}/{1}] ({2:0.##}m)", currentCircle + 1, DRILL_RADII.Count, BlockUtils.GetPistonsTotalPosition((context as DrillStation).DrillStationBlocks.VerticalPistons));
}
}
public void LoadFromStateDTO(StateDTO stateDTO)
{
this.currentCircle = stateDTO.Circle;
this.depth = stateDTO.Depth;
}
}
class ContainerFullState : State
{
private int circle;
private float depth;
public ContainerFullState(int circle, float depth)
{
this.circle = circle;
this.depth = depth;
}
public StateDTO GetStateDTO(Context context)
{
BlockUtils.AppendDebugOut((context as DrillStation).DrillStationBlocks.DebugPanels, string.Format("Building State DTO with params {0}, {1}, {2}", typeof(ContainerFullState).Name, circle, depth));
return new StateDTO(typeof(ContainerFullState).Name, circle, depth);
}
public void Handle(Context context)
{
var drillStationBlocks = (context as DrillStation).DrillStationBlocks;
//move to the start position (pistons at 1m/s rotor at 1 rpm)
if (drillStationBlocks.ToPosition(drillStationBlocks.VerticalPistons, 0, 1, drillStationBlocks.HorizontalPiston, 0, 1, drillStationBlocks.Rotor, 0, 1))
{
//if the containers are not emptied to below lower threshold turn off the blocks otherwise turn them on again and proceed wit deepeningState
if (BlockUtils.ContainersCapacityReached(drillStationBlocks.CargoContainers, CONTAINER_LOWER_THRESHOLD))
{
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Container not emptied, turning off the drilling blocks");
//turn off all drills
drillStationBlocks.Drills.ForEach(block =>
{
block.GetActionWithName("OnOff_Off").Apply(block);
});
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned of all drills");
//turn off all hPistons
drillStationBlocks.HorizontalPiston.ForEach(block =>
{
block.GetActionWithName("OnOff_Off").Apply(block);
});
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned off all horizontal pistons");
//turn off the rotor
drillStationBlocks.Rotor.GetActionWithName("OnOff_Off").Apply(drillStationBlocks.Rotor);
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned off the rotor");
//turn off all vPistons
drillStationBlocks.VerticalPistons.ForEach(block =>
{
block.GetActionWithName("OnOff_Off").Apply(block);
});
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned of all vertical pistons");
}
else
{
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Container was emptied, turning on the blocks");
//turn on all blocks, just for good measure
drillStationBlocks.TurnOnAllBlocks();
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "returning to deepening State");
context.State = new DeepeningState();
(context.State as DeepeningState).SetCurrentCircle(circle);
(context.State as DeepeningState).SetVerticalOffset(depth);
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Setting state on context: " + context.State.GetType().Name);
}
}
}
public string Status(Context context)
{
BlockUtils.AppendDebugOut((context as DrillStation).DrillStationBlocks.DebugPanels, "retrieving status");
return "Container Full";
}
public void LoadFromStateDTO(StateDTO stateDTO)
{
circle = stateDTO.Circle;
depth = stateDTO.Depth;
}
}
/// <summary>
/// The DrillingState
/// </summary>
class DeepeningState : State
{
private int currentCircle = 0;
private bool depthReached = true;
private float verticalOffset = VERTICAL_OFFSET;
public StateDTO GetStateDTO(Context context)
{
BlockUtils.AppendDebugOut((context as DrillStation).DrillStationBlocks.DebugPanels, string.Format("Building State DTO with params {0}, {1}, {2}", typeof(DeepeningState).Name, currentCircle, depthReached ? verticalOffset : BlockUtils.GetPistonsTotalPosition((context as DrillStation).DrillStationBlocks.VerticalPistons)));
return new StateDTO(typeof(DeepeningState).Name, currentCircle, depthReached ? verticalOffset : BlockUtils.GetPistonsTotalPosition((context as DrillStation).DrillStationBlocks.VerticalPistons));
}
public void SetCurrentCircle(int currentCircle)
{
this.currentCircle = currentCircle;
}
public void SetVerticalOffset(float verticalOffset)
{
this.verticalOffset = verticalOffset;
}
public void LoadFromStateDTO(StateDTO stateDTO)
{
currentCircle = stateDTO.Circle;
//we need to know how much the drills drop per round to build in safety margin
var safetyMargin = 60 * DRILL_DOWN_SPEED / ROTOR_RPM;
verticalOffset = (safetyMargin < stateDTO.Depth) ? stateDTO.Depth - safetyMargin : 0;
}
public void Handle(Context context)
{
var drillStationBlocks = (context as DrillStation).DrillStationBlocks;
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("Deepening: currentCircle {0}", currentCircle));
//if currentCircle < the number of radii the flatten, else move to start, and proceed to next state
if (currentCircle < DRILL_RADII.Count)
{
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("deepening: depth reached {0}", depthReached));
// Check container capacity
if (BlockUtils.ContainersCapacityReached(drillStationBlocks.CargoContainers, CONTAINER_UPPER_THRESHOLD))
{
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Container full, going to ContainerFullState");
context.State = new ContainerFullState(currentCircle, BlockUtils.GetPistonsTotalPosition(drillStationBlocks.VerticalPistons));
}
if (depthReached)
{
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Moving to start Position");
//move to the start position (pistons at 1m/s rotor at 1 rpm)
if (drillStationBlocks.ToPosition(drillStationBlocks.VerticalPistons, verticalOffset, 1, drillStationBlocks.HorizontalPiston, DRILL_RADII[currentCircle], 1, drillStationBlocks.Rotor, 0, 1))
{
depthReached = false;
}
else
{
//if not at start, break excution
return;
}
}
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("deepening: removing rotor limits"));
//unlock rotor
BlockUtils.RemoveRotorLimits(drillStationBlocks.Rotor);
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("deepening: setting rotor to turn"));
//set rotor speed
BlockUtils.setRotorSpeed(drillStationBlocks.Rotor, ROTOR_RPM);
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("deepening: moving pistons to depth {0}", TARGET_DEPTH));
//move the vPistons down until the depth is reached
if (BlockUtils.MovePistonsToPosition(drillStationBlocks.VerticalPistons, TARGET_DEPTH, DRILL_DOWN_SPEED))
{
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("deepening: TARGET DEPTH reached, increasing current circle, setting depth reached true, setting vertical offset to {0}", VERTICAL_OFFSET));
currentCircle++;
verticalOffset = VERTICAL_OFFSET;
depthReached = true;
}
}
else {
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Flattening DONE");
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Moving to start Position");
//move to the start position (pistons at 1m/s rotor at 1 rpm)
if (drillStationBlocks.ToPosition(drillStationBlocks.VerticalPistons, 0, 1, drillStationBlocks.HorizontalPiston, 0, 1, drillStationBlocks.Rotor, 0, 1))
{
//when done proceed to the next state
if (END_FLATTENING)
{
context.State = new FlatteningState(TARGET_DEPTH);
}
else
{
context.State = new DoneState();
}
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Setting state on context: " + context.State.GetType().Name);
}
}
}
public string Status(Context context)
{
BlockUtils.AppendDebugOut((context as DrillStation).DrillStationBlocks.DebugPanels, "retrieving status");
if (currentCircle == DRILL_RADII.Count)
{
return "Drilling DONE";
}
else
{
return string.Format("Drilling [{0}/{1}] ({2:0.##}m/{3:0.##}m)", currentCircle + 1, DRILL_RADII.Count, depthReached ? verticalOffset : BlockUtils.GetPistonsTotalPosition((context as DrillStation).DrillStationBlocks.VerticalPistons), TARGET_DEPTH);
}
}
}
/// <summary>
/// The DoneState
/// </summary>
class DoneState : State
{
public StateDTO GetStateDTO(Context context)
{
BlockUtils.AppendDebugOut((context as DrillStation).DrillStationBlocks.DebugPanels, string.Format("Building State DTO with params {0}, {1}, {2}", typeof(DoneState).Name, -1, -1));
return new StateDTO(typeof(DoneState).Name, -1, -1);
}
public void Handle(Context context)
{
var drillStationBlocks = (context as DrillStation).DrillStationBlocks;
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "Moving to start Position");
//move to the start position (pistons at 1m/s rotor at 1 rpm)
if (!drillStationBlocks.ToPosition(drillStationBlocks.VerticalPistons, 0, 1, drillStationBlocks.HorizontalPiston, 0, 1, drillStationBlocks.Rotor, 0, 1))
return;
//turn off all drills
drillStationBlocks.Drills.ForEach(block =>
{
block.GetActionWithName("OnOff_Off").Apply(block);
});
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned off all drills");
//turn off all hPistons
drillStationBlocks.HorizontalPiston.ForEach(block =>
{
block.GetActionWithName("OnOff_Off").Apply(block);
});
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned off all horizontal pistons");
//turn off the rotor
drillStationBlocks.Rotor.GetActionWithName("OnOff_Off").Apply(drillStationBlocks.Rotor);
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned off the rotor");
//turn off all vPistons
drillStationBlocks.VerticalPistons.ForEach(block =>
{
block.GetActionWithName("OnOff_Off").Apply(block);
});
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned off all vertical psitons");
//if the refineries do not have anything left to refine, turn them off
var allRefineriesDone = true;
drillStationBlocks.Refineries.ForEach(refinery =>
{
var refineryItems = refinery.GetInventory(0).GetItems();
//if there are items in the refinery
if (refineryItems.Count > 0)
{
var stop = true;
refineryItems.ForEach(item =>
{
stop &= item.Amount <= (VRage.MyFixedPoint)0.1f;
allRefineriesDone &= stop;
});
if (stop)
refinery.GetActionWithName("OnOff_Off").Apply(refinery);
}
else
{
refinery.GetActionWithName("OnOff_Off").Apply(refinery);
}
});
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, string.Format("refineries have remaining work: {0}", allRefineriesDone));
//if all refineries are done: clean the remaining input and output, stop timer and shutdown script
if (allRefineriesDone)
{
drillStationBlocks.CleanRefineries(0);
drillStationBlocks.CleanRefineries(1);
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "cleaning refineries input and output inventories");
//timer
drillStationBlocks.Timer.GetActionWithName("OnOff_Off").Apply(drillStationBlocks.Timer);
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned off timer");
//turn off all panels
drillStationBlocks.DebugPanels.ForEach(block =>
{
block.GetActionWithName("OnOff_Off").Apply(block);
});
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned off all panels");
//script
drillStationBlocks.ProgrammableBlock.GetActionWithName("OnOff_Off").Apply(drillStationBlocks.ProgrammableBlock);
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "turned off script");
}
BlockUtils.AppendDebugOut(drillStationBlocks.DebugPanels, "No new state to set, end of cycle reached");
}
public void LoadFromStateDTO(StateDTO stateDTO)
{
return;
}
public string Status(Context context)
{
BlockUtils.AppendDebugOut((context as DrillStation).DrillStationBlocks.DebugPanels, "retrieving status");
return "DONE";
}
}
/// <summary>
/// The 'State' interface
/// </summary>
interface State
{
/// <summary>
/// handle the context in order to move to the next state.
/// </summary>
/// <param name="context"></param>
void Handle(Context context);
/// <summary>
/// retrieves a friendly status message
/// </summary>
/// <param name="context"></param>
string Status(Context context);
/// <summary>
/// gets the stateDTO based on the current variables
/// </summary>
/// <param name="context"></param>
StateDTO GetStateDTO(Context context);
/// <summary>
/// sets the state to a point contained in the DTO
/// </summary>
/// <param name="stateDTO"></param>
void LoadFromStateDTO(StateDTO stateDTO);
}
class StateDTO
{
public string State { get; private set; }
public int Circle { get; private set; }
public float Depth { get; private set; }
public StateDTO(string state, int circle, float depth)
{
State = state;
Circle = circle;
Depth = depth;
}
/// <summary>
/// builds the DTO info from a string value
/// </summary>
/// <param name="persistantStorage"></param>
public StateDTO(string persistantStorage)
{
var keyValues = persistantStorage.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var keyValue in keyValues)
{
var key = keyValue.Split('=')[0];
var value = keyValue.Split('=')[1];
switch (key)
{
case "state":
State = value;
break;
case "circle":
Circle = int.Parse(value);
break;
case "depth":
Depth = float.Parse(value);
break;
}
}
}
/// <summary>
/// formats the DTO to display as a string, also used in persistant storage
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("state={0},circle={1},depth={2}", State, Circle, Depth);
}
/// <summary>
/// returns a build state from the DTO
/// </summary>
/// <returns></returns>
public State BuildState()
{
State targetState;
switch (State)
{
case "FlatteningState":
targetState = new FlatteningState(0);
break;
case "DeepeningState":
targetState = new DeepeningState();
break;
case "DoneState":
targetState = new DoneState();
break;
default:
targetState = new InitState();
break;
}
targetState.LoadFromStateDTO(this);
return targetState;
}
}
abstract class Context
{
private State _state;
// Gets or sets the state
public State State
{
get { return _state; }
set { _state = value; }
}
/// <summary>
///
/// </summary>
public virtual void Request()
{
_state.Handle(this);
}
}
/// <summary>
/// The 'Context' class
/// </summary>
class DrillStation : Context
{
private DrillStationBlocks _drillStationBlocks;
// Constructor
public DrillStation(IMyGridTerminalSystem GridTerminalSystem)
{
//init is the default state
State = new InitState();
//build the station blocks
this._drillStationBlocks = new DrillStationBlocks(GridTerminalSystem);
//store the storage
State.LoadFromStateDTO(new StateDTO(BlockUtils.GetStateFromStateStorageLights(this._drillStationBlocks.StateStorageLights)));
}
// Gets the DrillStationBlocks
public DrillStationBlocks DrillStationBlocks
{
get { return _drillStationBlocks; }
}
public override void Request()
{
//clear the debug on each run
BlockUtils.ClearDebugOut(DrillStationBlocks.DebugPanels);
//handle the current state
base.Request();
//move the refined goods to the cargo container
DrillStationBlocks.CleanRefineries(1);
//output the status to antenna
BlockUtils.SetStatusToAntennas(DrillStationBlocks.Antennas, State.Status(this));
BlockUtils.SetStateToStateStorageLights(DrillStationBlocks.StateStorageLights, State.GetStateDTO(this));
}
}
class DrillStationBlocks
{
public IMyMotorAdvancedStator Rotor { get; set; }
public List<IMyPistonBase> HorizontalPiston { get; set; }
public List<IMyPistonBase> VerticalPistons { get; set; }
public List<IMyShipDrill> Drills { get; set; }
public List<IMyRadioAntenna> Antennas { get; set; }
public List<IMyTextPanel> DebugPanels { get; set; }
public List<IMyRefinery> Refineries { get; set; }
public List<IMyCargoContainer> CargoContainers { get; set; }
public IMyTimerBlock Timer { get; set; }
public IMyProgrammableBlock ProgrammableBlock { get; set; }
public List<IMyInteriorLight> StateStorageLights { get; set; }
public DrillStationBlocks(IMyGridTerminalSystem GridTerminalSystem)
{
StateStorageLights = new List<IMyInteriorLight>();
var interiorLightTempList = new List<IMyTerminalBlock>();
GridTerminalSystem.GetBlocksOfType<IMyInteriorLight>(interiorLightTempList);
interiorLightTempList.ForEach(light =>
{
if (light.CustomName.StartsWith(STORAGE_LIGHT))
{
StateStorageLights.Add(light as IMyInteriorLight);
}
});
Rotor = GridTerminalSystem.GetBlockWithName(ROTOR_NAME) as IMyMotorAdvancedStator;
Timer = GridTerminalSystem.GetBlockWithName(TIMER_NAME) as IMyTimerBlock;
ProgrammableBlock = GridTerminalSystem.GetBlockWithName(PROGRAMMABLEBLOCK_NAME) as IMyProgrammableBlock;
//HorizontalPiston
HorizontalPiston = new List<IMyPistonBase>();
var hPistonTempList = new List<IMyTerminalBlock>();
GridTerminalSystem.GetBlocksOfType<IMyPistonBase>(hPistonTempList);
hPistonTempList.ForEach(vPiston =>
{
if (vPiston.CustomName.Contains(H_PISTON_NAME))
{
HorizontalPiston.Add(vPiston as IMyPistonBase);
}
});
//VerticalPistons
VerticalPistons = new List<IMyPistonBase>();
var vPistonTempList = new List<IMyTerminalBlock>();
GridTerminalSystem.GetBlocksOfType<IMyPistonBase>(vPistonTempList);
vPistonTempList.ForEach(vPiston =>
{
if (vPiston.CustomName.Contains(V_PISTON_NAME))
{
VerticalPistons.Add(vPiston as IMyPistonBase);
}
});
//Drills
Drills = new List<IMyShipDrill>();
var drillTempList = new List<IMyTerminalBlock>();
GridTerminalSystem.GetBlocksOfType<IMyShipDrill>(drillTempList);
drillTempList.ForEach(drill => Drills.Add(drill as IMyShipDrill));
//Antennas
Antennas = new List<IMyRadioAntenna>();
var antennaTempList = new List<IMyTerminalBlock>();
GridTerminalSystem.GetBlocksOfType<IMyRadioAntenna>(antennaTempList);
antennaTempList.ForEach(antenna => Antennas.Add(antenna as IMyRadioAntenna));
//DebugPanels
DebugPanels = new List<IMyTextPanel>();
var debugPanelTempList = new List<IMyTerminalBlock>();
GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(debugPanelTempList);
debugPanelTempList.ForEach(debugPanel => DebugPanels.Add(debugPanel as IMyTextPanel));
//Refineries
Refineries = new List<IMyRefinery>();
var refineryTempList = new List<IMyTerminalBlock>();
GridTerminalSystem.GetBlocksOfType<IMyRefinery>(refineryTempList);
refineryTempList.ForEach(refinery => Refineries.Add(refinery as IMyRefinery));
//CargoContainers
CargoContainers = new List<IMyCargoContainer>();
var containerTempList = new List<IMyTerminalBlock>();
GridTerminalSystem.GetBlocksOfType<IMyCargoContainer>(containerTempList);
containerTempList.ForEach(container => CargoContainers.Add(container as IMyCargoContainer));
}
public bool ToPosition(List<IMyPistonBase> pistons1, float pistons1position, float speed1, List<IMyPistonBase> pistons2, float pistons2position, float speed2, IMyMotorAdvancedStator rotor, float rotorPosition, float rpm)
{
if (DETAILEDDEBUG)
BlockUtils.AppendDebugOut(DebugPanels, string.Format("Moving to position {0}, {1}, {2}", pistons1position, pistons2position, rotorPosition));
if (!BlockUtils.MovePistonsToPosition(pistons1, pistons1position, speed1))
{
if (DETAILEDDEBUG)
BlockUtils.AppendDebugOut(DebugPanels, string.Format("Moving pistons1 to position {0} with speed {1}, return false", pistons1position, speed1));
return false;
}
if (DETAILEDDEBUG)
BlockUtils.AppendDebugOut(DebugPanels, "pistons1 reached position");
if (!BlockUtils.MovePistonsToPosition(pistons2, pistons2position, speed2))
{
if (DETAILEDDEBUG)
BlockUtils.AppendDebugOut(DebugPanels, string.Format("Moving pistons2 to position {0} with speed {1}, return false", pistons2position, speed2));
return false;
}
if (DETAILEDDEBUG)
BlockUtils.AppendDebugOut(DebugPanels, "pistons2 reached position");
if (!BlockUtils.MoveRotorToPosition(rotor, rotorPosition, rpm))
{
if (DETAILEDDEBUG)
BlockUtils.AppendDebugOut(DebugPanels, string.Format("Moving rotor to position {0} with speed {1}, return false", rotorPosition, rpm));
return false;
}
if (DETAILEDDEBUG)
BlockUtils.AppendDebugOut(DebugPanels, "rotor reached position. All parts reached position. return true");
return true;
}
public void CleanRefineries(int refineryInventoryIndex)
{
BlockUtils.AppendDebugOut(DebugPanels, "Cleaning Refineries");
foreach (var refinery in Refineries)
{
//get the target inventory, 0 is input, 1 is output, else will probably throw error, CBA to check on this
var refineryInventory = refinery.GetInventory(refineryInventoryIndex);
var refineryItems = refineryInventory.GetItems();
IMyInventory targetInventory = null;
//if there are items in the refinery
if (refineryItems.Count > 0)
{
//revers loop as we will remove items
for (int i = refineryItems.Count - 1; i >= 0; i--)
{
//loop the containers to find a target
foreach (var cargoContainer in CargoContainers)
{
//if the container is operational and not full it is a valid target
if ((cargoContainer.IsFunctional || cargoContainer.IsWorking) && !cargoContainer.GetInventory(0).IsFull)
{
targetInventory = cargoContainer.GetInventory(0);
break;
}
}
// transfer items if target is found
if (targetInventory != null)
refineryInventory.TransferItemTo(targetInventory, i);
}
}
}
}
public void TurnOnAllBlocks()
{
//turn on all panels
this.DebugPanels.ForEach(block =>
{
block.GetActionWithName("OnOff_On").Apply(block);
});
BlockUtils.AppendDebugOut(this.DebugPanels, "turned on all panels");
//turn on the timer block and set the interval, also start the timer
this.Timer.GetActionWithName("OnOff_On").Apply(this.Timer);
BlockUtils.AppendDebugOut(this.DebugPanels, string.Format("turned on the timer, set timer to {0} and started it.", TRIGGER_DELAY));
//turn on all antenna
this.Antennas.ForEach(block =>
{
block.GetActionWithName("OnOff_On").Apply(block);
});
BlockUtils.AppendDebugOut(this.DebugPanels, "turned on all antennas");
//turn on all drills
this.Drills.ForEach(block =>
{
block.GetActionWithName("OnOff_On").Apply(block);
});
BlockUtils.AppendDebugOut(this.DebugPanels, "turned on all drills");
//turn on all hPistons
this.HorizontalPiston.ForEach(block =>
{
block.GetActionWithName("OnOff_On").Apply(block);
});
BlockUtils.AppendDebugOut(this.DebugPanels, "turned on all horizontal pistons");
//turn on all refineries
this.Refineries.ForEach(block =>
{
block.GetActionWithName("OnOff_On").Apply(block);
});
BlockUtils.AppendDebugOut(this.DebugPanels, "turned on all horizontal pistons");
//turn on the rotor
this.Rotor.GetActionWithName("OnOff_On").Apply(this.Rotor);
BlockUtils.AppendDebugOut(this.DebugPanels, "turned on the rotor");
//turn on all vPistons
this.VerticalPistons.ForEach(block =>
{
block.GetActionWithName("OnOff_On").Apply(block);
});
BlockUtils.AppendDebugOut(this.DebugPanels, "turned on all vertical pistons");
}
}
class BlockUtils
{
public static void ResetStateStorageLights(List<IMyInteriorLight> stateStorageLights)
{
stateStorageLights.ForEach(light =>
{
if (light.CustomName.StartsWith(STORAGE_LIGHT))
{
light.SetCustomName(STORAGE_LIGHT);
}
});
}
public static void SetStateToStateStorageLights(List<IMyInteriorLight> stateStorageLights, StateDTO state)
{
stateStorageLights.ForEach(light =>
{
if (light.CustomName.StartsWith(STORAGE_LIGHT))
{
StateDTO lightState = new StateDTO(light.CustomName);
if (state.Circle > lightState.Circle)
{
Echo("setting state from " + lightState.ToString() + " to " + state.ToString());
light.SetCustomName(STORAGE_LIGHT + "," + state.ToString());
}
else if (state.Circle == lightState.Circle)
{
if (state.Depth > lightState.Depth)
{
Echo("setting state from " + lightState.ToString() + " to " + state.ToString());
light.SetCustomName(STORAGE_LIGHT + "," + state.ToString());
}
}
}
});
}
public static string GetStateFromStateStorageLights(List<IMyInteriorLight> stateStorageLights)
{
var stateString = "";
if (stateStorageLights.Count > 0)
{
stateString = stateStorageLights.First().CustomName;
}
return stateString;
}
/// <summary>
/// clears the output from the debug panels
/// </summary>
/// <param name="debugPanels">List of IMyTextPanel</param>
public static void ClearDebugOut(List<IMyTextPanel> debugPanels)
{
if (DEBUG)
{
if (debugPanels == null)
return;
debugPanels.ForEach(panel =>
{
panel.WritePublicTitle("DEBUG PANEL");
panel.WritePublicText("");
});
}
}
/// <summary>
/// appends the output to the debug panels
/// </summary>
/// <param name="debugPanels">List of IMyTextPanel</param>
/// <param name="debugOut">the output to append to the debug panels</param>
public static void AppendDebugOut(List<IMyTextPanel> debugPanels, string debugOut)
{
if (DEBUG)
{
if (debugPanels == null)
return;
debugPanels.ForEach(panel =>
{
panel.WritePublicTitle("DEBUG PANEL");
var currentOut = panel.GetPublicText();
panel.WritePublicText(string.Format("{0}\n{1}", currentOut, debugOut));
});
}
}
/// <summary>
/// Sets the state to all antena connected on the GridTerminalSystem
/// </summary>
/// <param name="antennaLists">List of IMyRadioAntenna</param>
/// <param name="status">Current status</param>
public static void SetStatusToAntennas(List<IMyRadioAntenna> antennaLists, string status)
{
if (antennaLists == null)
return;
string antennaName = "{0} - {1}";
antennaLists.ForEach(antenna => antenna.SetCustomName(string.Format(antennaName, DRILL_STATION_NAME, status)));
}
/// <summary>
/// gets the total amount of psiton extention
/// </summary>
/// <param name="pistons">List of IMyPistonBase</param>
/// <returns>the total extention in meter</returns>
public static float GetPistonsTotalPosition(List<IMyPistonBase> pistons)
{
var total = 0f;
pistons.ForEach(piston => total += piston.CurrentPosition);
return total;
}
/// <summary>
/// Evaluates the rotors currect position
/// </summary>
/// <param name="rotor">The rotor to get the position from.</param>
/// <returns>the rotor degree position</returns>
public static float GetRotorPosition(IMyMotorAdvancedStator rotor)
{
var currentposition = "";
System.Text.RegularExpressions.Regex matchthis = new System.Text.RegularExpressions.Regex(@"^.+\n.+\:\s?(-?[0-9]+).*[\s\S]*$");
System.Text.RegularExpressions.Match match = matchthis.Match(rotor.DetailedInfo);
if (match.Success)
{
currentposition = match.Groups[1].Value;
}
else
{
//Echo("The rotor position could not parsed");
throw new FormatException("The rotor position could not parsed");
}
return float.Parse(currentposition);
}
/// <summary>
/// forces the torque of the rotor to what i would call safe automatic operational levels
/// </summary>
public static void ForceRotorsTorque(IMyMotorAdvancedStator rotor)
{
rotor.SetValueFloat("BrakingTorque", 36000000);
rotor.SetValueFloat("Torque", 10000000);
}
/// <summary>
/// Moves the rotor to a certain position
/// </summary>
/// <param name="destinationPosition">the degree value of the postion</param>
/// <param name="rpm">the rotor speed to move with</param>
/// <returns>returns true wen the rotor is in postion, false if it needs to move.</returns>
public static bool MoveRotorToPosition(IMyMotorAdvancedStator rotor, float destinationPosition, float rpm)
{
var currentPosition = GetRotorPosition(rotor);
//set the limits
SetRotorLimits(rotor, destinationPosition, destinationPosition);
//move the rotor to within the limits
if (currentPosition == destinationPosition)
{
setRotorSpeed(rotor, 0f);
rotor.GetActionWithName("OnOff_Off").Apply(rotor); // Stop rotor
return true;
}
else if (currentPosition < destinationPosition)
{
rotor.GetActionWithName("OnOff_On").Apply(rotor); // Start rotor
setRotorSpeed(rotor, rpm);
return false;
}
else if (currentPosition > destinationPosition)
{
rotor.GetActionWithName("OnOff_On").Apply(rotor); // Start rotor
setRotorSpeed(rotor, -rpm);
return false;
}
return false;
}
/// <summary>
/// Sets the rotor limits
/// </summary>
/// <param name="rotor">the rotor to set the limits on</param>
/// <param name="lower">the lower bound</param>
/// <param name="upper">the upper bound</param>
public static void SetRotorLimits(IMyMotorAdvancedStator rotor, float lower, float upper)
{
//warn for fuckery if settin values possible out of bounds when not obviously meant to be that way
if ((lower < -360 && lower != float.NegativeInfinity) || (upper > 360 && upper != float.PositiveInfinity))
{
//Echo("[WARN] Setting Rotor limits is doing wierd stuff around or beyond the 360 degree mark, often SE interprets this as infinity");
}
rotor.SetValueFloat("LowerLimit", lower);
rotor.SetValueFloat("UpperLimit", upper);
}
/// <summary>
/// Sets the rotor speeds
/// </summary>
/// <param name="rotor">the rotor to set the limits on</param>
/// <param name="rpm">the rotor speed in rpm</param>
public static void setRotorSpeed(IMyMotorAdvancedStator rotor, float rpm)
{
rotor.SetValueFloat("Velocity", rpm);
rotor.GetActionWithName("OnOff_On").Apply(rotor); // Start rotor
}
/// <summary>
/// sets the rotor limits to [-infity,infinity]
/// </summary>
/// <param name="rotor">The rotor to set the limits on.</param>
public static void RemoveRotorLimits(IMyMotorAdvancedStator rotor)
{
SetRotorLimits(rotor, float.NegativeInfinity, float.PositiveInfinity);
}
/// <summary>
/// moves the pistons to a certain extension postion, if there are multiple pistons, then the destPosition is split between all the psitons
/// </summary>
/// <param name="pistons"></param>
/// <param name="destPosition"></param>
/// <param name="speed"></param>
/// <returns>true if the pistosn is in position</returns>
public static bool MovePistonsToPosition(List<IMyPistonBase> pistons, float destPosition, float speed)
{
var inPosition = true;
pistons.ForEach(piston =>
{
inPosition &= MovePistonToPosition(piston, destPosition / (float)pistons.Count, speed / (float)pistons.Count);
});
return inPosition;
}
/// <summary>
/// moves the piston to a certain position
/// </summary>
/// <param name="piston"></param>
/// <param name="destinationPosition"></param>
/// <param name="speed"></param>
/// <returns>true if the piston is in position</returns>
public static bool MovePistonToPosition(IMyPistonBase piston, float destinationPosition, float speed)
{
piston.SetValueFloat("LowerLimit", destinationPosition);
piston.SetValueFloat("UpperLimit", destinationPosition);
var currentPosition = piston.CurrentPosition;
//move the rotor to within the limits
if (currentPosition == destinationPosition)
{
// Stop piston
piston.SetValueFloat("Velocity", 0);
return true;
}
else if (currentPosition < destinationPosition)
{
piston.SetValueFloat("Velocity", speed);
return false;
}
else if (currentPosition > destinationPosition)
{
piston.SetValueFloat("Velocity", -speed);
return false;
}
return false;
}
/// <summary>
/// Check container capacity
/// </summary>
/// <param name="cargocontainers"></param>
/// <param name="destPosition"></param>
/// <returns>true if cargo containers have space</returns>
public static bool ContainersCapacityReached(List<IMyCargoContainer> cargoContainers, float threshold)
{
float maxVolume = 0;
float currentVolume = 0;
cargoContainers.ForEach(container =>
{
maxVolume += (float)container.GetInventory(0).MaxVolume;
currentVolume += (float)container.GetInventory(0).CurrentVolume;
});
//Check if we are above or below threshold
bool freeSpace = (currentVolume / (float)maxVolume >= threshold);
return freeSpace;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.Pug
{
internal sealed class ServiceManager : IDisposable
{
private const string ServiceManagerId = "ServiceManager";
private IPropertyOwner _propertyOwner;
private readonly object thelock = new object();
private Dictionary<Type, object> _servicesByType = new Dictionary<Type, object>();
private Dictionary<Guid, object> _servicesByGuid = new Dictionary<Guid, object>();
private Dictionary<Tuple<Type, string>, object> _servicesByContentType = new Dictionary<Tuple<Type, string>, object>();
private ServiceManager(IPropertyOwner propertyOwner)
{
this._propertyOwner = propertyOwner;
this._propertyOwner.Properties.AddProperty(ServiceManagerId, this);
}
/// <summary>
/// Returns service manager attached to a given Property owner
/// </summary>
/// <param name="propertyOwner">Property owner</param>
/// <returns>Service manager instance</returns>
public static ServiceManager FromPropertyOwner(IPropertyOwner propertyOwner)
{
ServiceManager sm = null;
if (propertyOwner.Properties.ContainsProperty(ServiceManagerId))
{
sm = propertyOwner.Properties.GetProperty(ServiceManagerId) as ServiceManager;
return sm;
}
return new ServiceManager(propertyOwner);
}
/// <summary>
/// Retrieves service from a service manager for this Property owner given service type
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <param name="propertyOwner">Property owner</param>
/// <returns>Service instance</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static T GetService<T>(IPropertyOwner propertyOwner) where T : class
{
try
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
return sm.GetService<T>();
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Retrieves service from a service manager for this property owner given service type GUID.
/// Primarily used to retrieve services that implement COM interop and are usable from native code.
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <param name="propertyOwner">Property owner</param>
/// <returns>Service instance</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static object GetService(IPropertyOwner propertyOwner, ref Guid serviceGuid)
{
try
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
return sm.GetService(ref serviceGuid);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Retrieves service from a service manager for this Property owner given service type and content type
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <param name="propertyOwner">Property owner</param>
/// <param name="contentType">Content type</param>
/// <returns>Service instance</returns>
public static T GetService<T>(IPropertyOwner propertyOwner, IContentType contentType) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
if (sm != null)
{
return sm.GetService<T>(contentType);
}
return null;
}
public static ICollection<T> GetAllServices<T>(IPropertyOwner propertyOwner) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
if (sm != null)
{
return sm.GetAllServices<T>();
}
return new List<T>();
}
/// <summary>
/// Add service to a service manager associated with a particular Property owner
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <param name="serviceInstance">Service instance</param>
/// <param name="propertyOwner">Property owner</param>
public static void AddService<T>(T serviceInstance, IPropertyOwner propertyOwner) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.AddService<T>(serviceInstance);
}
/// <summary>
/// Add content type specific service to a service manager associated with a particular Property owner
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <param name="serviceInstance">Service instance</param>
/// <param name="propertyOwner">Property owner</param>
/// <param name="contentType">Content type of the service</param>
public static void AddService<T>(T serviceInstance, IPropertyOwner propertyOwner, IContentType contentType) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.AddService<T>(serviceInstance, contentType);
}
/// <summary>
/// Add service to a service manager associated with a particular property owner.
/// Typically used to store services implemented in native code and identified by
/// the interface GUID.
/// </summary>
/// <typeparam name="serviceGuid">Service GUID</typeparam>
/// <param name="serviceInstance">Service instance</param>
/// <param name="propertyOwner">Property owner</param>
public static void AddService(ref Guid serviceGuid, object serviceInstance, IPropertyOwner propertyOwner)
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.AddService(ref serviceGuid, serviceInstance);
}
public static void RemoveService<T>(IPropertyOwner propertyOwner) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.RemoveService<T>();
}
public static void RemoveService<T>(IPropertyOwner propertyOwner, IContentType contentType) where T : class
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.RemoveService<T>(contentType);
}
public static void RemoveService(IPropertyOwner propertyOwner, ref Guid guidService)
{
var sm = ServiceManager.FromPropertyOwner(propertyOwner);
Debug.Assert(sm != null);
sm.RemoveService(ref guidService);
}
private T GetService<T>() where T : class
{
lock (this.thelock)
{
object service = null;
if (!this._servicesByType.TryGetValue(typeof(T), out service))
{
// try walk through and cast. Perhaps someone is asking for IFoo
// that is implemented on class Bar but Bar was added as Bar, not as IFoo
foreach (var kvp in this._servicesByType)
{
service = kvp.Value as T;
if (service != null)
{
break;
}
}
}
return service as T;
}
}
private T GetService<T>(IContentType contentType) where T : class
{
lock (this.thelock)
{
object service = null;
this._servicesByContentType.TryGetValue(Tuple.Create(typeof(T), contentType.TypeName), out service);
if (service != null)
{
return service as T;
}
// Try walking through and cast. Perhaps someone is asking for IFoo
// that is implemented on class Bar but Bar was added as Bar, not as IFoo
foreach (var kvp in this._servicesByContentType)
{
if (StringComparer.OrdinalIgnoreCase.Equals(kvp.Key.Item2, contentType.TypeName))
{
service = kvp.Value as T;
if (service != null)
{
return service as T;
}
}
}
// iterate through base types since Razor, PHP and ASP.NET content type derive from HTML
foreach (var ct in contentType.BaseTypes)
{
service = GetService<T>(ct);
if (service != null)
{
break;
}
}
return service as T;
}
}
private object GetService(ref Guid serviceGuid)
{
lock (this.thelock)
{
foreach (var kvp in this._servicesByGuid)
{
if (serviceGuid.Equals(kvp.Key))
{
return kvp.Value;
}
}
foreach (var kvp in this._servicesByType)
{
if (serviceGuid.Equals(kvp.Value.GetType().GUID))
{
return kvp.Value;
}
}
return null;
}
}
private ICollection<T> GetAllServices<T>() where T : class
{
var list = new List<T>();
lock (this.thelock)
{
foreach (var kvp in this._servicesByType)
{
var service = kvp.Value as T;
if (service != null)
{
list.Add(service);
}
}
}
return list;
}
private void AddService<T>(T serviceInstance) where T : class
{
lock (this.thelock)
{
if (GetService<T>() == null)
{
this._servicesByType.Add(typeof(T), serviceInstance);
}
}
}
private void AddService<T>(T serviceInstance, IContentType contentType) where T : class
{
lock (this.thelock)
{
if (GetService<T>(contentType) == null)
{
this._servicesByContentType.Add(Tuple.Create(typeof(T), contentType.TypeName), serviceInstance);
}
}
}
private void AddService(ref Guid serviceGuid, object serviceInstance)
{
lock (this.thelock)
{
if (GetService(ref serviceGuid) == null)
{
this._servicesByGuid.Add(serviceGuid, serviceInstance);
}
}
}
private void RemoveService<T>() where T : class
{
this._servicesByType.Remove(typeof(T));
}
private void RemoveService<T>(IContentType contentType) where T : class
{
lock (this.thelock)
{
this._servicesByContentType.Remove(Tuple.Create(typeof(T), contentType.TypeName));
}
}
private void RemoveService(ref Guid guidService)
{
this._servicesByGuid.Remove(guidService);
}
public void Dispose()
{
if (this._propertyOwner != null)
{
this._propertyOwner.Properties.RemoveProperty(ServiceManagerId);
this._servicesByGuid.Clear();
this._servicesByType.Clear();
this._servicesByContentType.Clear();
this._propertyOwner = null;
}
}
}
}
| |
// 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.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
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>
/// LoadBalancerNetworkInterfacesOperations operations.
/// </summary>
internal partial class LoadBalancerNetworkInterfacesOperations : IServiceOperations<NetworkManagementClient>, ILoadBalancerNetworkInterfacesOperations
{
/// <summary>
/// Initializes a new instance of the LoadBalancerNetworkInterfacesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LoadBalancerNetworkInterfacesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Gets associated load balancer network interfaces.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/networkInterfaces").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NetworkInterface>>();
_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<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets associated load balancer network interfaces.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NetworkInterface>>();
_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<Page<NetworkInterface>>(_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 Xunit;
public static class ActivatorTests
{
[Fact]
public static void TestCreateInstance()
{
// Passing null args is equivalent to an empty array of args.
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), null));
Assert.Equal(1, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { }));
Assert.Equal(1, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { 42 }));
Assert.Equal(2, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { "Hello" }));
Assert.Equal(3, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { 5.1, "Hello" }));
Assert.Equal(4, c.I);
Activator.CreateInstance(typeof(StructTypeWithoutReflectionMetadata));
}
[Fact]
public static void TestCreateInstance_ConstructorWithPrimitive_PerformsPrimitiveWidening()
{
// Primitive widening is allowed by the binder, but not by Dynamic.DelegateInvoke().
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { (short)-2 }));
Assert.Equal(2, c.I);
}
[Fact]
public static void TestCreateInstance_ConstructorWithParamsParameter()
{
// C# params arguments are honored by Activator.CreateInstance()
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs() }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs(), "P1" }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs(), "P1", "P2" }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs() }));
Assert.Equal(6, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), "P1" }));
Assert.Equal(6, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), "P1", "P2" }));
Assert.Equal(6, c.I);
}
[Fact]
public static void TestCreateInstance_Invalid()
{
Assert.Throws<ArgumentNullException>("type", () => Activator.CreateInstance(null)); // Type is null
Assert.Throws<ArgumentNullException>("type", () => Activator.CreateInstance(null, new object[0])); // Type is null
Assert.Throws<AmbiguousMatchException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { null }));
// C# designated optional parameters are not optional as far as Activator.CreateInstance() is concerned.
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { 5.1 }));
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { 5.1, Type.Missing }));
// Invalid params args
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), 5, 6 }));
// Primitive widening not supported for "params" arguments.
//
// (This is probably an accidental behavior on the desktop as the default binder specifically checks to see if the params arguments are widenable to the
// params array element type and gives it the go-ahead if it is. Unfortunately, the binder then bollixes itself by using Array.Copy() to copy
// the params arguments. Since Array.Copy() doesn't tolerate this sort of type mismatch, it throws an InvalidCastException which bubbles out
// out of Activator.CreateInstance. Accidental or not, we'll inherit that behavior on .NET Native.)
Assert.Throws<InvalidCastException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { new VarIntArgs(), 1, (short)2 }));
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<TypeWithoutDefaultCtor>()); // Type has no default constructor
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance<TypeWithDefaultCtorThatThrows>()); // Type has a default constructor throws an exception
}
[Fact]
public static void TestCreateInstance_Generic()
{
Choice1 c = Activator.CreateInstance<Choice1>();
Assert.Equal(1, c.I);
Activator.CreateInstance<DateTime>();
Activator.CreateInstance<StructTypeWithoutReflectionMetadata>();
}
[Fact]
public static void TestCreateInstance_Generic_Invalid()
{
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<int[]>()); // Cannot create array type
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<TypeWithoutDefaultCtor>()); // Type has no default constructor
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance<TypeWithDefaultCtorThatThrows>()); // Type has a default constructor that throws
}
class PrivateType
{
public PrivateType() { }
}
class PrivateTypeWithDefaultCtor
{
private PrivateTypeWithDefaultCtor() { }
}
class PrivateTypeWithoutDefaultCtor
{
private PrivateTypeWithoutDefaultCtor(int x) { }
}
class PrivateTypeWithDefaultCtorThatThrows
{
public PrivateTypeWithDefaultCtorThatThrows() { throw new Exception(); }
}
[Fact]
public static void TestCreateInstance_Type_Bool()
{
Assert.Equal(typeof(PrivateType), Activator.CreateInstance(typeof(PrivateType), true).GetType());
Assert.Equal(typeof(PrivateType), Activator.CreateInstance(typeof(PrivateType), false).GetType());
Assert.Equal(typeof(PrivateTypeWithDefaultCtor), Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtor), true).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtor), false).GetType());
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtorThatThrows), true).GetType());
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtorThatThrows), false).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithoutDefaultCtor), true).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithoutDefaultCtor), false).GetType());
}
public class Choice1 : Attribute
{
public Choice1()
{
I = 1;
}
public Choice1(int i)
{
I = 2;
}
public Choice1(string s)
{
I = 3;
}
public Choice1(double d, string optionalS = "Hey")
{
I = 4;
}
public Choice1(VarArgs varArgs, params object[] parameters)
{
I = 5;
}
public Choice1(VarStringArgs varArgs, params string[] parameters)
{
I = 6;
}
public Choice1(VarIntArgs varArgs, params int[] parameters)
{
I = 7;
}
public int I;
}
public class VarArgs
{
}
public class VarStringArgs
{
}
public class VarIntArgs
{
}
public struct StructTypeWithoutReflectionMetadata
{
}
public class TypeWithoutDefaultCtor
{
private TypeWithoutDefaultCtor(int x) { }
}
public class TypeWithDefaultCtorThatThrows
{
public TypeWithDefaultCtorThatThrows() { throw new Exception(); }
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(EasyJoystick))]
public class GUIEasyJoystickInspector : Editor{
GUIStyle paddingStyle1;
public GUIEasyJoystickInspector(){
paddingStyle1 = new GUIStyle();
paddingStyle1.padding = new RectOffset(15,0,0,0);
}
void OnEnable(){
EasyJoystick t = (EasyJoystick)target;
if (t.areaTexture==null){
t.areaTexture = (Texture)Resources.Load("RadialJoy_Area");
EditorUtility.SetDirty(t);
}
if (t.touchTexture==null){
t.touchTexture = (Texture)Resources.Load("RadialJoy_Touch");
EditorUtility.SetDirty(t);
}
if (t.deadTexture==null){
t.deadTexture = (Texture)Resources.Load("RadialJoy_Dead");
EditorUtility.SetDirty(t);
}
t.showDebugRadius = true;
}
void OnDisable(){
EasyJoystick t = (EasyJoystick)target;
t.showDebugRadius = false;
}
public override void OnInspectorGUI(){
EasyJoystick t = (EasyJoystick)target;
// Joystick Properties
HTGUILayout.FoldOut( ref t.showProperties,"Joystick properties",false);
if (t.showProperties){
EditorGUILayout.BeginVertical(paddingStyle1);
t.name = EditorGUILayout.TextField("Joystick name",t.name);
if (t.enable) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enable = EditorGUILayout.Toggle("Enable joystick",t.enable);
if (t.isActivated) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.isActivated = EditorGUILayout.Toggle("Activated",t.isActivated);
if (t.showDebugRadius) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.showDebugRadius = EditorGUILayout.Toggle("Show debug area",t.showDebugRadius);
GUI.backgroundColor = Color.white;
HTGUILayout.DrawSeparatorLine(paddingStyle1.padding.left);
EditorGUILayout.Separator();
if (t.useFixedUpdate) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.useFixedUpdate = EditorGUILayout.Toggle("Use fixed update",t.useFixedUpdate);
if (t.isUseGuiLayout) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.isUseGuiLayout = EditorGUILayout.Toggle("Use GUI Layout",t.isUseGuiLayout);
GUI.backgroundColor = Color.white;
if (!t.isUseGuiLayout){
EditorGUILayout.HelpBox("This lets you skip the GUI layout phase (Increase GUI performance). It can only be used if you do not use GUI.Window and GUILayout inside of this OnGUI call.",MessageType.Warning);
}
EditorGUILayout.EndVertical();
}
HTGUILayout.FoldOut( ref t.showPosition,"Joystick position & size",false);
if (t.showPosition){
// Dynamic joystick
if (t.DynamicJoystick) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.DynamicJoystick = EditorGUILayout.Toggle("Dynamic joystick",t.DynamicJoystick);
GUI.backgroundColor = Color.white;
if (t.DynamicJoystick){
GUI.backgroundColor = Color.cyan;
t.area = (EasyJoystick.DynamicArea) EditorGUILayout.EnumPopup("Free area",t.area);
GUI.backgroundColor = Color.white;
}
else{
GUI.backgroundColor = Color.cyan;
t.JoyAnchor = (EasyJoystick.JoystickAnchor)EditorGUILayout.EnumPopup("Anchor",t.JoyAnchor);
GUI.backgroundColor = Color.white;
t.JoystickPositionOffset = EditorGUILayout.Vector2Field("Offset",t.JoystickPositionOffset);
}
HTGUILayout.DrawSeparatorLine(paddingStyle1.padding.left);
EditorGUILayout.Separator();
t.ZoneRadius = EditorGUILayout.FloatField("Area radius",t.ZoneRadius);
t.TouchSize = EditorGUILayout.FloatField("Touch radius",t.TouchSize);
if (t.RestrictArea) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.RestrictArea = EditorGUILayout.Toggle(" Restrict to area",t.RestrictArea);
if (t.resetFingerExit) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.resetFingerExit = EditorGUILayout.Toggle(" Reset finger exit",t.resetFingerExit);
GUI.backgroundColor = Color.white;
t.deadZone = EditorGUILayout.FloatField("Dead zone radius",t.deadZone);
}
// Joystick axes properties
HTGUILayout.FoldOut( ref t.showInteraction,"Joystick axes properties & events",false);
if (t.showInteraction){
EditorGUILayout.BeginVertical(paddingStyle1);
// Interaction
GUI.backgroundColor = Color.cyan;
t.Interaction = (EasyJoystick.InteractionType)EditorGUILayout.EnumPopup("Interaction type",t.Interaction);
GUI.backgroundColor = Color.white;
if (t.Interaction == EasyJoystick.InteractionType.EventNotification || t.Interaction == EasyJoystick.InteractionType.DirectAndEvent){
if (t.useBroadcast) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.useBroadcast = EditorGUILayout.Toggle("Broadcast messages",t.useBroadcast);
GUI.backgroundColor = Color.white;
if (t.useBroadcast){
t.receiverGameObject =(GameObject) EditorGUILayout.ObjectField(" Receiver gameobject",t.receiverGameObject,typeof(GameObject),true);
GUI.backgroundColor = Color.cyan;
t.messageMode =(EasyJoystick.Broadcast) EditorGUILayout.EnumPopup(" Sending mode",t.messageMode);
GUI.backgroundColor = Color.white;
}
}
HTGUILayout.DrawSeparatorLine(paddingStyle1.padding.left);
// X axis
GUI.color = new Color(255f/255f,69f/255f,40f/255f);
t.enableXaxis = EditorGUILayout.BeginToggleGroup("Enable X axis",t.enableXaxis);
GUI.color = Color.white;
if (t.enableXaxis){
EditorGUILayout.BeginVertical(paddingStyle1);
t.speed.x = EditorGUILayout.FloatField("Speed",t.speed.x);
if (t.inverseXAxis) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.inverseXAxis = EditorGUILayout.Toggle("Inverse axis",t.inverseXAxis);
GUI.backgroundColor = Color.white;
EditorGUILayout.Separator();
if (t.Interaction == EasyJoystick.InteractionType.Direct || t.Interaction == EasyJoystick.InteractionType.DirectAndEvent){
t.XAxisTransform = (Transform)EditorGUILayout.ObjectField("Joystick X to",t.XAxisTransform,typeof(Transform),true);
if ( t.XAxisTransform!=null){
// characterCollider
if (t.XAxisTransform.GetComponent<CharacterController>() && (t.XTI==EasyJoystick.PropertiesInfluenced.Translate || t.XTI==EasyJoystick.PropertiesInfluenced.TranslateLocal)){
EditorGUILayout.HelpBox("CharacterController detected",MessageType.Info);
t.xAxisGravity = EditorGUILayout.FloatField("Gravity",t.xAxisGravity);
}
else{
t.xAxisGravity=0;
}
GUI.backgroundColor = Color.cyan;
t.XTI = (EasyJoystick.PropertiesInfluenced)EditorGUILayout.EnumPopup("Influenced",t.XTI);
GUI.backgroundColor = Color.white;
switch( t.xAI){
case EasyJoystick.AxisInfluenced.X:
GUI.color = new Color(255f/255f,69f/255f,40f/255f);
break;
case EasyJoystick.AxisInfluenced.Y:
GUI.color = Color.green;
break;
case EasyJoystick.AxisInfluenced.Z:
GUI.color = new Color(63f/255f,131f/255f,245f/255f);
break;
}
GUI.backgroundColor = Color.cyan;
t.xAI = (EasyJoystick.AxisInfluenced)EditorGUILayout.EnumPopup("Axis influenced",t.xAI);
GUI.backgroundColor = Color.white;
GUI.color = Color.white;
EditorGUILayout.Separator();
if (t.XTI == EasyJoystick.PropertiesInfluenced.RotateLocal){
// auto stab
if (t.enableXAutoStab) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableXAutoStab = EditorGUILayout.Toggle( "AutoStab",t.enableXAutoStab);
GUI.backgroundColor = Color.white;
if (t.enableXAutoStab){
EditorGUILayout.BeginVertical(paddingStyle1);
t.ThresholdX = EditorGUILayout.FloatField("Threshold ", t.ThresholdX);
t.StabSpeedX = EditorGUILayout.FloatField("Speed",t.StabSpeedX);
EditorGUILayout.EndVertical();
}
EditorGUILayout.Separator();
// Clamp
if (t.enableXClamp) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableXClamp = EditorGUILayout.Toggle("Clamp rotation",t.enableXClamp);
GUI.backgroundColor = Color.white;
if (t.enableXClamp){
EditorGUILayout.BeginVertical(paddingStyle1);
t.clampXMax = EditorGUILayout.FloatField("Max angle value",t.clampXMax);
t.clampXMin = EditorGUILayout.FloatField("Min angle value",t.clampXMin);
EditorGUILayout.EndVertical();
}
}
}
}
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndToggleGroup();
HTGUILayout.DrawSeparatorLine(paddingStyle1.padding.left);
// Y axis
GUI.color = Color.green;
t.enableYaxis = EditorGUILayout.BeginToggleGroup("Enable Y axis",t.enableYaxis);
GUI.color = Color.white;
if (t.enableYaxis){
EditorGUILayout.BeginVertical(paddingStyle1);
t.speed.y = EditorGUILayout.FloatField("Speed",t.speed.y);
if (t.inverseYAxis) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.inverseYAxis = EditorGUILayout.Toggle("Inverse axis",t.inverseYAxis);
GUI.backgroundColor = Color.white;
EditorGUILayout.Separator();
if (t.Interaction == EasyJoystick.InteractionType.Direct || t.Interaction == EasyJoystick.InteractionType.DirectAndEvent){
t.YAxisTransform = (Transform)EditorGUILayout.ObjectField("Joystick Y to",t.YAxisTransform,typeof(Transform),true);
if ( t.YAxisTransform!=null){
// characterCollider
if (t.YAxisTransform.GetComponent<CharacterController>() && (t.YTI==EasyJoystick.PropertiesInfluenced.Translate || t.YTI==EasyJoystick.PropertiesInfluenced.TranslateLocal)){
EditorGUILayout.HelpBox("CharacterController detected",MessageType.Info);
t.yAxisGravity = EditorGUILayout.FloatField("Gravity",t.yAxisGravity);
}
else{
t.yAxisGravity=0;
}
GUI.backgroundColor = Color.cyan;
t.YTI = (EasyJoystick.PropertiesInfluenced)EditorGUILayout.EnumPopup("Influenced",t.YTI);
GUI.backgroundColor = Color.white;
switch( t.yAI){
case EasyJoystick.AxisInfluenced.X:
GUI.color = new Color(255f/255f,69f/255f,40f/255f);
break;
case EasyJoystick.AxisInfluenced.Y:
GUI.color = Color.green;
break;
case EasyJoystick.AxisInfluenced.Z:
GUI.color = new Color(63f/255f,131f/255f,245f/255f);
break;
}
GUI.backgroundColor = Color.cyan;
t.yAI = (EasyJoystick.AxisInfluenced)EditorGUILayout.EnumPopup("Axis influenced",t.yAI);
GUI.backgroundColor = Color.white;
GUI.color = Color.white;
EditorGUILayout.Separator();
if (t.YTI == EasyJoystick.PropertiesInfluenced.RotateLocal){
// auto stab
if (t.enableYAutoStab) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableYAutoStab = EditorGUILayout.Toggle( "AutoStab",t.enableYAutoStab);
GUI.backgroundColor = Color.white;
if (t.enableYAutoStab){
EditorGUILayout.BeginVertical(paddingStyle1);
t.ThresholdY = EditorGUILayout.FloatField("Threshold ", t.ThresholdY);
t.StabSpeedY = EditorGUILayout.FloatField("Speed",t.StabSpeedY);
EditorGUILayout.EndVertical();
}
EditorGUILayout.Separator();
// Clamp
if (t.enableYClamp) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableYClamp = EditorGUILayout.Toggle("Clamp rotation",t.enableYClamp);
GUI.backgroundColor = Color.white;
if (t.enableYClamp){
EditorGUILayout.BeginVertical(paddingStyle1);
t.clampYMax = EditorGUILayout.FloatField("Max angle value",t.clampYMax);
t.clampYMin = EditorGUILayout.FloatField("Min angle value",t.clampYMin);
EditorGUILayout.EndVertical();
}
}
}
}
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndToggleGroup();
HTGUILayout.DrawSeparatorLine(paddingStyle1.padding.left);
EditorGUILayout.Separator();
// Smoothing return
if (t.enableSmoothing) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableSmoothing = EditorGUILayout.BeginToggleGroup("Smoothing return",t.enableSmoothing);
GUI.backgroundColor = Color.white;
if (t.enableSmoothing){
EditorGUILayout.BeginVertical(paddingStyle1);
t.Smoothing = EditorGUILayout.Vector2Field( "Smoothing",t.Smoothing);
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndToggleGroup();
if (t.enableInertia) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableInertia = EditorGUILayout.BeginToggleGroup("Enable inertia",t.enableInertia);
GUI.backgroundColor = Color.white;
if (t.enableInertia){
EditorGUILayout.BeginVertical(paddingStyle1);
t.Inertia = EditorGUILayout.Vector2Field( "Inertia",t.Inertia);
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndToggleGroup();
EditorGUILayout.EndVertical();
}
// Joystick Texture
HTGUILayout.FoldOut(ref t.showAppearance,"Joystick textures",false);
if (t.showAppearance){
EditorGUILayout.BeginVertical(paddingStyle1);
t.guiDepth = EditorGUILayout.IntField("Gui depth",t.guiDepth);
EditorGUILayout.Separator();
if (t.showZone) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.showZone = EditorGUILayout.Toggle("Show area",t.showZone);
GUI.backgroundColor = Color.white;
if (t.showZone){
t.areaColor = EditorGUILayout.ColorField( "Color",t.areaColor);
t.areaTexture = (Texture)EditorGUILayout.ObjectField("Area texture",t.areaTexture,typeof(Texture),true);
}
EditorGUILayout.Separator();
if (t.showTouch) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.showTouch = EditorGUILayout.Toggle("Show touch",t.showTouch);
GUI.backgroundColor = Color.white;
if (t.showTouch){
t.touchColor = EditorGUILayout.ColorField("Color",t.touchColor);
t.touchTexture = (Texture)EditorGUILayout.ObjectField("Area texture",t.touchTexture,typeof(Texture),true);
}
EditorGUILayout.Separator();
if (t.showDeadZone) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.showDeadZone = EditorGUILayout.Toggle("Show dead",t.showDeadZone);
GUI.backgroundColor = Color.white;
if (t.showDeadZone){
t.deadTexture = (Texture)EditorGUILayout.ObjectField("Dead zone texture",t.deadTexture,typeof(Texture),true);
}
EditorGUILayout.EndVertical();
}
// Refresh
if (GUI.changed){
EditorUtility.SetDirty(t);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlDiffView.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Collections;
namespace Microsoft.XmlDiffPatch {
internal enum XmlDiffViewOperation {
Match = 0,
Ignore = 1,
Add = 2,
MoveTo = 3,
Remove = 4,
MoveFrom = 5,
Change = 6,
}
public sealed class XmlDiffView {
XmlDiffViewDocument _doc = null;
Hashtable _descriptors = new Hashtable();
// options
bool _bIgnoreChildOrder = false;
bool _bIgnoreComments = false;
bool _bIgnorePI = false;
bool _bIgnoreWhitespace = false;
bool _bIgnoreNamespaces = false;
bool _bIgnorePrefixes = false;
bool _bIgnoreXmlDecl = false;
bool _bIgnoreDtd = false;
// used when loading
struct LoadState {
public XmlDiffViewNode _curLastChild;
public XmlDiffViewAttribute _curLastAttribute;
public void Reset() {
_curLastChild = null;
_curLastAttribute = null;
}
}
LoadState _loadState;
public XmlDiffView() {
}
public void Load( XmlReader sourceXml, XmlReader diffgram ) {
// load diffgram to DOM
XmlDocument diffgramDoc = new XmlDocument();
diffgramDoc.Load( diffgram );
// process operation descriptors
PreprocessDiffgram( diffgramDoc );
// load document
_doc = new XmlDiffViewDocument();
LoadSourceChildNodes( _doc, sourceXml, false );
// apply diffgram
ApplyDiffgram( diffgramDoc.DocumentElement, _doc );
}
private void PreprocessDiffgram( XmlDocument diffgramDoc ) {
// read xmldiff options
XmlAttribute attr = (XmlAttribute)diffgramDoc.DocumentElement.Attributes.GetNamedItem( "options" );
if ( attr == null )
throw new Exception( "Missing 'options' attribute in the diffgram.");
string optionsAttr = attr.Value;
XmlDiffOptions options = XmlDiff.ParseOptions( optionsAttr );
_bIgnoreChildOrder = ( ( (int)options & (int)(XmlDiffOptions.IgnoreChildOrder) ) > 0 ) ;
_bIgnoreComments = ( ( (int)options & (int)(XmlDiffOptions.IgnoreComments) ) > 0 ) ;
_bIgnorePI = ( ( (int)options & (int)(XmlDiffOptions.IgnorePI) ) > 0 ) ;
_bIgnoreWhitespace = ( ( (int)options & (int)(XmlDiffOptions.IgnoreWhitespace) ) > 0 ) ;
_bIgnoreNamespaces = ( ( (int)options & (int)(XmlDiffOptions.IgnoreNamespaces) ) > 0 ) ;
_bIgnorePrefixes = ( ( (int)options & (int)(XmlDiffOptions.IgnorePrefixes) ) > 0 ) ;
_bIgnoreDtd = ( ( (int)options & (int)(XmlDiffOptions.IgnoreDtd) ) > 0 ) ;
if ( _bIgnoreNamespaces )
_bIgnorePrefixes = true;
// read descriptors
XmlNodeList children = diffgramDoc.DocumentElement.ChildNodes;
IEnumerator e = children.GetEnumerator();
while ( e.MoveNext() ) {
XmlElement desc = e.Current as XmlElement;
if ( desc != null && desc.LocalName == "descriptor" ) {
int opid = int.Parse( desc.GetAttribute( "opid" ) );
OperationDescriptor.Type type;
switch ( desc.GetAttribute( "type" ) ) {
case "move": type = OperationDescriptor.Type.Move; break;
case "prefix change": type = OperationDescriptor.Type.PrefixChange; break;
case "namespace change": type = OperationDescriptor.Type.NamespaceChange; break;
default:
throw new Exception( "Invalid descriptor type." );
}
OperationDescriptor od = new OperationDescriptor( opid, type );
_descriptors[opid] = od;
}
}
}
private void LoadSourceChildNodes( XmlDiffViewParentNode parent, XmlReader reader, bool bEmptyElement ) {
LoadState savedLoadState = _loadState;
_loadState.Reset();
// load attributes
while ( reader.MoveToNextAttribute() )
{
XmlDiffViewAttribute attr;
if ( reader.Prefix == "xmlns" ||
( reader.Prefix == string.Empty && reader.LocalName == "xmlns" ))
{
attr = new XmlDiffViewAttribute( reader.LocalName, reader.Prefix, reader.NamespaceURI, reader.Value );
if ( _bIgnoreNamespaces )
attr._op = XmlDiffViewOperation.Ignore;
}
else
{
string attrValue = _bIgnoreWhitespace ? NormalizeText( reader.Value ) : reader.Value;
attr = new XmlDiffViewAttribute( reader.LocalName, reader.Prefix, reader.NamespaceURI, attrValue );
}
((XmlDiffViewElement)parent).InsertAttributeAfter( attr, _loadState._curLastAttribute );
_loadState._curLastAttribute = attr;
}
// empty element -> return, do not load chilren
if ( bEmptyElement )
goto End;
// load children
while ( reader.Read() ) {
// ignore whitespaces between nodes
if ( reader.NodeType == XmlNodeType.Whitespace )
continue;
XmlDiffViewNode child = null;
switch ( reader.NodeType )
{
case XmlNodeType.Element:
bool bEmptyEl = reader.IsEmptyElement;
XmlDiffViewElement elem = new XmlDiffViewElement( reader.LocalName, reader.Prefix, reader.NamespaceURI, _bIgnorePrefixes );
LoadSourceChildNodes( elem, reader, bEmptyEl );
child = elem;
break;
case XmlNodeType.Attribute:
Debug.Assert( false, "We should never get to this point, attributes should be read at the beginning of thid method." );
break;
case XmlNodeType.Text:
child = new XmlDiffViewCharData(( _bIgnoreWhitespace ) ? NormalizeText( reader.Value ) : reader.Value, XmlNodeType.Text );
break;
case XmlNodeType.CDATA:
child = new XmlDiffViewCharData( reader.Value, XmlNodeType.CDATA );
break;
case XmlNodeType.EntityReference:
child = new XmlDiffViewER( reader.Name );
break;
case XmlNodeType.Comment:
child = new XmlDiffViewCharData( reader.Value, XmlNodeType.Comment );
if ( _bIgnoreComments )
child._op = XmlDiffViewOperation.Ignore;
break;
case XmlNodeType.ProcessingInstruction:
child = new XmlDiffViewPI( reader.Name, reader.Value );
if ( _bIgnorePI )
child._op = XmlDiffViewOperation.Ignore;
break;
case XmlNodeType.SignificantWhitespace:
if( reader.XmlSpace == XmlSpace.Preserve ) {
child = new XmlDiffViewCharData( reader.Value, XmlNodeType.SignificantWhitespace );
if ( _bIgnoreWhitespace )
child._op = XmlDiffViewOperation.Ignore;
}
break;
case XmlNodeType.XmlDeclaration:
child = new XmlDiffViewXmlDeclaration( NormalizeText( reader.Value ));
if ( _bIgnoreXmlDecl )
child._op = XmlDiffViewOperation.Ignore;
break;
case XmlNodeType.EndElement:
goto End;
case XmlNodeType.DocumentType:
child = new XmlDiffViewDocumentType( reader.Name, reader.GetAttribute("PUBLIC"),reader.GetAttribute("SYSTEM"), reader.Value );
if ( _bIgnoreDtd )
child._op = XmlDiffViewOperation.Ignore;
break;
default:
Debug.Assert( false, "Invalid node type" );
break;
}
parent.InsertChildAfter( child, _loadState._curLastChild, true );
_loadState._curLastChild = child;
}
End:
_loadState = savedLoadState;
}
private void ApplyDiffgram( XmlNode diffgramParent, XmlDiffViewParentNode sourceParent ) {
sourceParent.CreateSourceNodesIndex();
XmlDiffViewNode currentPosition = null;
IEnumerator diffgramChildren = diffgramParent.ChildNodes.GetEnumerator();
while ( diffgramChildren.MoveNext() ) {
XmlNode diffgramNode = (XmlNode)diffgramChildren.Current;
if ( diffgramNode.NodeType == XmlNodeType.Comment )
continue;
XmlElement diffgramElement = diffgramChildren.Current as XmlElement;
if ( diffgramElement == null )
throw new Exception( "Invalid node in diffgram." );
if ( diffgramElement.NamespaceURI != XmlDiff.NamespaceUri )
throw new Exception( "Invalid element in diffgram." );
string matchAttr = diffgramElement.GetAttribute( "match" );
XmlDiffPathNodeList matchNodes = null;
if ( matchAttr != string.Empty )
matchNodes = XmlDiffPath.SelectNodes( _doc, sourceParent, matchAttr );
switch ( diffgramElement.LocalName ) {
case "node":
if ( matchNodes.Count != 1 )
throw new Exception( "The 'match' attribute of 'node' element must select a single node." );
matchNodes.MoveNext();
if ( diffgramElement.ChildNodes.Count > 0 )
ApplyDiffgram( diffgramElement, (XmlDiffViewParentNode)matchNodes.Current );
currentPosition = matchNodes.Current;
break;
case "add":
if ( matchAttr != string.Empty ) {
OnAddMatch( diffgramElement, matchNodes, sourceParent, ref currentPosition );
}
else {
string typeAttr = diffgramElement.GetAttribute( "type" );
if ( typeAttr != string.Empty ) {
OnAddNode( diffgramElement, typeAttr, sourceParent, ref currentPosition );
}
else {
OnAddFragment( diffgramElement, sourceParent, ref currentPosition );
}
}
break;
case "remove":
OnRemove( diffgramElement, matchNodes, sourceParent, ref currentPosition );
break;
case "change":
OnChange( diffgramElement, matchNodes, sourceParent, ref currentPosition );
break;
}
}
}
private void OnRemove( XmlElement diffgramElement, XmlDiffPathNodeList matchNodes,
XmlDiffViewParentNode sourceParent, ref XmlDiffViewNode currentPosition ) {
// opid & descriptor
XmlDiffViewOperation op = XmlDiffViewOperation.Remove;
int opid = 0;
OperationDescriptor opDesc = null;
string opidAttr = diffgramElement.GetAttribute( "opid" );
if ( opidAttr != string.Empty ) {
opid = int.Parse( opidAttr );
opDesc = GetDescriptor( opid );
if ( opDesc._type == OperationDescriptor.Type.Move )
op = XmlDiffViewOperation.MoveFrom;
}
// subtree
string subtreeAttr = diffgramElement.GetAttribute( "subtree" );
bool bSubtree = ( subtreeAttr != "no" );
if ( !bSubtree ) {
if ( matchNodes.Count != 1 )
throw new Exception("The 'match' attribute of 'remove' element must select a single node when the 'subtree' attribute is specified." );
// annotate node
matchNodes.MoveNext();
XmlDiffViewNode node = matchNodes.Current;
AnnotateNode( node, op, opid, false );
if ( opid != 0 )
opDesc._nodeList.AddNode( node );
// recurse
ApplyDiffgram( diffgramElement, (XmlDiffViewParentNode)node );
}
else {
// annotate nodes
matchNodes.Reset();
while ( matchNodes.MoveNext() ) {
if ( opid != 0 )
opDesc._nodeList.AddNode( matchNodes.Current );
AnnotateNode( matchNodes.Current, op, opid, true );
}
}
}
private void OnAddMatch( XmlElement diffgramElement, XmlDiffPathNodeList matchNodes, XmlDiffViewParentNode sourceParent,
ref XmlDiffViewNode currentPosition ) {
string opidAttr = diffgramElement.GetAttribute( "opid" );
if ( opidAttr == string.Empty )
throw new Exception( "Missing opid attribute." );
// opid & descriptor
int opid = int.Parse( opidAttr );
OperationDescriptor opDesc = GetDescriptor( opid );
string subtreeAttr = diffgramElement.GetAttribute( "subtree" );
bool bSubtree = ( subtreeAttr != "no" );
// move single node without subtree
if ( !bSubtree ) {
if ( matchNodes.Count != 1 )
throw new Exception("The 'match' attribute of 'add' element must select a single node when the 'subtree' attribute is specified." );
// clone node
matchNodes.MoveNext();
XmlDiffViewNode newNode = matchNodes.Current.Clone( false );
AnnotateNode( newNode, XmlDiffViewOperation.MoveTo, opid, true );
opDesc._nodeList.AddNode( newNode );
// insert in tree
sourceParent.InsertChildAfter( newNode, currentPosition, false );
currentPosition = newNode;
// recurse
ApplyDiffgram( diffgramElement, (XmlDiffViewParentNode)newNode );
}
// move subtree
else {
matchNodes.Reset();
while ( matchNodes.MoveNext() ) {
XmlDiffViewNode newNode = matchNodes.Current.Clone( true );
AnnotateNode( newNode, XmlDiffViewOperation.MoveTo, opid, true );
opDesc._nodeList.AddNode( newNode );
sourceParent.InsertChildAfter( newNode, currentPosition, false );
currentPosition = newNode;
}
}
}
private void OnAddNode( XmlElement diffgramElement, string nodeTypeAttr, XmlDiffViewParentNode sourceParent,
ref XmlDiffViewNode currentPosition ) {
XmlNodeType nodeType = (XmlNodeType) int.Parse( nodeTypeAttr );
string name = diffgramElement.GetAttribute( "name" );
string prefix = diffgramElement.GetAttribute( "prefix" );
string ns = diffgramElement.GetAttribute( "ns" );
string opidAttr = diffgramElement.GetAttribute( "opid" );
int opid = ( opidAttr == string.Empty ) ? 0 : int.Parse( opidAttr );
if ( nodeType == XmlNodeType.Attribute ) {
Debug.Assert( name != string.Empty );
XmlDiffViewAttribute newAttr = new XmlDiffViewAttribute( name, prefix, ns, diffgramElement.InnerText );
newAttr._op = XmlDiffViewOperation.Add;
newAttr._opid = opid;
((XmlDiffViewElement)sourceParent).InsertAttributeAfter( newAttr, null );
}
else {
XmlDiffViewNode newNode = null;
switch ( nodeType ) {
case XmlNodeType.Element:
Debug.Assert( name != string.Empty );
newNode = new XmlDiffViewElement( name, prefix, ns, _bIgnorePrefixes );
ApplyDiffgram( diffgramElement, (XmlDiffViewParentNode)newNode );
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
Debug.Assert( diffgramElement.InnerText != string.Empty );
newNode = new XmlDiffViewCharData( diffgramElement.InnerText, nodeType );
break;
case XmlNodeType.ProcessingInstruction:
Debug.Assert( diffgramElement.InnerText != string.Empty );
Debug.Assert( name != string.Empty );
newNode = new XmlDiffViewPI( name, diffgramElement.InnerText );
break;
case XmlNodeType.EntityReference:
Debug.Assert( name != string.Empty );
newNode = new XmlDiffViewER( name );
break;
case XmlNodeType.XmlDeclaration:
Debug.Assert( diffgramElement.InnerText != string.Empty );
newNode = new XmlDiffViewXmlDeclaration( diffgramElement.InnerText );
break;
case XmlNodeType.DocumentType:
newNode = new XmlDiffViewDocumentType( diffgramElement.GetAttribute( "name" ),
diffgramElement.GetAttribute( "publicId" ),
diffgramElement.GetAttribute( "systemId" ),
diffgramElement.InnerText );
break;
default:
Debug.Assert( false, "Invalid node type." );
break;
}
Debug.Assert( newNode != null );
newNode._op = XmlDiffViewOperation.Add;
newNode._opid = opid;
sourceParent.InsertChildAfter( newNode, currentPosition, false );
currentPosition = newNode;
}
}
private void OnAddFragment( XmlElement diffgramElement, XmlDiffViewParentNode sourceParent, ref XmlDiffViewNode currentPosition ) {
IEnumerator childNodes = diffgramElement.ChildNodes.GetEnumerator();
while ( childNodes.MoveNext() ) {
XmlDiffViewNode newChildNode = ImportNode( (XmlNode)childNodes.Current );
sourceParent.InsertChildAfter( newChildNode, currentPosition, false );
currentPosition = newChildNode;
AnnotateNode( newChildNode, XmlDiffViewOperation.Add, 0, true );
}
}
private XmlDiffViewNode ImportNode( XmlNode node ) {
XmlDiffViewNode newNode = null;
switch ( node.NodeType ) {
case XmlNodeType.Element:
XmlElement el = (XmlElement)node;
XmlDiffViewElement newElement = new XmlDiffViewElement( el.LocalName, el.Prefix, el.NamespaceURI, _bIgnorePrefixes );
// attributes
IEnumerator attributes = node.Attributes.GetEnumerator();
XmlDiffViewAttribute lastNewAttr = null;
while ( attributes.MoveNext() ) {
XmlAttribute at = (XmlAttribute)attributes.Current;
XmlDiffViewAttribute newAttr = new XmlDiffViewAttribute( at.LocalName, at.Prefix, at.NamespaceURI, at.Value );
newElement.InsertAttributeAfter( newAttr, lastNewAttr );
lastNewAttr = newAttr;
}
// children
IEnumerator childNodes = node.ChildNodes.GetEnumerator();
XmlDiffViewNode lastNewChildNode = null;
while ( childNodes.MoveNext() ) {
XmlDiffViewNode newChildNode = ImportNode( (XmlNode)childNodes.Current );
newElement.InsertChildAfter( newChildNode, lastNewChildNode, false );
lastNewChildNode = newChildNode;
}
newNode = newElement;
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
newNode = new XmlDiffViewCharData( node.Value, node.NodeType );
break;
case XmlNodeType.ProcessingInstruction:
newNode = new XmlDiffViewPI( node.Name, node.Value );
break;
case XmlNodeType.EntityReference:
newNode = new XmlDiffViewER( node.Name );
break;
default:
Debug.Assert( false, "Invalid node type." );
break;
}
Debug.Assert( newNode != null );
return newNode;
}
private void OnChange( XmlElement diffgramElement, XmlDiffPathNodeList matchNodes,
XmlDiffViewParentNode sourceParent, ref XmlDiffViewNode currentPosition ) {
Debug.Assert( matchNodes.Count == 1 );
matchNodes.Reset();
matchNodes.MoveNext();
XmlDiffViewNode node = matchNodes.Current;
if ( node._nodeType != XmlNodeType.Attribute )
currentPosition = node;
XmlDiffViewNode.ChangeInfo changeInfo = new XmlDiffViewNode.ChangeInfo();
string name = diffgramElement.HasAttribute("name") ? diffgramElement.GetAttribute( "name" ) : null;
string prefix = diffgramElement.HasAttribute("prefix") ? diffgramElement.GetAttribute( "prefix" ) : null;
string ns = diffgramElement.HasAttribute("ns") ? diffgramElement.GetAttribute( "ns" ) : null;
switch ( node._nodeType ) {
case XmlNodeType.Element:
changeInfo._localName = ( name == null )? ((XmlDiffViewElement)node)._localName : name;
changeInfo._prefix = ( prefix == null ) ? ((XmlDiffViewElement)node)._prefix : prefix;
changeInfo._ns = ( ns == null ) ? ((XmlDiffViewElement)node)._ns : ns;
break;
case XmlNodeType.Attribute:
string value = diffgramElement.InnerText;
if ( name == string.Empty && prefix == string.Empty && value == string.Empty )
return;
changeInfo._localName = ( name == null ) ? ((XmlDiffViewAttribute)node)._localName : name;
changeInfo._prefix = ( prefix == null ) ? ((XmlDiffViewAttribute)node)._prefix : prefix;
changeInfo._ns = ( ns == null ) ? ((XmlDiffViewAttribute)node)._ns : ns;
changeInfo._value = diffgramElement.InnerText;
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
Debug.Assert( diffgramElement.FirstChild != null );
changeInfo._value = diffgramElement.InnerText;
break;
case XmlNodeType.Comment:
Debug.Assert( diffgramElement.FirstChild != null );
Debug.Assert( diffgramElement.FirstChild.NodeType == XmlNodeType.Comment );
changeInfo._value = diffgramElement.FirstChild.Value;
break;
case XmlNodeType.ProcessingInstruction:
if ( name == null ) {
Debug.Assert( diffgramElement.FirstChild != null );
Debug.Assert( diffgramElement.FirstChild.NodeType == XmlNodeType.ProcessingInstruction );
changeInfo._localName = diffgramElement.FirstChild.Name;
changeInfo._value = diffgramElement.FirstChild.Value;
}
else {
changeInfo._localName = name;
changeInfo._value = ((XmlDiffViewPI)node)._value;
}
break;
case XmlNodeType.EntityReference:
Debug.Assert( name != null );
changeInfo._localName = name;
break;
case XmlNodeType.XmlDeclaration:
Debug.Assert( diffgramElement.FirstChild != null );
changeInfo._value = diffgramElement.InnerText;
break;
case XmlNodeType.DocumentType:
changeInfo._localName = ( name == null ) ? ((XmlDiffViewDocumentType)node)._name : name ;
if ( diffgramElement.HasAttribute( "publicId" ) )
changeInfo._prefix = diffgramElement.GetAttribute( "publicId" );
else
changeInfo._prefix = ((XmlDiffViewDocumentType)node)._publicId;
if ( diffgramElement.HasAttribute( "systemId" ) )
changeInfo._ns = diffgramElement.GetAttribute( "systemId" );
else
changeInfo._ns = ((XmlDiffViewDocumentType)node)._systemId;
if ( diffgramElement.FirstChild != null )
changeInfo._value = diffgramElement.InnerText;
else
changeInfo._value = ((XmlDiffViewDocumentType)node)._subset;
break;
default:
Debug.Assert( false, "Invalid node type." );
break;
}
node._changeInfo = changeInfo;
node._op = XmlDiffViewOperation.Change;
string opidAttr = diffgramElement.GetAttribute( "opid" );
if ( opidAttr != string.Empty ) {
node._opid = int.Parse( opidAttr );
}
if ( node._nodeType == XmlNodeType.Element &&
diffgramElement.FirstChild != null ) {
ApplyDiffgram( diffgramElement, (XmlDiffViewParentNode)node );
}
}
private OperationDescriptor GetDescriptor( int opid ) {
OperationDescriptor opDesc = (OperationDescriptor)_descriptors[opid];
if ( opDesc == null )
throw new Exception( "Invalid operation id." );
return opDesc;
}
private void AnnotateNode( XmlDiffViewNode node, XmlDiffViewOperation op, int opid, bool bSubtree ) {
node._op = op;
node._opid = opid;
if ( node._nodeType == XmlNodeType.Element ) {
XmlDiffViewAttribute attr = ((XmlDiffViewElement)node)._attributes;
while ( attr != null ) {
attr._op = op;
attr._opid = opid;
attr = (XmlDiffViewAttribute)attr._nextSibbling;
}
}
if ( bSubtree ) {
XmlDiffViewNode childNode = node.FirstChildNode;
while ( childNode != null ) {
AnnotateNode( childNode, op, opid, true );
childNode = childNode._nextSibbling;
}
}
}
public void GetHtml( TextWriter htmlOutput ) {
_doc.DrawHtml( new XmlTextWriter( htmlOutput ), 10 );
}
// Static methods and data for drawing
static internal readonly string[] HtmlBgColor = {
"background-color: white", // Match = 0,
"background-color: white", // Ignore = 1,
"background-color: yellow", // Add = 2,
"background-color: yellow", // MoveTo = 3,
"background-color: red", // Remove = 4,
"background-color: red", // MoveFrom = 5,
"background-color: lightgreen", // Change = 6,
};
static internal readonly string[] HtmlFgColor = {
"black", // Match = 0,
"#AAAAAA",// Ignore = 1,
"black", // Add = 2,
"blue", // MoveTo = 3,
"black", // Remove = 4,
"blue", // MoveFrom = 5,
"black", // Change = 6,
};
static internal readonly bool[,] HtmlWriteToPane = {
{ true, true }, // Match = 0,
{ true, true }, // Ignore = 1,
{ false, true }, // Add = 2,
{ false, true }, // MoveTo = 3,
{ true, false }, // Remove = 4,
{ true, false }, // MoveFrom = 5,
{ true, true }, // Change = 6,
};
static internal readonly int DeltaIndent = 15;
static private readonly string Nbsp = " " +
" " +
" ";
static private void HtmlSetColor( XmlWriter pane, XmlDiffViewOperation op ) {
pane.WriteStartElement( "font" );
pane.WriteAttributeString( "style", HtmlBgColor[(int)op] );
pane.WriteAttributeString( "color", HtmlFgColor[(int)op] );
}
static private void HtmlResetColor( XmlWriter pane ) {
pane.WriteFullEndElement();
}
static internal void HtmlWriteString( XmlWriter pane, string str ) {
pane.WriteString( str );
}
static internal void HtmlWriteString( XmlWriter pane, XmlDiffViewOperation op, string str ) {
HtmlSetColor( pane, op );
pane.WriteString( str );
HtmlResetColor( pane );
}
static internal void HtmlWriteEmptyString( XmlWriter pane ) {
//pane.WriteCharEntity( (char)255 );
pane.WriteRaw( " " );
}
static internal void HtmlStartCell( XmlWriter writer, int indent ) {
writer.WriteStartElement( "td" );
writer.WriteAttributeString( "style", "padding-left: " + indent.ToString() + "pt;" );
}
static internal void HtmlEndCell( XmlWriter writer ) {
writer.WriteFullEndElement();
}
static internal void HtmlBr( XmlWriter writer ) {
writer.WriteStartElement( "br" );
writer.WriteEndElement();
}
static internal void HtmlStartRow( XmlWriter writer ) {
writer.WriteStartElement( "tr" );
}
static internal void HtmlEndRow( XmlWriter writer ) {
writer.WriteFullEndElement();
}
static internal string GetIndent( int charCount ) {
int nbspCount = charCount * 6;
if ( nbspCount <= Nbsp.Length ) {
return Nbsp.Substring( 0, nbspCount );
}
else {
string indent = string.Empty;
while ( nbspCount > Nbsp.Length ) {
indent += Nbsp;
nbspCount -= Nbsp.Length;
}
indent += Nbsp.Substring( 0, nbspCount );
return indent;
}
}
internal static string NormalizeText( string text )
{
char[] chars = text.ToCharArray();
int i = 0;
int j = 0;
for (;;)
{
while ( j < chars.Length && IsWhitespace( text[j] ) )
j++;
while ( j < chars.Length && !IsWhitespace( text[j] ) )
chars[i++]=chars[j++];
if ( j < chars.Length )
{
chars[i++]=' ';
j++;
}
else
{
if ( j == 0 )
return string.Empty;
if ( IsWhitespace( chars[j-1] ) )
i--;
return new string( chars, 0, i );
}
}
}
internal static bool IsWhitespace( char c )
{
return ( c == ' ' ||
c == '\t' ||
c == '\n' ||
c == '\r' );
}
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.
using System;
using System.CodeDom;
using System.Collections;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
namespace InternalHelper.Tests.Patterns
{
using InternalHelper;
using InternalHelper.Tests;
using InternalHelper.Enumerations;
using Microsoft.Test.UIAutomation;
using Microsoft.Test.UIAutomation.Core;
using Microsoft.Test.UIAutomation.TestManager;
using Microsoft.Test.UIAutomation.Interfaces;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
public class ScrollItemPatternWrapper : PatternObject
{
#region Variables
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
ScrollItemPattern _pattern;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
internal ScrollPattern _scrollPattern;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
internal AutomationElement _container;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
internal const double _HUNDRED = 100D;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
internal const double _ZERO = 0D;
#endregion Variables
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
internal ScrollItemPatternWrapper(AutomationElement element, string testSuite, TestPriorities priority, TypeOfControl typeOfControl, TypeOfPattern typeOfPattern, string dirResults, bool testEvents, IApplicationCommands commands)
:
base(element, testSuite, priority, typeOfControl, typeOfPattern, dirResults, testEvents, commands)
{
Comment("Creating ScrollItemTests");
_pattern = (ScrollItemPattern)GetPattern(m_le, m_useCurrent, ScrollItemPattern.Pattern);
if (_pattern == null)
ThrowMe(CheckType.IncorrectElementConfiguration, Helpers.PatternNotSupported + ": ScrollItemPattern");
// Find the ScrollPattern
_container = m_le;
while (_container != null && !(bool)_container.GetCurrentPropertyValue(AutomationElement.IsScrollPatternAvailableProperty))
_container = TreeWalker.ControlViewWalker.GetParent(_container);
// Check to see if we actual found the container of the scrollitem
if (_container == null)
ThrowMe(CheckType.IncorrectElementConfiguration, "Element does not have a container with ScrollPattern");
Comment("Found scroll container: " + Library.GetUISpyLook(_container));
_scrollPattern = (ScrollPattern)_container.GetCurrentPattern(ScrollPattern.Pattern) as ScrollPattern;
}
#region Properties
#endregion Properties
#region Methods
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
internal void pattern_ScrollIntoView(Type expectedException, CheckType checkType)
{
string call = "ScrollIntoView()";
try
{
Comment("Before " + call + ", BoundingRectagle = '" + m_le.Current.BoundingRectangle + "'");
_pattern.ScrollIntoView();
Comment("After " + call + ", BoundingRectagle = '" + m_le.Current.BoundingRectangle + "'");
}
catch (Exception actualException)
{
if (Library.IsCriticalException(actualException))
throw;
TestException(expectedException, actualException, call, checkType);
return;
}
TestNoException(expectedException, call, checkType);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
internal void helper_SetScrollPercent(double horizontalPercent, double verticalPercent, Type expectedException, CheckType checkType)
{
string call = "SetScrollPercent(" + horizontalPercent + ", " + verticalPercent + ")";
string erroStr = expectedException == null ? "none" : expectedException.ToString();
try
{
Comment("Before " + call + " HorizontalScrollPercent = " + _scrollPattern.Current.HorizontalScrollPercent + ", VerticalScrollPercent = '" + _scrollPattern.Current.VerticalScrollPercent + "'");
// We really don't care if control can scroll to where we can based on the
// scrollability, just do something as much as we can and exit gracefully
if ((bool)_container.GetCurrentPropertyValue(ScrollPattern.HorizontallyScrollableProperty) && (bool)_container.GetCurrentPropertyValue(ScrollPattern.VerticallyScrollableProperty))
_scrollPattern.SetScrollPercent(horizontalPercent, verticalPercent);
else if ((bool)_container.GetCurrentPropertyValue(ScrollPattern.HorizontallyScrollableProperty) && !(bool)_container.GetCurrentPropertyValue(ScrollPattern.VerticallyScrollableProperty))
_scrollPattern.SetScrollPercent(horizontalPercent, ScrollPattern.NoScroll);
else if (!(bool)_container.GetCurrentPropertyValue(ScrollPattern.HorizontallyScrollableProperty) && (bool)_container.GetCurrentPropertyValue(ScrollPattern.VerticallyScrollableProperty))
_scrollPattern.SetScrollPercent(ScrollPattern.NoScroll, verticalPercent);
Thread.Sleep(1);
Comment("After " + call + " HorizontalScrollPercent = " + _scrollPattern.Current.HorizontalScrollPercent + ", VerticalScrollPercent = '" + _scrollPattern.Current.VerticalScrollPercent + "'");
}
catch (Exception actualException)
{
if (Library.IsCriticalException(actualException))
throw;
TestException(expectedException, actualException, call, checkType);
return;
}
TestNoException(expectedException, call, checkType);
}
#endregion Methods
}
}
namespace Microsoft.Test.UIAutomation.Tests.Patterns
{
using InternalHelper;
using InternalHelper.Tests;
using InternalHelper.Tests.Patterns;
using InternalHelper.Enumerations;
using Microsoft.Test.UIAutomation;
using Microsoft.Test.UIAutomation.Core;
using Microsoft.Test.UIAutomation.TestManager;
using Microsoft.Test.UIAutomation.Interfaces;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
public sealed class ScrollItemTests : ScrollItemPatternWrapper
{
#region Member variables
/// -------------------------------------------------------------------
/// <summary>
/// Used to identify the assembly name
/// </summary>
/// -------------------------------------------------------------------
const string THIS = "ScrollItemTests";
/// <summary></summary>
public const string TestSuite = NAMESPACE + "." + THIS;
/// <summary>Defines which UIAutomation Pattern this tests</summary>
public static readonly string TestWhichPattern = Automation.PatternName(ScrollItemPattern.Pattern);
#endregion Member variables
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public ScrollItemTests(AutomationElement element, TestPriorities priority, string dirResults, bool testEvents, TypeOfControl typeOfControl, IApplicationCommands commands)
:
base(element, TestSuite, priority, typeOfControl, TypeOfPattern.ScrollItem, dirResults, testEvents, commands)
{
}
#region Tests
/// -------------------------------------------------------------------
///<summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ScrollIntoView.1",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Generic,
Description = new string[]
{
"Precondition: Element has a parent contantainer",
"Precondition: Parent's IsOffScreen == false",
"Verification: Call ScrollIntoView"
})]
public void TestScrollItemBVT1(TestCaseAttribute testCase)
{
this.HeaderComment(testCase);
// "Precondition: Element has a parent contantainer",
TSC_VerifyProperty(TreeWalker.ControlViewWalker.GetParent(m_le), null, false, "Parent", CheckType.IncorrectElementConfiguration);
// "Precondition: Parent's IsOffScreen == false",
TSC_VerifyPropertyEqual(TreeWalker.ControlViewWalker.GetParent(m_le).Current.IsOffscreen, false, AutomationElement.IsOffscreenProperty, CheckType.IncorrectElementConfiguration);
// "Verification: Call ScrollIntoView"
pattern_ScrollIntoView(null, CheckType.Verification);
m_TestStep++;
}
/// -------------------------------------------------------------------
///<summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ScrollIntoView.2",
Priority = TestPriorities.Pri1,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Generic,
Description = new string[]
{
"Verification: Verify that the elements container is visible",
"Step: Scroll to 0, 0",
"Step: Verify element still supports ScrollItem pattern",
"Step: Call ScrollIntoView()",
"Verification: The the element is within the view port of the parent"
})]
public void TestScrollItem1(TestCaseAttribute testCase)
{
this.HeaderComment(testCase);
TestDriverScrollIntoView1(_ZERO, _ZERO);
}
/// -------------------------------------------------------------------
///<summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ScrollIntoView.3",
Priority = TestPriorities.Pri1,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Generic,
Description = new string[]
{
"Verification: Verify that the elements container is visible",
"Step: Scroll to 0, 100",
"Step: Verify element still supports ScrollItem pattern",
"Step: Call ScrollIntoView()",
"Verification: The the element is within the view port of the parent"
})]
public void TestScrollItem2(TestCaseAttribute testCase)
{
this.HeaderComment(testCase);
TestDriverScrollIntoView1(_ZERO, _HUNDRED);
}
/// -------------------------------------------------------------------
///<summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ScrollIntoView.4",
Priority = TestPriorities.Pri1,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Generic,
Description = new string[]
{
"Verification: Verify that the elements container is visible",
"Step: Scroll to 100, 0",
"Step: Verify element still supports ScrollItem pattern",
"Step: Call ScrollIntoView()",
"Verification: The the element is within the view port of the parent"
})]
public void TestScrollItem3(TestCaseAttribute testCase)
{
this.HeaderComment(testCase);
TestDriverScrollIntoView1(_HUNDRED, _ZERO);
}
/// -------------------------------------------------------------------
///<summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ScrollIntoView.5",
Priority = TestPriorities.Pri1,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Generic,
Description = new string[]
{
"Verification: Verify that the elements container is visible",
"Step: Scroll to 100, 100",
"Step: Verify element still supports ScrollItem pattern",
"Step: Call ScrollIntoView()",
"Verification: The the element is within the view port of the parent"
})]
public void TestScrollItem4(TestCaseAttribute testCase)
{
this.HeaderComment(testCase);
TestDriverScrollIntoView1(_HUNDRED, _HUNDRED);
}
#endregion Tests
#region TestDrivers
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TestDriverScrollIntoView1(double left, double top)
{
// "Verification: Verify that the elements container is visible
TSC_VerifyPropertyEqual(_container.Current.IsOffscreen, false, AutomationElement.IsOffscreenProperty, CheckType.IncorrectElementConfiguration);
// "Step: Scroll to left, top",
TS_Scroll(left, top, CheckType.Verification);
//"Step: Verify element still supports ScrollItem pattern",
TSC_VerifyPropertyEqual(m_le.GetCurrentPropertyValue(AutomationElement.IsScrollItemPatternAvailableProperty), true, AutomationElement.IsScrollItemPatternAvailableProperty, CheckType.IncorrectElementConfiguration);
// "Step: Call ScrollIntoView()",
TS_ScrollIntoView(CheckType.Verification);
// "Verification: The the element is within the view port of the parent"
TS_IsElementWithinContainer(CheckType.Verification);
}
#endregion TestDrivers
#region TS_* methods
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_ScrollIntoView(CheckType checkType)
{
pattern_ScrollIntoView(null, CheckType.Verification);
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_Scroll(double left, double top, CheckType checkType)
{
helper_SetScrollPercent(left, top, null, checkType);
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_IsElementWithinContainer(CheckType checkType)
{
Rect cRect = _container.Current.BoundingRectangle;
Rect eRect = m_le.Current.BoundingRectangle;
// only one point needs to be withing the parents rect
if (!PointWithin(_container.Current.BoundingRectangle, new Point(eRect.Left, eRect.Top)) &&
!PointWithin(_container.Current.BoundingRectangle, new Point(eRect.Right, eRect.Top)) &&
!PointWithin(_container.Current.BoundingRectangle, new Point(eRect.Left, eRect.Bottom)) &&
!PointWithin(_container.Current.BoundingRectangle, new Point(eRect.Right, eRect.Bottom))
)
ThrowMe(checkType, "Element's rect(" + eRect + ") is not within ScrollPattern element's rect(" + cRect + ")");
m_TestStep++;
}
#endregion TS_* methods
#region Helpers
/// -------------------------------------------------------------------
/// <summary>
/// Determine if a point with within the rectangle
/// </summary>
/// -------------------------------------------------------------------
bool PointWithin(Rect rect, Point point)
{
if (!(rect.Left <= point.X && point.X <= rect.Right) && !(rect.Bottom <= point.Y && point.Y <= rect.Top))
return false;
else
return true;
}
#endregion Helpers
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
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 CompiledAutomaton = Lucene.Net.Util.Automaton.CompiledAutomaton;
/// <summary>
/// Exposes flex API, merged from flex API of
/// sub-segments.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class MultiTerms : Terms
{
private readonly Terms[] subs;
private readonly ReaderSlice[] subSlices;
private readonly IComparer<BytesRef> termComp;
private readonly bool hasFreqs;
private readonly bool hasOffsets;
private readonly bool hasPositions;
private readonly bool hasPayloads;
/// <summary>
/// Sole constructor.
/// </summary>
/// <param name="subs"> The <see cref="Terms"/> instances of all sub-readers. </param>
/// <param name="subSlices"> A parallel array (matching
/// <paramref name="subs"/>) describing the sub-reader slices. </param>
public MultiTerms(Terms[] subs, ReaderSlice[] subSlices)
{
this.subs = subs;
this.subSlices = subSlices;
IComparer<BytesRef> _termComp = null;
Debug.Assert(subs.Length > 0, "inefficient: don't use MultiTerms over one sub");
bool _hasFreqs = true;
bool _hasOffsets = true;
bool _hasPositions = true;
bool _hasPayloads = false;
for (int i = 0; i < subs.Length; i++)
{
if (_termComp == null)
{
_termComp = subs[i].Comparer;
}
else
{
// We cannot merge sub-readers that have
// different TermComps
IComparer<BytesRef> subTermComp = subs[i].Comparer;
if (subTermComp != null && !subTermComp.Equals(_termComp))
{
throw new InvalidOperationException("sub-readers have different BytesRef.Comparers; cannot merge");
}
}
_hasFreqs &= subs[i].HasFreqs;
_hasOffsets &= subs[i].HasOffsets;
_hasPositions &= subs[i].HasPositions;
_hasPayloads |= subs[i].HasPayloads;
}
termComp = _termComp;
hasFreqs = _hasFreqs;
hasOffsets = _hasOffsets;
hasPositions = _hasPositions;
hasPayloads = hasPositions && _hasPayloads; // if all subs have pos, and at least one has payloads.
}
public override TermsEnum Intersect(CompiledAutomaton compiled, BytesRef startTerm)
{
IList<MultiTermsEnum.TermsEnumIndex> termsEnums = new List<MultiTermsEnum.TermsEnumIndex>();
for (int i = 0; i < subs.Length; i++)
{
TermsEnum termsEnum = subs[i].Intersect(compiled, startTerm);
if (termsEnum != null)
{
termsEnums.Add(new MultiTermsEnum.TermsEnumIndex(termsEnum, i));
}
}
if (termsEnums.Count > 0)
{
return (new MultiTermsEnum(subSlices)).Reset(termsEnums.ToArray(/*MultiTermsEnum.TermsEnumIndex.EMPTY_ARRAY*/));
}
else
{
return TermsEnum.EMPTY;
}
}
public override TermsEnum GetIterator(TermsEnum reuse)
{
IList<MultiTermsEnum.TermsEnumIndex> termsEnums = new List<MultiTermsEnum.TermsEnumIndex>();
for (int i = 0; i < subs.Length; i++)
{
TermsEnum termsEnum = subs[i].GetIterator(null);
if (termsEnum != null)
{
termsEnums.Add(new MultiTermsEnum.TermsEnumIndex(termsEnum, i));
}
}
if (termsEnums.Count > 0)
{
return (new MultiTermsEnum(subSlices)).Reset(termsEnums.ToArray(/*MultiTermsEnum.TermsEnumIndex.EMPTY_ARRAY*/));
}
else
{
return TermsEnum.EMPTY;
}
}
public override long Count => -1;
public override long SumTotalTermFreq
{
get
{
long sum = 0;
foreach (Terms terms in subs)
{
long v = terms.SumTotalTermFreq;
if (v == -1)
{
return -1;
}
sum += v;
}
return sum;
}
}
public override long SumDocFreq
{
get
{
long sum = 0;
foreach (Terms terms in subs)
{
long v = terms.SumDocFreq;
if (v == -1)
{
return -1;
}
sum += v;
}
return sum;
}
}
public override int DocCount
{
get
{
int sum = 0;
foreach (Terms terms in subs)
{
int v = terms.DocCount;
if (v == -1)
{
return -1;
}
sum += v;
}
return sum;
}
}
public override IComparer<BytesRef> Comparer => termComp;
public override bool HasFreqs => hasFreqs;
public override bool HasOffsets => hasOffsets;
public override bool HasPositions => hasPositions;
public override bool HasPayloads => hasPayloads;
}
}
| |
//#define USE_SharpZipLib
#if !UNITY_WEBPLAYER
#define USE_FileIO
#endif
/* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* If you want to use compression when saving to file / stream / B64 you have to include
* SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
* define "USE_SharpZipLib" at the top of the file
*
* Written by Bunny83
* 2012-06-09
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
* Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace SimpleJSON
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual IEnumerable<string> Keys { get { yield break; } }
public virtual void Add(string aKey, JSONNode aItem){ }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey) { return null; }
public virtual JSONNode Remove(int aIndex) { return null; }
public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
public virtual string ToPrettyString(int prefix = 0)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(Value,out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(Value,out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value,out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value,out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value)?"true":"false";
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null)?null:d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach(char c in aText)
{
switch(c)
{
case '\\' : result += "\\\\"; break;
case '\"' : result += "\\\""; break;
case '\n' : result += "\\n" ; break;
case '\r' : result += "\\r" ; break;
case '\t' : result += "\\t" ; break;
case '\b' : result += "\\b" ; break;
case '\f' : result += "\\f" ; break;
default : result += c ; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token != "")
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName,Token);
}
TokenName = "";
Token = "";
if (stack.Count>0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (Token != "")
{
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't' : Token += '\t'; break;
case 'r' : Token += '\r'; break;
case 'n' : Token += '\n'; break;
case 'b' : Token += '\b'; break;
case 'f' : Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i+1,4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default : Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter) {}
public void SaveToStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
Serialize(W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public void SaveToFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using(var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode LoadFromFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if (aIndex<0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (aIndex<0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get{ return new JSONLazyCreator(this);}
set{ m_List.Add(value); }
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach(JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override string ToPrettyString (int prefix = 0)
{
string prePrefix = "";
for (int i = 0; i < prefix; i++) {
prePrefix += " ";
}
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + prePrefix + " ";
result += N.ToPrettyString(prefix);
}
result += "\n" + prePrefix + "]";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Array);
aWriter.Write(m_List.Count);
for(int i = 0; i < m_List.Count; i++)
{
m_List[i].Serialize(aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
public override IEnumerable<string> Keys
{
get
{
foreach(var key in m_Dict.Keys)
yield return key;
}
}
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey,value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(KeyValuePair<string,JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override string ToPrettyString (int prefix = 0)
{
int longestLength = 0;
foreach (string key in m_Dict.Keys) {
if (key.Length > longestLength)
longestLength = key.Length;
}
string prePrefix = "";
for (int i = 0; i < prefix; i++) {
prePrefix += " ";
}
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
string aPrefix = "";
for(int i = 0; i < longestLength - N.Key.Length; i++) {
aPrefix += " ";
}
if (result.Length > 3)
result += ", ";
result += "\n" + prePrefix;
result += aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToPrettyString(prefix + longestLength);
}
result += "\n" + prePrefix + "}";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Class);
aWriter.Write(m_Dict.Count);
foreach(string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].Serialize(aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToPrettyString (int prefix)
{
return "\"" + Escape(m_Data) + "\"";
}
public override JSONNode Remove (string aKey)
{
return "\"" + Escape(m_Data) + "\"";
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData("");
tmp.AsInt = AsInt;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.IntValue);
aWriter.Write(AsInt);
return;
}
tmp.AsFloat = AsFloat;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.FloatValue);
aWriter.Write(AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.DoubleValue);
aWriter.Write(AsDouble);
return;
}
tmp.AsBool = AsBool;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.BoolValue);
aWriter.Write(AsBool);
return;
}
aWriter.Write((byte)JSONBinaryTag.Value);
aWriter.Write(m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if (m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override string ToPrettyString (int prefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Azure;
using Management;
using Rest;
using 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>
/// RecommendedElasticPoolsOperations operations.
/// </summary>
internal partial class RecommendedElasticPoolsOperations : IServiceOperations<SqlManagementClient>, IRecommendedElasticPoolsOperations
{
/// <summary>
/// Initializes a new instance of the RecommendedElasticPoolsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RecommendedElasticPoolsOperations(SqlManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SqlManagementClient
/// </summary>
public SqlManagementClient Client { get; private set; }
/// <summary>
/// Gets a recommented elastic pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the recommended elastic pool to be retrieved.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RecommendedElasticPool>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, string recommendedElasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (recommendedElasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "recommendedElasticPoolName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("recommendedElasticPoolName", recommendedElasticPoolName);
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.Sql/servers/{serverName}/recommendedElasticPools/{recommendedElasticPoolName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{recommendedElasticPoolName}", System.Uri.EscapeDataString(recommendedElasticPoolName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.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 (Newtonsoft.Json.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<RecommendedElasticPool>();
_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<RecommendedElasticPool>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a database inside of a recommented elastic pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the elastic pool to be retrieved.
/// </param>
/// <param name='databaseName'>
/// The name of the database to be retrieved.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Database>> GetDatabasesWithHttpMessagesAsync(string resourceGroupName, string serverName, string recommendedElasticPoolName, string databaseName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (recommendedElasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "recommendedElasticPoolName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("recommendedElasticPoolName", recommendedElasticPoolName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetDatabases", 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.Sql/servers/{serverName}/recommendedElasticPools/{recommendedElasticPoolName}/databases/{databaseName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{recommendedElasticPoolName}", System.Uri.EscapeDataString(recommendedElasticPoolName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.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 (Newtonsoft.Json.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<Database>();
_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<Database>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns recommended elastic pools.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<RecommendedElasticPool>>> ListWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recommendedElasticPools").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.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 (Newtonsoft.Json.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<IEnumerable<RecommendedElasticPool>>();
_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<Page<RecommendedElasticPool>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns a database inside of a recommented elastic pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the recommended elastic pool to be retrieved.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Database>>> ListDatabasesWithHttpMessagesAsync(string resourceGroupName, string serverName, string recommendedElasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (recommendedElasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "recommendedElasticPoolName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("recommendedElasticPoolName", recommendedElasticPoolName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListDatabases", 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.Sql/servers/{serverName}/recommendedElasticPools/{recommendedElasticPoolName}/databases").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{recommendedElasticPoolName}", System.Uri.EscapeDataString(recommendedElasticPoolName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.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 (Newtonsoft.Json.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<IEnumerable<Database>>();
_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<Page<Database>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns a recommented elastic pool metrics.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the recommended elastic pool to be retrieved.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<RecommendedElasticPoolMetric>>> ListMetricsWithHttpMessagesAsync(string resourceGroupName, string serverName, string recommendedElasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (recommendedElasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "recommendedElasticPoolName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("recommendedElasticPoolName", recommendedElasticPoolName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListMetrics", 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.Sql/servers/{serverName}/recommendedElasticPools/{recommendedElasticPoolName}/metrics").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{recommendedElasticPoolName}", System.Uri.EscapeDataString(recommendedElasticPoolName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.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 (Newtonsoft.Json.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<IEnumerable<RecommendedElasticPoolMetric>>();
_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<Page<RecommendedElasticPoolMetric>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*=========================================================================
**
** Purpose:
** A complex number z is a number of the form z = x + yi, where x and y
** are real numbers, and i is the imaginary unit, with the property i2= -1.
**
===========================================================================*/
using System;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Numerics
{
public struct Complex : IEquatable<Complex>, IFormattable
{
// --------------SECTION: Private Data members ----------- //
private Double _real;
private Double _imaginary;
// ---------------SECTION: Necessary Constants ----------- //
private const Double LOG_10_INV = 0.43429448190325;
// --------------SECTION: Public Properties -------------- //
public Double Real
{
get
{
return _real;
}
}
public Double Imaginary
{
get
{
return _imaginary;
}
}
public Double Magnitude
{
get
{
return Complex.Abs(this);
}
}
public Double Phase
{
get
{
return Math.Atan2(_imaginary, _real);
}
}
// --------------SECTION: Attributes -------------- //
public static readonly Complex Zero = new Complex(0.0, 0.0);
public static readonly Complex One = new Complex(1.0, 0.0);
public static readonly Complex ImaginaryOne = new Complex(0.0, 1.0);
// --------------SECTION: Constructors and factory methods -------------- //
public Complex(Double real, Double imaginary) /* Constructor to create a complex number with rectangular co-ordinates */
{
_real = real;
_imaginary = imaginary;
}
public static Complex FromPolarCoordinates(Double magnitude, Double phase) /* Factory method to take polar inputs and create a Complex object */
{
return new Complex((magnitude * Math.Cos(phase)), (magnitude * Math.Sin(phase)));
}
public static Complex Negate(Complex value)
{
return -value;
}
public static Complex Add(Complex left, Complex right)
{
return left + right;
}
public static Complex Subtract(Complex left, Complex right)
{
return left - right;
}
public static Complex Multiply(Complex left, Complex right)
{
return left * right;
}
public static Complex Divide(Complex dividend, Complex divisor)
{
return dividend / divisor;
}
// --------------SECTION: Arithmetic Operator(unary) Overloading -------------- //
public static Complex operator -(Complex value) /* Unary negation of a complex number */
{
return (new Complex((-value._real), (-value._imaginary)));
}
// --------------SECTION: Arithmetic Operator(binary) Overloading -------------- //
public static Complex operator +(Complex left, Complex right)
{
return (new Complex((left._real + right._real), (left._imaginary + right._imaginary)));
}
public static Complex operator -(Complex left, Complex right)
{
return (new Complex((left._real - right._real), (left._imaginary - right._imaginary)));
}
public static Complex operator *(Complex left, Complex right)
{
// Multiplication: (a + bi)(c + di) = (ac -bd) + (bc + ad)i
Double result_Realpart = (left._real * right._real) - (left._imaginary * right._imaginary);
Double result_Imaginarypart = (left._imaginary * right._real) + (left._real * right._imaginary);
return (new Complex(result_Realpart, result_Imaginarypart));
}
public static Complex operator /(Complex left, Complex right)
{
// Division : Smith's formula.
double a = left._real;
double b = left._imaginary;
double c = right._real;
double d = right._imaginary;
if (Math.Abs(d) < Math.Abs(c))
{
double doc = d / c;
return new Complex((a + b * doc) / (c + d * doc), (b - a * doc) / (c + d * doc));
}
else
{
double cod = c / d;
return new Complex((b + a * cod) / (d + c * cod), (-a + b * cod) / (d + c * cod));
}
}
// --------------SECTION: Other arithmetic operations -------------- //
public static Double Abs(Complex value)
{
if (Double.IsInfinity(value._real) || Double.IsInfinity(value._imaginary))
{
return double.PositiveInfinity;
}
// |value| == sqrt(a^2 + b^2)
// sqrt(a^2 + b^2) == a/a * sqrt(a^2 + b^2) = a * sqrt(a^2/a^2 + b^2/a^2)
// Using the above we can factor out the square of the larger component to dodge overflow.
double c = Math.Abs(value._real);
double d = Math.Abs(value._imaginary);
if (c > d)
{
double r = d / c;
return c * Math.Sqrt(1.0 + r * r);
}
else if (d == 0.0)
{
return c; // c is either 0.0 or NaN
}
else
{
double r = c / d;
return d * Math.Sqrt(1.0 + r * r);
}
}
public static Complex Conjugate(Complex value)
{
// Conjugate of a Complex number: the conjugate of x+i*y is x-i*y
return (new Complex(value._real, (-value._imaginary)));
}
public static Complex Reciprocal(Complex value)
{
// Reciprocal of a Complex number : the reciprocal of x+i*y is 1/(x+i*y)
if ((value._real == 0) && (value._imaginary == 0))
{
return Complex.Zero;
}
return Complex.One / value;
}
// --------------SECTION: Comparison Operator(binary) Overloading -------------- //
public static bool operator ==(Complex left, Complex right)
{
return ((left._real == right._real) && (left._imaginary == right._imaginary));
}
public static bool operator !=(Complex left, Complex right)
{
return ((left._real != right._real) || (left._imaginary != right._imaginary));
}
// --------------SECTION: Comparison operations (methods implementing IEquatable<ComplexNumber>,IComparable<ComplexNumber>) -------------- //
public override bool Equals(object obj)
{
if (!(obj is Complex)) return false;
return this == ((Complex)obj);
}
public bool Equals(Complex value)
{
return ((_real.Equals(value._real)) && (_imaginary.Equals(value._imaginary)));
}
// --------------SECTION: Type-casting basic numeric data-types to ComplexNumber -------------- //
public static implicit operator Complex(Int16 value)
{
return (new Complex(value, 0.0));
}
public static implicit operator Complex(Int32 value)
{
return (new Complex(value, 0.0));
}
public static implicit operator Complex(Int64 value)
{
return (new Complex(value, 0.0));
}
[CLSCompliant(false)]
public static implicit operator Complex(UInt16 value)
{
return (new Complex(value, 0.0));
}
[CLSCompliant(false)]
public static implicit operator Complex(UInt32 value)
{
return (new Complex(value, 0.0));
}
[CLSCompliant(false)]
public static implicit operator Complex(UInt64 value)
{
return (new Complex(value, 0.0));
}
[CLSCompliant(false)]
public static implicit operator Complex(SByte value)
{
return (new Complex(value, 0.0));
}
public static implicit operator Complex(Byte value)
{
return (new Complex(value, 0.0));
}
public static implicit operator Complex(Single value)
{
return (new Complex(value, 0.0));
}
public static implicit operator Complex(Double value)
{
return (new Complex(value, 0.0));
}
public static explicit operator Complex(BigInteger value)
{
return (new Complex((Double)value, 0.0));
}
public static explicit operator Complex(Decimal value)
{
return (new Complex((Double)value, 0.0));
}
// --------------SECTION: Formattig/Parsing options -------------- //
public override String ToString()
{
return (String.Format(CultureInfo.CurrentCulture, "({0}, {1})", _real, _imaginary));
}
public String ToString(String format)
{
return (String.Format(CultureInfo.CurrentCulture, "({0}, {1})", _real.ToString(format, CultureInfo.CurrentCulture), _imaginary.ToString(format, CultureInfo.CurrentCulture)));
}
public String ToString(IFormatProvider provider)
{
return (String.Format(provider, "({0}, {1})", _real, _imaginary));
}
public String ToString(String format, IFormatProvider provider)
{
return (String.Format(provider, "({0}, {1})", _real.ToString(format, provider), _imaginary.ToString(format, provider)));
}
public override Int32 GetHashCode()
{
Int32 n1 = 99999997;
Int32 hash_real = _real.GetHashCode() % n1;
Int32 hash_imaginary = _imaginary.GetHashCode();
Int32 final_hashcode = hash_real ^ hash_imaginary;
return (final_hashcode);
}
// --------------SECTION: Trigonometric operations (methods implementing ITrigonometric) -------------- //
public static Complex Sin(Complex value)
{
double a = value._real;
double b = value._imaginary;
return new Complex(Math.Sin(a) * Math.Cosh(b), Math.Cos(a) * Math.Sinh(b));
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sinh", Justification = "matell: Existing Name")]
public static Complex Sinh(Complex value) /* Hyperbolic sin */
{
double a = value._real;
double b = value._imaginary;
return new Complex(Math.Sinh(a) * Math.Cos(b), Math.Cosh(a) * Math.Sin(b));
}
public static Complex Asin(Complex value) /* Arcsin */
{
if ((value._imaginary == 0 && value._real < 0) || value._imaginary > 0)
{
return -Asin(-value);
}
return (-ImaginaryOne) * Log(ImaginaryOne * value + Sqrt(One - value * value));
}
public static Complex Cos(Complex value)
{
double a = value._real;
double b = value._imaginary;
return new Complex(Math.Cos(a) * Math.Cosh(b), -(Math.Sin(a) * Math.Sinh(b)));
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cosh", Justification = "matell: Existing Name")]
public static Complex Cosh(Complex value) /* Hyperbolic cos */
{
double a = value._real;
double b = value._imaginary;
return new Complex(Math.Cosh(a) * Math.Cos(b), Math.Sinh(a) * Math.Sin(b));
}
public static Complex Acos(Complex value) /* Arccos */
{
if ((value._imaginary == 0 && value._real > 0) || value._imaginary < 0)
{
return System.Math.PI - Acos(-value);
}
return (-ImaginaryOne) * Log(value + ImaginaryOne * Sqrt(One - (value * value)));
}
public static Complex Tan(Complex value)
{
return (Sin(value) / Cos(value));
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Tanh", Justification = "matell: Existing Name")]
public static Complex Tanh(Complex value) /* Hyperbolic tan */
{
return (Sinh(value) / Cosh(value));
}
public static Complex Atan(Complex value) /* Arctan */
{
Complex Two = new Complex(2.0, 0.0);
return (ImaginaryOne / Two) * (Log(One - ImaginaryOne * value) - Log(One + ImaginaryOne * value));
}
// --------------SECTION: Other numerical functions -------------- //
public static Complex Log(Complex value) /* Log of the complex number value to the base of 'e' */
{
return (new Complex((Math.Log(Abs(value))), (Math.Atan2(value._imaginary, value._real))));
}
public static Complex Log(Complex value, Double baseValue) /* Log of the complex number to a the base of a double */
{
return (Log(value) / Log(baseValue));
}
public static Complex Log10(Complex value) /* Log to the base of 10 of the complex number */
{
Complex temp_log = Log(value);
return (Scale(temp_log, (Double)LOG_10_INV));
}
public static Complex Exp(Complex value) /* The complex number raised to e */
{
Double temp_factor = Math.Exp(value._real);
Double result_re = temp_factor * Math.Cos(value._imaginary);
Double result_im = temp_factor * Math.Sin(value._imaginary);
return (new Complex(result_re, result_im));
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sqrt", Justification = "matell: Existing Name")]
public static Complex Sqrt(Complex value) /* Square root ot the complex number */
{
return Complex.FromPolarCoordinates(Math.Sqrt(value.Magnitude), value.Phase / 2.0);
}
public static Complex Pow(Complex value, Complex power) /* A complex number raised to another complex number */
{
if (power == Complex.Zero)
{
return Complex.One;
}
if (value == Complex.Zero)
{
return Complex.Zero;
}
double a = value._real;
double b = value._imaginary;
double c = power._real;
double d = power._imaginary;
double rho = Complex.Abs(value);
double theta = Math.Atan2(b, a);
double newRho = c * theta + d * Math.Log(rho);
double t = Math.Pow(rho, c) * Math.Pow(Math.E, -d * theta);
return new Complex(t * Math.Cos(newRho), t * Math.Sin(newRho));
}
public static Complex Pow(Complex value, Double power) // A complex number raised to a real number
{
return Pow(value, new Complex(power, 0));
}
//--------------- SECTION: Private member functions for internal use -----------------------------------//
private static Complex Scale(Complex value, Double factor)
{
Double result_re = factor * value._real;
Double result_im = factor * value._imaginary;
return (new Complex(result_re, result_im));
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
using Pathfinding.RVO;
/** AI for following paths.
* This AI is the default movement script which comes with the A* Pathfinding Project.
* It is in no way required by the rest of the system, so feel free to write your own. But I hope this script will make it easier
* to set up movement for the characters in your game. This script is not written for high performance, so I do not recommend using it for large groups of units.
* \n
* \n
* This script will try to follow a target transform, in regular intervals, the path to that target will be recalculated.
* It will on FixedUpdate try to move towards the next point in the path.
* However it will only move in the forward direction, but it will rotate around it's Y-axis
* to make it reach the target.
*
* \section variables Quick overview of the variables
* In the inspector in Unity, you will see a bunch of variables. You can view detailed information further down, but here's a quick overview.\n
* The #repathRate determines how often it will search for new paths, if you have fast moving targets, you might want to set it to a lower value.\n
* The #target variable is where the AI will try to move, it can be a point on the ground where the player has clicked in an RTS for example.
* Or it can be the player object in a zombie game.\n
* The speed is self-explanatory, so is turningSpeed, however #slowdownDistance might require some explanation.
* It is the approximate distance from the target where the AI will start to slow down. Note that this doesn't only affect the end point of the path
* but also any intermediate points, so be sure to set #forwardLook and #pickNextWaypointDist to a higher value than this.\n
* #pickNextWaypointDist is simply determines within what range it will switch to target the next waypoint in the path.\n
* #forwardLook will try to calculate an interpolated target point on the current segment in the path so that it has a distance of #forwardLook from the AI\n
* Below is an image illustrating several variables as well as some internal ones, but which are relevant for understanding how it works.
* Note that the #forwardLook range will not match up exactly with the target point practically, even though that's the goal.
* \shadowimage{aipath_variables.png}
* This script has many movement fallbacks.
* If it finds a NavmeshController, it will use that, otherwise it will look for a character controller, then for a rigidbody and if it hasn't been able to find any
* it will use Transform.Translate which is guaranteed to always work.
*/
[RequireComponent(typeof(Seeker))]
[AddComponentMenu("Pathfinding/AI/AIPath (3D)")]
[HelpURL("http://arongranberg.com/astar/docs/class_a_i_path.php")]
public class AIPath : MonoBehaviour {
/** Determines how often it will search for new paths.
* If you have fast moving targets or AIs, you might want to set it to a lower value.
* The value is in seconds between path requests.
*/
public float repathRate = 0.5F;
/** Target to move towards.
* The AI will try to follow/move towards this target.
* It can be a point on the ground where the player has clicked in an RTS for example, or it can be the player object in a zombie game.
*/
public Transform target;
/** Enables or disables searching for paths.
* Setting this to false does not stop any active path requests from being calculated or stop it from continuing to follow the current path.
* \see #canMove
*/
public bool canSearch = true;
/** Enables or disables movement.
* \see #canSearch */
public bool canMove = true;
/** Maximum velocity.
* This is the maximum speed in world units per second.
*/
public float speed = 3;
/** Rotation speed.
* Rotation is calculated using Quaternion.SLerp. This variable represents the damping, the higher, the faster it will be able to rotate.
*/
public float turningSpeed = 5;
/** Distance from the target point where the AI will start to slow down.
* Note that this doesn't only affect the end point of the path
* but also any intermediate points, so be sure to set #forwardLook and #pickNextWaypointDist to a higher value than this
*/
public float slowdownDistance = 0.6F;
/** Determines within what range it will switch to target the next waypoint in the path */
public float pickNextWaypointDist = 2;
/** Target point is Interpolated on the current segment in the path so that it has a distance of #forwardLook from the AI.
* See the detailed description of AIPath for an illustrative image */
public float forwardLook = 1;
/** Distance to the end point to consider the end of path to be reached.
* When this has been reached, the AI will not move anymore until the target changes and OnTargetReached will be called.
*/
public float endReachedDistance = 0.2F;
/** Do a closest point on path check when receiving path callback.
* Usually the AI has moved a bit between requesting the path, and getting it back, and there is usually a small gap between the AI
* and the closest node.
* If this option is enabled, it will simulate, when the path callback is received, movement between the closest node and the current
* AI position. This helps to reduce the moments when the AI just get a new path back, and thinks it ought to move backwards to the start of the new path
* even though it really should just proceed forward.
*/
public bool closestOnPathCheck = true;
protected float minMoveScale = 0.05F;
/** Cached Seeker component */
protected Seeker seeker;
/** Cached Transform component */
protected Transform tr;
/** Time when the last path request was sent */
protected float lastRepath = -9999;
/** Current path which is followed */
protected Path path;
/** Cached CharacterController component */
protected CharacterController controller;
protected RVOController rvoController;
/** Cached Rigidbody component */
protected Rigidbody rigid;
/** Current index in the path which is current target */
protected int currentWaypointIndex = 0;
/** Holds if the end-of-path is reached
* \see TargetReached */
protected bool targetReached = false;
/** Only when the previous path has been returned should be search for a new path */
protected bool canSearchAgain = true;
protected Vector3 lastFoundWaypointPosition;
protected float lastFoundWaypointTime = -9999;
/** Returns if the end-of-path has been reached
* \see targetReached */
public bool TargetReached {
get {
return targetReached;
}
}
/** Holds if the Start function has been run.
* Used to test if coroutines should be started in OnEnable to prevent calculating paths
* in the awake stage (or rather before start on frame 0).
*/
private bool startHasRun = false;
/** Initializes reference variables.
* If you override this function you should in most cases call base.Awake () at the start of it.
* */
protected virtual void Awake () {
seeker = GetComponent<Seeker>();
//This is a simple optimization, cache the transform component lookup
tr = transform;
//Cache some other components (not all are necessarily there)
controller = GetComponent<CharacterController>();
rvoController = GetComponent<RVOController>();
if (rvoController != null) rvoController.enableRotation = false;
rigid = GetComponent<Rigidbody>();
}
/** Starts searching for paths.
* If you override this function you should in most cases call base.Start () at the start of it.
* \see OnEnable
* \see RepeatTrySearchPath
*/
protected virtual void Start () {
startHasRun = true;
OnEnable();
}
/** Run at start and when reenabled.
* Starts RepeatTrySearchPath.
*
* \see Start
*/
protected virtual void OnEnable () {
lastRepath = -9999;
canSearchAgain = true;
lastFoundWaypointPosition = GetFeetPosition();
if (startHasRun) {
//Make sure we receive callbacks when paths complete
seeker.pathCallback += OnPathComplete;
StartCoroutine(RepeatTrySearchPath());
}
}
public void OnDisable () {
// Abort calculation of path
if (seeker != null && !seeker.IsDone()) seeker.GetCurrentPath().Error();
// Release current path
if (path != null) path.Release(this);
path = null;
//Make sure we receive callbacks when paths complete
seeker.pathCallback -= OnPathComplete;
}
/** Tries to search for a path every #repathRate seconds.
* \see TrySearchPath
*/
protected IEnumerator RepeatTrySearchPath () {
while (true) {
float v = TrySearchPath();
yield return new WaitForSeconds(v);
}
}
/** Tries to search for a path.
* Will search for a new path if there was a sufficient time since the last repath and both
* #canSearchAgain and #canSearch are true and there is a target.
*
* \returns The time to wait until calling this function again (based on #repathRate)
*/
public float TrySearchPath () {
if (Time.time - lastRepath >= repathRate && canSearchAgain && canSearch && target != null) {
SearchPath();
return repathRate;
} else {
//StartCoroutine (WaitForRepath ());
float v = repathRate - (Time.time-lastRepath);
return v < 0 ? 0 : v;
}
}
/** Requests a path to the target */
public virtual void SearchPath () {
if (target == null) throw new System.InvalidOperationException("Target is null");
lastRepath = Time.time;
//This is where we should search to
Vector3 targetPosition = target.position;
canSearchAgain = false;
//Alternative way of requesting the path
//ABPath p = ABPath.Construct (GetFeetPosition(),targetPoint,null);
//seeker.StartPath (p);
//We should search from the current position
seeker.StartPath(GetFeetPosition(), targetPosition);
}
public virtual void OnTargetReached () {
//End of path has been reached
//If you want custom logic for when the AI has reached it's destination
//add it here
//You can also create a new script which inherits from this one
//and override the function in that script
}
/** Called when a requested path has finished calculation.
* A path is first requested by #SearchPath, it is then calculated, probably in the same or the next frame.
* Finally it is returned to the seeker which forwards it to this function.\n
*/
public virtual void OnPathComplete (Path _p) {
ABPath p = _p as ABPath;
if (p == null) throw new System.Exception("This function only handles ABPaths, do not use special path types");
canSearchAgain = true;
//Claim the new path
p.Claim(this);
// Path couldn't be calculated of some reason.
// More info in p.errorLog (debug string)
if (p.error) {
p.Release(this);
return;
}
//Release the previous path
if (path != null) path.Release(this);
//Replace the old path
path = p;
//Reset some variables
currentWaypointIndex = 0;
targetReached = false;
//The next row can be used to find out if the path could be found or not
//If it couldn't (error == true), then a message has probably been logged to the console
//however it can also be got using p.errorLog
//if (p.error)
if (closestOnPathCheck) {
// Simulate movement from the point where the path was requested
// to where we are right now. This reduces the risk that the agent
// gets confused because the first point in the path is far away
// from the current position (possibly behind it which could cause
// the agent to turn around, and that looks pretty bad).
Vector3 p1 = Time.time - lastFoundWaypointTime < 0.3f ? lastFoundWaypointPosition : p.originalStartPoint;
Vector3 p2 = GetFeetPosition();
Vector3 dir = p2-p1;
float magn = dir.magnitude;
dir /= magn;
int steps = (int)(magn/pickNextWaypointDist);
#if ASTARDEBUG
Debug.DrawLine(p1, p2, Color.red, 1);
#endif
for (int i = 0; i <= steps; i++) {
CalculateVelocity(p1);
p1 += dir;
}
}
}
public virtual Vector3 GetFeetPosition () {
if (rvoController != null) {
return tr.position - Vector3.up*rvoController.height*0.5f;
} else
if (controller != null) {
return tr.position - Vector3.up*controller.height*0.5F;
}
return tr.position;
}
public virtual void Update () {
if (!canMove) { return; }
Vector3 dir = CalculateVelocity(GetFeetPosition());
//Rotate towards targetDirection (filled in by CalculateVelocity)
RotateTowards(targetDirection);
if (rvoController != null) {
rvoController.Move(dir);
} else
if (controller != null) {
controller.SimpleMove(dir);
} else if (rigid != null) {
rigid.AddForce(dir);
} else {
tr.Translate(dir*Time.deltaTime, Space.World);
}
}
/** Point to where the AI is heading.
* Filled in by #CalculateVelocity */
protected Vector3 targetPoint;
/** Relative direction to where the AI is heading.
* Filled in by #CalculateVelocity */
protected Vector3 targetDirection;
protected float XZSqrMagnitude (Vector3 a, Vector3 b) {
float dx = b.x-a.x;
float dz = b.z-a.z;
return dx*dx + dz*dz;
}
/** Calculates desired velocity.
* Finds the target path segment and returns the forward direction, scaled with speed.
* A whole bunch of restrictions on the velocity is applied to make sure it doesn't overshoot, does not look too far ahead,
* and slows down when close to the target.
* /see speed
* /see endReachedDistance
* /see slowdownDistance
* /see CalculateTargetPoint
* /see targetPoint
* /see targetDirection
* /see currentWaypointIndex
*/
protected Vector3 CalculateVelocity (Vector3 currentPosition) {
if (path == null || path.vectorPath == null || path.vectorPath.Count == 0) return Vector3.zero;
List<Vector3> vPath = path.vectorPath;
if (vPath.Count == 1) {
vPath.Insert(0, currentPosition);
}
if (currentWaypointIndex >= vPath.Count) { currentWaypointIndex = vPath.Count-1; }
if (currentWaypointIndex <= 1) currentWaypointIndex = 1;
while (true) {
if (currentWaypointIndex < vPath.Count-1) {
//There is a "next path segment"
float dist = XZSqrMagnitude(vPath[currentWaypointIndex], currentPosition);
//Mathfx.DistancePointSegmentStrict (vPath[currentWaypointIndex+1],vPath[currentWaypointIndex+2],currentPosition);
if (dist < pickNextWaypointDist*pickNextWaypointDist) {
lastFoundWaypointPosition = currentPosition;
lastFoundWaypointTime = Time.time;
currentWaypointIndex++;
} else {
break;
}
} else {
break;
}
}
Vector3 dir = vPath[currentWaypointIndex] - vPath[currentWaypointIndex-1];
Vector3 targetPosition = CalculateTargetPoint(currentPosition, vPath[currentWaypointIndex-1], vPath[currentWaypointIndex]);
dir = targetPosition-currentPosition;
dir.y = 0;
float targetDist = dir.magnitude;
float slowdown = Mathf.Clamp01(targetDist / slowdownDistance);
this.targetDirection = dir;
this.targetPoint = targetPosition;
if (currentWaypointIndex == vPath.Count-1 && targetDist <= endReachedDistance) {
if (!targetReached) { targetReached = true; OnTargetReached(); }
//Send a move request, this ensures gravity is applied
return Vector3.zero;
}
Vector3 forward = tr.forward;
float dot = Vector3.Dot(dir.normalized, forward);
float sp = speed * Mathf.Max(dot, minMoveScale) * slowdown;
#if ASTARDEBUG
Debug.DrawLine(vPath[currentWaypointIndex-1], vPath[currentWaypointIndex], Color.black);
Debug.DrawLine(GetFeetPosition(), targetPosition, Color.red);
Debug.DrawRay(targetPosition, Vector3.up, Color.red);
Debug.DrawRay(GetFeetPosition(), dir, Color.yellow);
Debug.DrawRay(GetFeetPosition(), forward*sp, Color.cyan);
#endif
if (Time.deltaTime > 0) {
sp = Mathf.Clamp(sp, 0, targetDist/(Time.deltaTime*2));
}
return forward*sp;
}
/** Rotates in the specified direction.
* Rotates around the Y-axis.
* \see turningSpeed
*/
protected virtual void RotateTowards (Vector3 dir) {
if (dir == Vector3.zero) return;
Quaternion rot = tr.rotation;
Quaternion toTarget = Quaternion.LookRotation(dir);
rot = Quaternion.Slerp(rot, toTarget, turningSpeed*Time.deltaTime);
Vector3 euler = rot.eulerAngles;
euler.z = 0;
euler.x = 0;
rot = Quaternion.Euler(euler);
tr.rotation = rot;
}
/** Calculates target point from the current line segment.
* \param p Current position
* \param a Line segment start
* \param b Line segment end
* The returned point will lie somewhere on the line segment.
* \see #forwardLook
* \todo This function uses .magnitude quite a lot, can it be optimized?
*/
protected Vector3 CalculateTargetPoint (Vector3 p, Vector3 a, Vector3 b) {
a.y = p.y;
b.y = p.y;
float magn = (a-b).magnitude;
if (magn == 0) return a;
float closest = Mathf.Clamp01(VectorMath.ClosestPointOnLineFactor(a, b, p));
Vector3 point = (b-a)*closest + a;
float distance = (point-p).magnitude;
float lookAhead = Mathf.Clamp(forwardLook - distance, 0.0F, forwardLook);
float offset = lookAhead / magn;
offset = Mathf.Clamp(offset+closest, 0.0F, 1.0F);
return (b-a)*offset + a;
}
}
| |
//
// NowPlayingInterface.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright 2008-2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
using Banshee.Gui;
using Banshee.PlatformServices;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Sources.Gui;
namespace Banshee.NowPlaying
{
public class NowPlayingInterface : VBox, ISourceContents
{
private NowPlayingSource source;
private Hyena.Widgets.RoundedFrame frame;
private Gtk.Window video_window;
private Gtk.Window primary_window;
private FullscreenAdapter fullscreen_adapter;
private ScreensaverManager screensaver;
internal NowPlayingContents Contents { get; private set; }
public NowPlayingInterface ()
{
GtkElementsService service = ServiceManager.Get<GtkElementsService> ();
primary_window = service.PrimaryWindow;
Contents = new NowPlayingContents ();
// This is my really sweet hack - it's where the video widget
// is sent when the source is not active. This keeps the video
// widget from being completely destroyed, causing problems with
// its internal windowing and GstXOverlay. It's also conveniently
// the window that is used to do fullscreen video. Sweeeeeeeeeet.
video_window = new FullscreenWindow (service.PrimaryWindow);
video_window.Hidden += OnFullscreenWindowHidden;
video_window.Realize ();
video_window.Add (Contents);
frame = new Hyena.Widgets.RoundedFrame ();
frame.SetFillColor (new Cairo.Color (0, 0, 0));
frame.DrawBorder = false;
frame.Show ();
PackStart (frame, true, true, 0);
fullscreen_adapter = new FullscreenAdapter ();
fullscreen_adapter.SuggestUnfullscreen += OnAdapterSuggestUnfullscreen;
screensaver = new ScreensaverManager ();
}
protected override void Dispose (bool disposing)
{
if (disposing) {
fullscreen_adapter.SuggestUnfullscreen -= OnAdapterSuggestUnfullscreen;
fullscreen_adapter.Dispose ();
screensaver.Dispose ();
}
base.Dispose (disposing);
}
private void MoveVideoExternal (bool hidden)
{
if (Contents.Parent != video_window) {
Contents.Visible = !hidden;
Contents.Reparent (video_window);
}
}
private void MoveVideoInternal ()
{
if (Contents.Parent != frame) {
Contents.Reparent (frame);
Contents.Show ();
}
}
protected override void OnRealized ()
{
base.OnRealized ();
MoveVideoInternal ();
}
protected override void OnUnrealized ()
{
MoveVideoExternal (false);
base.OnUnrealized ();
}
#region Video Fullscreen Override
private ViewActions.FullscreenHandler previous_fullscreen_handler;
private bool primary_window_is_fullscreen;
private void DisableFullscreenAction ()
{
InterfaceActionService service = ServiceManager.Get<InterfaceActionService> ();
Gtk.ToggleAction action = service.ViewActions["FullScreenAction"] as Gtk.ToggleAction;
if (action != null) {
action.Active = false;
}
}
internal void OverrideFullscreen ()
{
FullscreenHandler (false);
InterfaceActionService service = ServiceManager.Get<InterfaceActionService> ();
if (service == null || service.ViewActions == null) {
return;
}
previous_fullscreen_handler = service.ViewActions.Fullscreen;
primary_window_is_fullscreen = (primary_window.Window.State & Gdk.WindowState.Fullscreen) != 0;
service.ViewActions.Fullscreen = FullscreenHandler;
DisableFullscreenAction ();
}
internal void RelinquishFullscreen ()
{
FullscreenHandler (false);
InterfaceActionService service = ServiceManager.Get<InterfaceActionService> ();
if (service == null || service.ViewActions == null) {
return;
}
service.ViewActions.Fullscreen = previous_fullscreen_handler;
}
private void OnFullscreenWindowHidden (object o, EventArgs args)
{
MoveVideoInternal ();
DisableFullscreenAction ();
}
private bool is_fullscreen;
private void FullscreenHandler (bool fullscreen)
{
// Note: Since the video window is override-redirect, we
// need to fullscreen the main window, so the window manager
// actually knows we are actually doing stuff in fullscreen
// here. The original primary window fullscreen state is
// stored, so when we can restore it appropriately
is_fullscreen = fullscreen;
if (fullscreen) {
primary_window.Fullscreen ();
MoveVideoExternal (true);
video_window.Show ();
fullscreen_adapter.Fullscreen (video_window, true);
screensaver.Inhibit ();
} else {
video_window.Hide ();
screensaver.UnInhibit ();
fullscreen_adapter.Fullscreen (video_window, false);
video_window.Hide ();
if (!primary_window_is_fullscreen) {
primary_window.Unfullscreen ();
}
}
}
private void OnAdapterSuggestUnfullscreen (object o, EventArgs args)
{
if (is_fullscreen) {
Hyena.Log.Debug ("Closing fullscreen at request of the FullscreenAdapter");
FullscreenHandler (false);
}
}
#endregion
#region ISourceContents
public bool SetSource (ISource src)
{
this.source = src as NowPlayingSource;
return this.source != null;
}
public ISource Source {
get { return source; }
}
public void ResetSource ()
{
source = null;
}
public Widget Widget {
get { return this; }
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Threading;
using ClosedXML.Excel;
using NUnit.Framework;
namespace ClosedXML_Tests.Excel.DataValidations
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestFixture]
public class DateAndTimeTests
{
[OneTimeSetUp]
public void SetCultureInfo()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
}
[Test]
public void Date()
{
Object actual = XLWorkbook.EvaluateExpr("Date(2008, 1, 1)");
Assert.AreEqual(39448, actual);
}
[Test]
public void Datevalue()
{
Object actual = XLWorkbook.EvaluateExpr("DateValue(\"8/22/2008\")");
Assert.AreEqual(39682, actual);
}
[Test]
public void Day()
{
Object actual = XLWorkbook.EvaluateExpr("Day(\"8/22/2008\")");
Assert.AreEqual(22, actual);
}
[Test]
public void Days()
{
Object actual = XLWorkbook.EvaluateExpr("DAYS(DATE(2016,10,1),DATE(1992,2,29))");
Assert.AreEqual(8981, actual);
actual = XLWorkbook.EvaluateExpr("DAYS(\"2016-10-1\",\"1992-2-29\")");
Assert.AreEqual(8981, actual);
}
[Test]
public void DayWithDifferentCulture()
{
CultureInfo ci = new CultureInfo(CultureInfo.InvariantCulture.LCID);
ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
Thread.CurrentThread.CurrentCulture = ci;
Object actual = XLWorkbook.EvaluateExpr("Day(\"1/6/2008\")");
Assert.AreEqual(1, actual);
}
[Test]
public void Days360_Default()
{
Object actual = XLWorkbook.EvaluateExpr("Days360(\"1/30/2008\", \"2/1/2008\")");
Assert.AreEqual(1, actual);
}
[Test]
public void Days360_Europe1()
{
Object actual = XLWorkbook.EvaluateExpr("DAYS360(\"1/1/2008\", \"3/31/2008\",TRUE)");
Assert.AreEqual(89, actual);
}
[Test]
public void Days360_Europe2()
{
Object actual = XLWorkbook.EvaluateExpr("DAYS360(\"3/31/2008\", \"1/1/2008\",TRUE)");
Assert.AreEqual(-89, actual);
}
[Test]
public void Days360_US1()
{
Object actual = XLWorkbook.EvaluateExpr("DAYS360(\"1/1/2008\", \"3/31/2008\",FALSE)");
Assert.AreEqual(90, actual);
}
[Test]
public void Days360_US2()
{
Object actual = XLWorkbook.EvaluateExpr("DAYS360(\"3/31/2008\", \"1/1/2008\",FALSE)");
Assert.AreEqual(-89, actual);
}
[Test]
public void EDate_Negative1()
{
Object actual = XLWorkbook.EvaluateExpr("EDate(\"3/1/2008\", -1)");
Assert.AreEqual(new DateTime(2008, 2, 1), actual);
}
[Test]
public void EDate_Negative2()
{
Object actual = XLWorkbook.EvaluateExpr("EDate(\"3/31/2008\", -1)");
Assert.AreEqual(new DateTime(2008, 2, 29), actual);
}
[Test]
public void EDate_Positive1()
{
Object actual = XLWorkbook.EvaluateExpr("EDate(\"3/1/2008\", 1)");
Assert.AreEqual(new DateTime(2008, 4, 1), actual);
}
[Test]
public void EDate_Positive2()
{
Object actual = XLWorkbook.EvaluateExpr("EDate(\"3/31/2008\", 1)");
Assert.AreEqual(new DateTime(2008, 4, 30), actual);
}
[Test]
public void EOMonth_Negative()
{
Object actual = XLWorkbook.EvaluateExpr("EOMonth(\"3/1/2008\", -1)");
Assert.AreEqual(new DateTime(2008, 2, 29), actual);
}
[Test]
public void EOMonth_Positive()
{
Object actual = XLWorkbook.EvaluateExpr("EOMonth(\"3/31/2008\", 1)");
Assert.AreEqual(new DateTime(2008, 4, 30), actual);
}
[Test]
public void Hour()
{
Object actual = XLWorkbook.EvaluateExpr("Hour(\"8/22/2008 3:30:45 PM\")");
Assert.AreEqual(15, actual);
}
[Test]
public void Minute()
{
Object actual = XLWorkbook.EvaluateExpr("Minute(\"8/22/2008 3:30:45 AM\")");
Assert.AreEqual(30, actual);
}
[Test]
public void Month()
{
Object actual = XLWorkbook.EvaluateExpr("Month(\"8/22/2008\")");
Assert.AreEqual(8, actual);
}
[Test]
public void IsoWeekNum()
{
Object actual = XLWorkbook.EvaluateExpr("ISOWEEKNUM(DATEVALUE(\"2012-3-9\"))");
Assert.AreEqual(10, actual);
actual = XLWorkbook.EvaluateExpr("ISOWEEKNUM(DATE(2012,12,31))");
Assert.AreEqual(1, actual);
}
[Test]
public void Networkdays_MultipleHolidaysGiven()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Date")
.CellBelow().SetValue(new DateTime(2008, 10, 1))
.CellBelow().SetValue(new DateTime(2009, 3, 1))
.CellBelow().SetValue(new DateTime(2008, 11, 26))
.CellBelow().SetValue(new DateTime(2008, 12, 4))
.CellBelow().SetValue(new DateTime(2009, 1, 21));
Object actual = ws.Evaluate("Networkdays(A2,A3,A4:A6)");
Assert.AreEqual(105, actual);
}
[Test]
public void Networkdays_NoHolidaysGiven()
{
Object actual = XLWorkbook.EvaluateExpr("Networkdays(\"10/01/2008\", \"3/01/2009\")");
Assert.AreEqual(108, actual);
}
[Test]
public void Networkdays_NegativeResult()
{
Object actual = XLWorkbook.EvaluateExpr("Networkdays(\"3/01/2009\", \"10/01/2008\")");
Assert.AreEqual(-108, actual);
actual = XLWorkbook.EvaluateExpr("Networkdays(\"2016-01-01\", \"2015-12-23\")");
Assert.AreEqual(-8, actual);
}
[Test]
public void Networkdays_OneHolidaysGiven()
{
Object actual = XLWorkbook.EvaluateExpr("Networkdays(\"10/01/2008\", \"3/01/2009\", \"11/26/2008\")");
Assert.AreEqual(107, actual);
}
[Test]
public void Second()
{
Object actual = XLWorkbook.EvaluateExpr("Second(\"8/22/2008 3:30:45 AM\")");
Assert.AreEqual(45, actual);
}
[Test]
public void Time()
{
Object actual = XLWorkbook.EvaluateExpr("Time(1,2,3)");
Assert.AreEqual(new TimeSpan(1, 2, 3), actual);
}
[Test]
public void TimeValue1()
{
Object actual = XLWorkbook.EvaluateExpr("TimeValue(\"2:24 AM\")");
Assert.IsTrue(XLHelper.AreEqual(0.1, (double) actual));
}
[Test]
public void TimeValue2()
{
Object actual = XLWorkbook.EvaluateExpr("TimeValue(\"22-Aug-2008 6:35 AM\")");
Assert.IsTrue(XLHelper.AreEqual(0.27430555555555558, (double) actual));
}
[Test]
public void Today()
{
Object actual = XLWorkbook.EvaluateExpr("Today()");
Assert.AreEqual(DateTime.Now.Date, actual);
}
[Test]
public void Weekday_1()
{
Object actual = XLWorkbook.EvaluateExpr("Weekday(\"2/14/2008\", 1)");
Assert.AreEqual(5, actual);
}
[Test]
public void Weekday_2()
{
Object actual = XLWorkbook.EvaluateExpr("Weekday(\"2/14/2008\", 2)");
Assert.AreEqual(4, actual);
}
[Test]
public void Weekday_3()
{
Object actual = XLWorkbook.EvaluateExpr("Weekday(\"2/14/2008\", 3)");
Assert.AreEqual(3, actual);
}
[Test]
public void Weekday_Omitted()
{
Object actual = XLWorkbook.EvaluateExpr("Weekday(\"2/14/2008\")");
Assert.AreEqual(5, actual);
}
[Test]
public void Weeknum_1()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2000\", 1)"));
}
[Test]
public void Weeknum_10()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2004\", 2)"));
}
[Test]
public void Weeknum_11()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2005\", 1)"));
}
[Test]
public void Weeknum_12()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2005\", 2)"));
}
[Test]
public void Weeknum_13()
{
Assert.AreEqual(10, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2006\", 1)"));
}
[Test]
public void Weeknum_14()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2006\", 2)"));
}
[Test]
public void Weeknum_15()
{
Assert.AreEqual(10, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2007\", 1)"));
}
[Test]
public void Weeknum_16()
{
Assert.AreEqual(10, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2007\", 2)"));
}
[Test]
public void Weeknum_17()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2008\", 1)"));
}
[Test]
public void Weeknum_18()
{
Assert.AreEqual(10, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2008\", 2)"));
}
[Test]
public void Weeknum_19()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2009\", 1)"));
}
[Test]
public void Weeknum_2()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2000\", 2)"));
}
[Test]
public void Weeknum_20()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2009\", 2)"));
}
[Test]
public void Weeknum_3()
{
Assert.AreEqual(10, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2001\", 1)"));
}
[Test]
public void Weeknum_4()
{
Assert.AreEqual(10, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2001\", 2)"));
}
[Test]
public void Weeknum_5()
{
Assert.AreEqual(10, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2002\", 1)"));
}
[Test]
public void Weeknum_6()
{
Assert.AreEqual(10, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2002\", 2)"));
}
[Test]
public void Weeknum_7()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2003\", 1)"));
}
[Test]
public void Weeknum_8()
{
Assert.AreEqual(10, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2003\", 2)"));
}
[Test]
public void Weeknum_9()
{
Assert.AreEqual(11, XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2004\", 1)"));
}
[Test]
public void Weeknum_Default()
{
Object actual = XLWorkbook.EvaluateExpr("Weeknum(\"3/9/2008\")");
Assert.AreEqual(11, actual);
}
[Test]
public void Workdays_MultipleHolidaysGiven()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Date")
.CellBelow().SetValue(new DateTime(2008, 10, 1))
.CellBelow().SetValue(151)
.CellBelow().SetValue(new DateTime(2008, 11, 26))
.CellBelow().SetValue(new DateTime(2008, 12, 4))
.CellBelow().SetValue(new DateTime(2009, 1, 21));
Object actual = ws.Evaluate("Workday(A2,A3,A4:A6)");
Assert.AreEqual(new DateTime(2009, 5, 5), actual);
}
[Test]
public void Workdays_NoHolidaysGiven()
{
Object actual = XLWorkbook.EvaluateExpr("Workday(\"10/01/2008\", 151)");
Assert.AreEqual(new DateTime(2009, 4, 30), actual);
actual = XLWorkbook.EvaluateExpr("Workday(\"2016-01-01\", -10)");
Assert.AreEqual(new DateTime(2015, 12, 18), actual);
}
[Test]
public void Workdays_OneHolidaysGiven()
{
Object actual = XLWorkbook.EvaluateExpr("Workday(\"10/01/2008\", 152, \"11/26/2008\")");
Assert.AreEqual(new DateTime(2009, 5, 4), actual);
}
[Test]
public void Year()
{
Object actual = XLWorkbook.EvaluateExpr("Year(\"8/22/2008\")");
Assert.AreEqual(2008, actual);
}
[Test]
public void Yearfrac_1_base0()
{
Object actual = XLWorkbook.EvaluateExpr("Yearfrac(\"1/1/2008\", \"3/31/2008\",0)");
Assert.IsTrue(XLHelper.AreEqual(0.25, (double) actual));
}
[Test]
public void Yearfrac_1_base1()
{
Object actual = XLWorkbook.EvaluateExpr("Yearfrac(\"1/1/2008\", \"3/31/2008\",1)");
Assert.IsTrue(XLHelper.AreEqual(0.24590163934426229, (double) actual));
}
[Test]
public void Yearfrac_1_base2()
{
Object actual = XLWorkbook.EvaluateExpr("Yearfrac(\"1/1/2008\", \"3/31/2008\",2)");
Assert.IsTrue(XLHelper.AreEqual(0.25, (double) actual));
}
[Test]
public void Yearfrac_1_base3()
{
Object actual = XLWorkbook.EvaluateExpr("Yearfrac(\"1/1/2008\", \"3/31/2008\",3)");
Assert.IsTrue(XLHelper.AreEqual(0.24657534246575341, (double) actual));
}
[Test]
public void Yearfrac_1_base4()
{
Object actual = XLWorkbook.EvaluateExpr("Yearfrac(\"1/1/2008\", \"3/31/2008\",4)");
Assert.IsTrue(XLHelper.AreEqual(0.24722222222222223, (double) actual));
}
[Test]
public void Yearfrac_2_base0()
{
Object actual = XLWorkbook.EvaluateExpr("Yearfrac(\"1/1/2008\", \"3/31/2013\",0)");
Assert.IsTrue(XLHelper.AreEqual(5.25, (double) actual));
}
[Test]
public void Yearfrac_2_base1()
{
Object actual = XLWorkbook.EvaluateExpr("Yearfrac(\"1/1/2008\", \"3/31/2013\",1)");
Assert.IsTrue(XLHelper.AreEqual(5.24452554744526, (double) actual));
}
[Test]
public void Yearfrac_2_base2()
{
Object actual = XLWorkbook.EvaluateExpr("Yearfrac(\"1/1/2008\", \"3/31/2013\",2)");
Assert.IsTrue(XLHelper.AreEqual(5.32222222222222, (double) actual));
}
[Test]
public void Yearfrac_2_base3()
{
Object actual = XLWorkbook.EvaluateExpr("Yearfrac(\"1/1/2008\", \"3/31/2013\",3)");
Assert.IsTrue(XLHelper.AreEqual(5.24931506849315, (double) actual));
}
[Test]
public void Yearfrac_2_base4()
{
Object actual = XLWorkbook.EvaluateExpr("Yearfrac(\"1/1/2008\", \"3/31/2013\",4)");
Assert.IsTrue(XLHelper.AreEqual(5.24722222222222, (double) actual));
}
}
}
| |
using System;
using System.IO;
using System.CodeDom;
namespace Stetic
{
public enum ImageSource
{
Theme,
Resource,
File
}
public class ImageInfo
{
ImageSource source;
string name;
Gtk.IconSize size;
Gdk.Pixbuf image;
private ImageInfo ()
{
}
public string Label {
get {
if (source == ImageSource.File)
return Path.GetFileName (name);
else
return name;
}
}
public string Name {
get { return name; }
}
public Gtk.IconSize ThemeIconSize {
get { return size; }
}
public ImageSource Source {
get { return source; }
}
public override string ToString ()
{
if (source == ImageSource.Theme)
return "stock:" + name + " " + size;
else if (source == ImageSource.Resource)
return "resource:" + name;
else
return "file:" + name;
}
public static ImageInfo FromResource (string resourceName)
{
ImageInfo info = new ImageInfo ();
info.name = resourceName;
info.source = ImageSource.Resource;
return info;
}
public static ImageInfo FromTheme (string iconId, Gtk.IconSize size)
{
ImageInfo info = new ImageInfo ();
info.name = iconId;
info.size = size;
info.source = ImageSource.Theme;
return info;
}
public static ImageInfo FromFile (string file)
{
ImageInfo info = new ImageInfo ();
info.name = file;
info.source = ImageSource.File;
return info;
}
public static ImageInfo FromString (string str)
{
ImageInfo info = new ImageInfo ();
if (str.StartsWith ("resource:")) {
info.source = ImageSource.Resource;
info.name = str.Substring (9);
} else if (str.StartsWith ("stock:")) {
info.source = ImageSource.Theme;
string[] s = str.Substring (6).Split (' ');
if (s.Length != 2)
return null;
info.name = s[0];
info.size = (Gtk.IconSize) Enum.Parse (typeof(Gtk.IconSize), s[1]);
} else if (str.StartsWith ("file:")) {
info.source = ImageSource.File;
info.name = str.Substring (5);
} else
return null;
return info;
}
public Gdk.Pixbuf GetImage (IProject project)
{
if (image != null)
return image;
switch (source) {
case ImageSource.Resource:
if (project.ResourceProvider == null)
return null;
System.IO.Stream s = project.ResourceProvider.GetResourceStream (name);
if (s == null)
return null;
try {
return image = new Gdk.Pixbuf (s);
} catch {
// Not a valid image
return WidgetUtils.MissingIcon;
}
case ImageSource.Theme:
return image = WidgetUtils.LoadIcon (name, size);
case ImageSource.File:
try {
string file = Path.Combine (project.ImagesRootPath, name);
return image = new Gdk.Pixbuf (file);
} catch {
return WidgetUtils.MissingIcon;
}
}
return null;
}
public Gdk.Pixbuf GetThumbnail (IProject project, int thumbnailSize)
{
Gdk.Pixbuf pix = GetImage (project);
if (pix == null)
return null;
if (pix.Width >= pix.Height && pix.Width > thumbnailSize) {
return ScaleImage (pix, thumbnailSize, thumbnailSize);
} else if (pix.Height > pix.Width && pix.Height > thumbnailSize) {
return ScaleImage (pix, thumbnailSize, thumbnailSize);
}
return pix;
}
public Gdk.Pixbuf GetScaledImage (IProject project, Gtk.IconSize size)
{
int w, h;
Gtk.Icon.SizeLookup (size, out w, out h);
return GetScaledImage (project, w, h);
}
public Gdk.Pixbuf GetScaledImage (IProject project, int width, int height)
{
Gdk.Pixbuf pix = GetImage (project);
if (pix == null)
return null;
else
return ScaleImage (pix, width, height);
}
Gdk.Pixbuf ScaleImage (Gdk.Pixbuf pix, int width, int height)
{
if ((pix.Width - width) > (pix.Height - height)) {
if (pix.Width != width) {
float prop = (float) pix.Height / (float) pix.Width;
return pix.ScaleSimple (width, (int)(width * prop), Gdk.InterpType.Bilinear);
}
} else {
if (pix.Height != height) {
float prop = (float) pix.Width / (float) pix.Height;
return pix.ScaleSimple ((int)(height * prop), height, Gdk.InterpType.Bilinear);
}
}
return pix;
}
public CodeExpression ToCodeExpression (GeneratorContext ctx)
{
switch (source) {
case ImageSource.Resource:
return new CodeMethodInvokeExpression (
new CodeTypeReferenceExpression (typeof(Gdk.Pixbuf)),
"LoadFromResource",
new CodePrimitiveExpression (name)
);
case ImageSource.Theme:
return ctx.GenerateLoadPixbuf (name, size);
case ImageSource.File:
return new CodeObjectCreateExpression (
typeof(Gdk.Pixbuf),
new CodeMethodInvokeExpression (
new CodeTypeReferenceExpression (typeof(System.IO.Path)),
"Combine",
new CodePropertyReferenceExpression (
new CodePropertyReferenceExpression (
new CodeTypeReferenceExpression (typeof(AppDomain)),
"CurrentDomain"
),
"BaseDirectory"
),
new CodePrimitiveExpression (name)
)
);
}
return new CodePrimitiveExpression (null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Stress.Data
{
public class DataStressConnection : IDisposable
{
public DbConnection DbConnection { get; private set; }
private readonly bool _clearPoolBeforeClose;
public DataStressConnection(DbConnection conn, bool clearPoolBeforeClose = false)
{
if (conn == null)
throw new ArgumentException("Cannot pass in null DbConnection to make new DataStressConnection!");
this.DbConnection = conn;
_clearPoolBeforeClose = clearPoolBeforeClose;
}
private short _spid = 0;
[ThreadStatic]
private static TrackedRandom s_randomInstance;
private static TrackedRandom RandomInstance
{
get
{
if (s_randomInstance == null)
s_randomInstance = new TrackedRandom();
return s_randomInstance;
}
}
public void Open()
{
bool sync = RandomInstance.NextBool();
if (sync)
{
OpenSync();
}
else
{
Task t = OpenAsync();
AsyncUtils.WaitAndUnwrapException(t);
}
}
public async Task OpenAsync()
{
int startMilliseconds = Environment.TickCount;
try
{
await DbConnection.OpenAsync();
}
catch (ObjectDisposedException e)
{
HandleObjectDisposedException(e, true);
throw;
}
catch (InvalidOperationException e)
{
int endMilliseconds = Environment.TickCount;
// we may be able to handle this exception
HandleInvalidOperationException(e, startMilliseconds, endMilliseconds, true);
throw;
}
GetSpid();
}
private void OpenSync()
{
int startMilliseconds = Environment.TickCount;
try
{
DbConnection.Open();
}
catch (ObjectDisposedException e)
{
HandleObjectDisposedException(e, false);
throw;
}
catch (InvalidOperationException e)
{
int endMilliseconds = Environment.TickCount;
// we may be able to handle this exception
HandleInvalidOperationException(e, startMilliseconds, endMilliseconds, false);
throw;
}
GetSpid();
}
private void HandleObjectDisposedException(ObjectDisposedException e, bool async)
{
// Race condition in DbConnectionFactory.TryGetConnection results in an ObjectDisposedException when calling OpenAsync on a non-pooled connection
string methodName = async ? "OpenAsync()" : "Open()";
throw DataStressErrors.ProductError(
"Hit ObjectDisposedException in SqlConnection." + methodName, e);
}
private static int s_fastTimeoutCountOpen; // number of times hit by SqlConnection.Open
private static int s_fastTimeoutCountOpenAsync; // number of times hit by SqlConnection.OpenAsync
private static readonly DateTime s_startTime = DateTime.Now;
private const int MaxFastTimeoutCountPerDay = 200;
/// <summary>
/// Handles InvalidOperationException generated from Open or OpenAsync calls.
/// For any other type of Exception, it simply returns
/// </summary>
private void HandleInvalidOperationException(InvalidOperationException e, int startMilliseconds, int endMilliseconds, bool async)
{
int elapsedMilliseconds = unchecked(endMilliseconds - startMilliseconds); // unchecked to handle overflow of Environment.TickCount
// Since InvalidOperationExceptions due to timeout can be caused by issues
// (e.g. network hiccup, server unavailable, etc) we need a heuristic to guess whether or not this exception
// should have happened or not.
bool wasTimeoutFromPool = (e.GetType() == typeof(InvalidOperationException)) &&
(e.Message.StartsWith("Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool"));
bool wasTooEarly = (elapsedMilliseconds < ((DbConnection.ConnectionTimeout - 5) * 1000));
if (wasTimeoutFromPool && wasTooEarly)
{
if (async)
Interlocked.Increment(ref s_fastTimeoutCountOpenAsync);
else
Interlocked.Increment(ref s_fastTimeoutCountOpen);
}
}
/// <summary>
/// Gets spid value.
/// </summary>
/// <remarks>
/// If we want to kill the connection, we get its spid up front before the test case uses the connection. Otherwise if
/// we try to get the spid when KillConnection is called, then the connection could be in a bad state (e.g. enlisted in
/// aborted transaction, or has open datareader) and we will fail to get the spid. Also the randomization is put here
/// instead of in KillConnection because otherwise this method would execute a command for every single connection which
/// most of the time will not be used later.
/// </remarks>
private void GetSpid()
{
if (DbConnection is System.Data.SqlClient.SqlConnection && RandomInstance.Next(0, 20) == 0)
{
using (var cmd = DbConnection.CreateCommand())
{
cmd.CommandText = "select @@spid";
_spid = (short)cmd.ExecuteScalar();
}
}
else
{
_spid = 0;
}
}
/// <summary>
/// Kills the given connection using "kill [spid]" if the parameter is nonzero
/// </summary>
private void KillConnection()
{
DataStressErrors.Assert(_spid != 0, "Called KillConnection with spid != 0");
using (var killerConn = DataTestGroup.Factory.CreateConnection())
{
killerConn.Open();
using (var killerCmd = killerConn.CreateCommand())
{
killerCmd.CommandText = "begin try kill " + _spid + " end try begin catch end catch";
killerCmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// Kills the given connection using "kill [spid]" if the parameter is nonzero
/// </summary>
/// <returns>a Task that is asynchronously killing the connection, or null if the connection is not being killed</returns>
public Task KillConnectionAsync()
{
if (_spid == 0)
return null;
else
return Task.Factory.StartNew(() => KillConnection());
}
public void Close()
{
if (_spid != 0)
{
KillConnection();
// Wait before putting the connection back in the pool, to ensure that
// the pool checks the connection the next time it is used.
Task.Delay(10).ContinueWith((t) => DbConnection.Close());
}
else
{
// If this is a SqlConnection, and it is a connection with a unique connection string that we will never use again,
// then call SqlConnection.ClearPool() before closing so that it is fully closed and does not waste client & server resources.
if (_clearPoolBeforeClose)
{
SqlConnection sqlConn = DbConnection as SqlConnection;
if (sqlConn != null) SqlConnection.ClearPool(sqlConn);
}
DbConnection.Close();
}
}
public void Dispose()
{
Close();
}
public DbCommand CreateCommand()
{
return DbConnection.CreateCommand();
}
}
}
| |
/*
* 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 OpenMetaverse;
using System;
namespace OpenSim.Framework
{
/// <summary>
/// Information about a particular user known to the userserver
/// </summary>
public class UserProfileData
{
/// <summary>
/// A UNIX Timestamp (seconds since epoch) for the users creation
/// </summary>
private int m_created;
/// <summary>
/// The users last registered agent (filled in on the user server)
/// </summary>
private UserAgentData m_currentAgent;
/// <summary>
/// The first component of a users account name
/// </summary>
private string m_firstname;
/// <summary>
/// The coordinates inside the region of the home location
/// </summary>
private Vector3 m_homeLocation;
/// <summary>
/// Where the user will be looking when they rez.
/// </summary>
private Vector3 m_homeLookAt;
private uint m_homeRegionX;
private uint m_homeRegionY;
/// <summary>
/// The ID value for this user
/// </summary>
private UUID m_id;
/// <summary>
/// A UNIX Timestamp for the users last login date / time
/// </summary>
private int m_lastLogin;
/// <summary>
/// A salted hash containing the users password, in the format md5(md5(password) + ":" + salt)
/// </summary>
/// <remarks>This is double MD5'd because the client sends an unsalted MD5 to the loginserver</remarks>
private string m_passwordHash;
/// <summary>
/// The salt used for the users hash, should be 32 bytes or longer
/// </summary>
private string m_passwordSalt;
/// <summary>
/// The about text listed in a users profile.
/// </summary>
private string m_profileAboutText = String.Empty;
/// <summary>
/// A uint mask containing the "I can do" fields of the users profile
/// </summary>
private uint m_profileCanDoMask;
/// <summary>
/// The profile image for the users first life tab
/// </summary>
private UUID m_profileFirstImage;
/// <summary>
/// The first life about text listed in a users profile
/// </summary>
private string m_profileFirstText = String.Empty;
/// <summary>
/// The profile image for an avatar stored on the asset server
/// </summary>
private UUID m_profileImage;
/// <summary>
/// A uint mask containing the "I want to do" part of the users profile
/// </summary>
private uint m_profileWantDoMask; // Profile window "I want to" mask
/// <summary>
/// The profile url for an avatar
/// </summary>
private string m_profileUrl;
/// <summary>
/// The second component of a users account name
/// </summary>
private string m_surname;
/// <summary>
/// A valid email address for the account. Useful for password reset requests.
/// </summary>
private string m_email = String.Empty;
/// <summary>
/// A URI to the users asset server, used for foreigners and large grids.
/// </summary>
private string m_userAssetUri = String.Empty;
/// <summary>
/// A URI to the users inventory server, used for foreigners and large grids
/// </summary>
private string m_userInventoryUri = String.Empty;
/// <summary>
/// The last used Web_login_key
/// </summary>
private UUID m_webLoginKey;
// Data for estates and other goodies
// to get away from per-machine configs a little
//
private int m_userFlags;
private int m_godLevel;
private string m_customType;
private UUID m_partner;
/// <summary>
/// The regionhandle of the users preferred home region. If
/// multiple sims occupy the same spot, the grid may decide
/// which region the user logs into
/// </summary>
public virtual ulong HomeRegion
{
get
{
return Util.RegionWorldLocToHandle(Util.RegionToWorldLoc(m_homeRegionX), Util.RegionToWorldLoc(m_homeRegionY));
// return Utils.UIntsToLong( m_homeRegionX * (uint)Constants.RegionSize, m_homeRegionY * (uint)Constants.RegionSize);
}
set
{
uint regionWorldLocX, regionWorldLocY;
Util.RegionHandleToWorldLoc(value, out regionWorldLocX, out regionWorldLocY);
m_homeRegionX = Util.WorldToRegionLoc(regionWorldLocX);
m_homeRegionY = Util.WorldToRegionLoc(regionWorldLocY);
// m_homeRegionX = (uint) (value >> 40);
// m_homeRegionY = (((uint) (value)) >> 8);
}
}
private UUID m_homeRegionId;
/// <summary>
/// The regionID of the users home region. This is unique;
/// even if the position of the region changes within the
/// grid, this will refer to the same region.
/// </summary>
public UUID HomeRegionID
{
get { return m_homeRegionId; }
set { m_homeRegionId = value; }
}
// Property wrappers
public UUID ID
{
get { return m_id; }
set { m_id = value; }
}
public UUID WebLoginKey
{
get { return m_webLoginKey; }
set { m_webLoginKey = value; }
}
public string FirstName
{
get { return m_firstname; }
set { m_firstname = value; }
}
public string SurName
{
get { return m_surname; }
set { m_surname = value; }
}
/// <value>
/// The concatentation of the various name components.
/// </value>
public string Name
{
get { return String.Format("{0} {1}", m_firstname, m_surname); }
}
public string Email
{
get { return m_email; }
set { m_email = value; }
}
public string PasswordHash
{
get { return m_passwordHash; }
set { m_passwordHash = value; }
}
public string PasswordSalt
{
get { return m_passwordSalt; }
set { m_passwordSalt = value; }
}
public uint HomeRegionX
{
get { return m_homeRegionX; }
set { m_homeRegionX = value; }
}
public uint HomeRegionY
{
get { return m_homeRegionY; }
set { m_homeRegionY = value; }
}
public Vector3 HomeLocation
{
get { return m_homeLocation; }
set { m_homeLocation = value; }
}
// for handy serialization
public float HomeLocationX
{
get { return m_homeLocation.X; }
set { m_homeLocation.X = value; }
}
public float HomeLocationY
{
get { return m_homeLocation.Y; }
set { m_homeLocation.Y = value; }
}
public float HomeLocationZ
{
get { return m_homeLocation.Z; }
set { m_homeLocation.Z = value; }
}
public Vector3 HomeLookAt
{
get { return m_homeLookAt; }
set { m_homeLookAt = value; }
}
// for handy serialization
public float HomeLookAtX
{
get { return m_homeLookAt.X; }
set { m_homeLookAt.X = value; }
}
public float HomeLookAtY
{
get { return m_homeLookAt.Y; }
set { m_homeLookAt.Y = value; }
}
public float HomeLookAtZ
{
get { return m_homeLookAt.Z; }
set { m_homeLookAt.Z = value; }
}
public int Created
{
get { return m_created; }
set { m_created = value; }
}
public int LastLogin
{
get { return m_lastLogin; }
set { m_lastLogin = value; }
}
public string UserInventoryURI
{
get { return m_userInventoryUri; }
set { m_userInventoryUri = value; }
}
public string UserAssetURI
{
get { return m_userAssetUri; }
set { m_userAssetUri = value; }
}
public uint CanDoMask
{
get { return m_profileCanDoMask; }
set { m_profileCanDoMask = value; }
}
public uint WantDoMask
{
get { return m_profileWantDoMask; }
set { m_profileWantDoMask = value; }
}
public string AboutText
{
get { return m_profileAboutText; }
set { m_profileAboutText = value; }
}
public string FirstLifeAboutText
{
get { return m_profileFirstText; }
set { m_profileFirstText = value; }
}
public string ProfileUrl
{
get { return m_profileUrl; }
set { m_profileUrl = value; }
}
public UUID Image
{
get { return m_profileImage; }
set { m_profileImage = value; }
}
public UUID FirstLifeImage
{
get { return m_profileFirstImage; }
set { m_profileFirstImage = value; }
}
public UserAgentData CurrentAgent
{
get { return m_currentAgent; }
set { m_currentAgent = value; }
}
public int UserFlags
{
get { return m_userFlags; }
set { m_userFlags = value; }
}
public int GodLevel
{
get { return m_godLevel; }
set { m_godLevel = value; }
}
public string CustomType
{
get { return m_customType; }
set { m_customType = value; }
}
public UUID Partner
{
get { return m_partner; }
set { m_partner = value; }
}
}
}
| |
/*
* HybridDictionary.cs - Implementation of
* "System.Collections.Specialized.HybridDictionary".
*
* Copyright (C) 2002 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.Collections.Specialized
{
#if !ECMA_COMPAT
using System;
using System.Collections;
using System.Globalization;
public class HybridDictionary : IDictionary, ICollection, IEnumerable
{
// Internal state. The object starts off as a list dictionary
// and then switches to a hash table when the number of elements
// exceeds "SwitchOverSize".
private ListDictionary list;
private Hashtable hash;
private bool caseInsensitive;
// The size at which we switch over.
private const int SwitchOverSize = 8;
// Constructors.
public HybridDictionary() : this(0, false) {}
public HybridDictionary(bool caseInsensitive)
: this(0, caseInsensitive) {}
public HybridDictionary(int initialSize)
: this(initialSize, false) {}
public HybridDictionary(int initialSize, bool caseInsensitive)
{
this.caseInsensitive = caseInsensitive;
if(initialSize > SwitchOverSize)
{
SwitchOver(initialSize);
}
else
{
list = new ListDictionary();
}
}
// Switch over to the hash table implementation.
private void SwitchOver(int size)
{
if(caseInsensitive)
{
hash = new Hashtable
(size, new CaseInsensitiveHashCodeProvider
(CultureInfo.InvariantCulture),
new CaseInsensitiveComparer
(CultureInfo.InvariantCulture));
}
else
{
hash = new Hashtable(size);
}
if(list != null)
{
IDictionaryEnumerator e = list.GetEnumerator();
while(e.MoveNext())
{
hash.Add(e.Key, e.Value);
}
list = null;
}
}
// Implement the ICollection interface.
public void CopyTo(Array array, int index)
{
if(hash != null)
{
hash.CopyTo(array, index);
}
else
{
list.CopyTo(array, index);
}
}
public int Count
{
get
{
if(hash != null)
{
return hash.Count;
}
else
{
return list.Count;
}
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public Object SyncRoot
{
get
{
return this;
}
}
// Implement the IDictionary interface.
public void Add(Object key, Object value)
{
if(hash != null)
{
hash.Add(key, value);
}
else if(list.Count < SwitchOverSize)
{
list.Add(key, value);
}
else
{
SwitchOver(SwitchOverSize + 1);
hash.Add(key, value);
}
}
public void Clear()
{
if(hash != null)
{
hash.Clear();
hash = null;
list = new ListDictionary();
}
else if(list != null)
{
list.Clear();
}
}
public bool Contains(Object key)
{
if(hash != null)
{
return hash.Contains(key);
}
else
{
return list.Contains(key);
}
}
public IDictionaryEnumerator GetEnumerator()
{
if(hash != null)
{
return hash.GetEnumerator();
}
else
{
return list.GetEnumerator();
}
}
public void Remove(Object key)
{
if(hash != null)
{
hash.Remove(key);
}
else
{
list.Remove(key);
}
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public Object this[Object key]
{
get
{
if(hash != null)
{
return hash[key];
}
else
{
return list[key];
}
}
set
{
if(hash != null)
{
hash[key] = value;
}
else
{
list[key] = value;
}
}
}
public ICollection Keys
{
get
{
if(hash != null)
{
return hash.Keys;
}
else
{
return list.Keys;
}
}
}
public ICollection Values
{
get
{
if(hash != null)
{
return hash.Values;
}
else
{
return list.Values;
}
}
}
// Implement the IEnumerable interface.
IEnumerator IEnumerable.GetEnumerator()
{
if(hash != null)
{
return ((IEnumerable)hash).GetEnumerator();
}
else
{
return ((IEnumerable)list).GetEnumerator();
}
}
}; // class HybridDictionary
#endif // !ECMA_COMPAT
}; // namespace System.Collections.Specialized
| |
// 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.
/*============================================================
**
**
**
**
** Purpose: Create a Memorystream over an UnmanagedMemoryStream
**
===========================================================*/
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
// Needed for backwards compatibility with V1.x usages of the
// ResourceManager, where a MemoryStream is now returned as an
// UnmanagedMemoryStream from ResourceReader.
internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream
{
private UnmanagedMemoryStream _unmanagedStream;
internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream)
{
_unmanagedStream = stream;
}
public override bool CanRead
{
get { return _unmanagedStream.CanRead; }
}
public override bool CanSeek
{
get { return _unmanagedStream.CanSeek; }
}
public override bool CanWrite
{
get { return _unmanagedStream.CanWrite; }
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
_unmanagedStream.Dispose();
}
finally
{
base.Dispose(disposing);
}
}
public override void Flush()
{
_unmanagedStream.Flush();
}
public override byte[] GetBuffer()
{
throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
}
public override bool TryGetBuffer(out ArraySegment<byte> buffer)
{
buffer = default;
return false;
}
public override int Capacity
{
get
{
return (int)_unmanagedStream.Capacity;
}
set
{
throw new IOException(SR.IO_FixedCapacity);
}
}
public override long Length
{
get
{
return _unmanagedStream.Length;
}
}
public override long Position
{
get
{
return _unmanagedStream.Position;
}
set
{
_unmanagedStream.Position = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return _unmanagedStream.Read(buffer, offset, count);
}
public override int Read(Span<byte> buffer)
{
return _unmanagedStream.Read(buffer);
}
public override int ReadByte()
{
return _unmanagedStream.ReadByte();
}
public override long Seek(long offset, SeekOrigin loc)
{
return _unmanagedStream.Seek(offset, loc);
}
public unsafe override byte[] ToArray()
{
byte[] buffer = new byte[_unmanagedStream.Length];
_unmanagedStream.Read(buffer, 0, (int)_unmanagedStream.Length);
return buffer;
}
public override void Write(byte[] buffer, int offset, int count)
{
_unmanagedStream.Write(buffer, offset, count);
}
public override void Write(ReadOnlySpan<byte> buffer)
{
_unmanagedStream.Write(buffer);
}
public override void WriteByte(byte value)
{
_unmanagedStream.WriteByte(value);
}
// Writes this MemoryStream to another stream.
public unsafe override void WriteTo(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
byte[] buffer = ToArray();
stream.Write(buffer, 0, buffer.Length);
}
public override void SetLength(long value)
{
// This was probably meant to call _unmanagedStream.SetLength(value), but it was forgotten in V.4.0.
// Now this results in a call to the base which touches the underlying array which is never actually used.
// We cannot fix it due to compat now, but we should fix this at the next SxS release oportunity.
base.SetLength(value);
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// The parameter checks must be in sync with the base version:
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
if (!CanRead && !CanWrite)
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
if (!destination.CanRead && !destination.CanWrite)
throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed);
if (!CanRead)
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
if (!destination.CanWrite)
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
return _unmanagedStream.CopyToAsync(destination, bufferSize, cancellationToken);
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return _unmanagedStream.FlushAsync(cancellationToken);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken);
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
return _unmanagedStream.ReadAsync(buffer, cancellationToken);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken);
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
return _unmanagedStream.WriteAsync(buffer, cancellationToken);
}
} // class UnmanagedMemoryStreamWrapper
} // namespace
| |
#region License
//
// Author: Ivan Porto Carrero <ivan@flanders.co.nz>
// Copyright (c) 2008, Flanders International Marketing Ltd.
// Copyright (c) 2007-2008, Enkari, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
#region Usings
using System;
using Ninject.Core.Logging;
using NLog;
#endregion
namespace Ninject.Integration.NLog.Infrastructure
{
/// <summary>
/// A logger that integrates with nlog, passing all messages to a <see cref="Logger"/>.
/// </summary>
public class NLogLogger : LoggerBase
{
private readonly Logger _nlogLogger;
/// <summary>
/// Gets a value indicating whether messages with Debug severity should be logged.
/// </summary>
public override bool IsDebugEnabled
{
get { return _nlogLogger.IsDebugEnabled; }
}
/// <summary>
/// Gets a value indicating whether messages with Info severity should be logged.
/// </summary>
public override bool IsInfoEnabled
{
get { return _nlogLogger.IsInfoEnabled; }
}
/// <summary>
/// Gets a value indicating whether messages with Warn severity should be logged.
/// </summary>
public override bool IsWarnEnabled
{
get { return _nlogLogger.IsWarnEnabled; }
}
/// <summary>
/// Gets a value indicating whether messages with Error severity should be logged.
/// </summary>
public override bool IsErrorEnabled
{
get { return _nlogLogger.IsErrorEnabled; }
}
/// <summary>
/// Gets a value indicating whether messages with Fatal severity should be logged.
/// </summary>
public override bool IsFatalEnabled
{
get { return _nlogLogger.IsFatalEnabled; }
}
/// <summary>
/// Initializes a new instance of the <see cref="NLogLogger"/> class.
/// </summary>
/// <param name="type">The type to associate with the logger.</param>
public NLogLogger(Type type)
: base(type)
{
_nlogLogger = LogManager.GetLogger(type.FullName);
}
/// <summary>
/// Logs the specified exception with Debug severity.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
#if !MONO
public override void Debug(Exception exception, string format, object[] args)
#else
public override void Debug(Exception exception, string format, params object[] args)
#endif
{
_nlogLogger.DebugException(string.Format(format, args), exception);
}
/// <summary>
/// Logs the specified message with Debug severity.
/// </summary>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
#if !MONO
public override void Debug(string format, object[] args)
#else
public override void Debug(string format, params object[] args)
#endif
{
_nlogLogger.Debug(format, args);
}
/// <summary>
/// Logs the specified exception with Error severity.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
#if !MONO
public override void Error(Exception exception, string format, object[] args)
#else
public override void Error(Exception exception, string format, params object[] args)
#endif
{
_nlogLogger.ErrorException(string.Format(format, args), exception);
}
/// <summary>
/// Logs the specified message with Error severity.
/// </summary>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
#if !MONO
public override void Error(string format, object[] args)
#else
public override void Error(string format, params object[] args)
#endif
{
_nlogLogger.Error(format, args);
}
/// <summary>
/// Logs the specified message with Fatal severity.
/// </summary>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
#if !MONO
public override void Fatal(string format, object[] args)
#else
public override void Fatal(string format, params object[] args)
#endif
{
_nlogLogger.Fatal(format, args);
}
/// <summary>
/// Logs the specified exception with Fatal severity.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
#if !MONO
public override void Fatal(Exception exception, string format, object[] args)
#else
public override void Fatal(Exception exception, string format, params object[] args)
#endif
{
_nlogLogger.FatalException(string.Format(format, args), exception);
}
/// <summary>
/// Logs the specified message with Info severity.
/// </summary>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
#if !MONO
public override void Info(string format, object[] args)
#else
public override void Info(string format, params object[] args)
#endif
{
_nlogLogger.Info(format, args);
}
/// <summary>
/// Logs the specified exception with Info severity.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
#if !MONO
public override void Info(Exception exception, string format, object[] args)
#else
public override void Info(Exception exception, string format, params object[] args)
#endif
{
_nlogLogger.InfoException(string.Format(format, args), exception);
}
/// <summary>
/// Logs the specified message with Warn severity.
/// </summary>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
#if !MONO
public override void Warn(string format, object[] args)
#else
public override void Warn(string format, params object[] args)
#endif
{
_nlogLogger.Warn(format, args);
}
/// <summary>
/// Logs the specified exception with Warn severity.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
#if !MONO
public override void Warn(Exception exception, string format, object[] args)
#else
public override void Warn(Exception exception, string format, params object[] args)
#endif
{
_nlogLogger.WarnException(string.Format(format, args), exception);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using VSPropertyPages;
using Cosmos.Build.Common;
using DebugMode = Cosmos.Build.Common.DebugMode;
using System.IO;
using System.Diagnostics;
namespace Cosmos.VS.ProjectSystem.VS.PropertyPages
{
internal partial class OldCosmosPropertyPageControl : WinFormsPropertyPageUI
{
protected class ProfileItem
{
public string Prefix;
public string Name;
public bool IsPreset;
public override string ToString() => Name;
}
private OldCosmosPropertyPageViewModel mViewModel;
protected ProfilePresets mPresets = new ProfilePresets();
protected int mVMwareAndBochsDebugPipe;
protected int mHyperVDebugPipe;
protected bool mShowTabBochs;
protected bool mShowTabQemu;
protected bool mShowTabDebug;
protected bool mShowTabDeployment;
protected bool mShowTabLaunch;
protected bool mShowTabVMware;
protected bool mShowTabHyperV;
protected bool mShowTabPXE;
protected bool mShowTabUSB;
protected bool mShowTabISO;
protected bool mShowTabSlave;
protected bool FreezeEvents;
public OldCosmosPropertyPageControl(OldCosmosPropertyPageViewModel aViewModel)
{
InitializeComponent();
mViewModel = aViewModel;
#region Profile
butnProfileClone.Click += new EventHandler(butnProfileClone_Click);
butnProfileDelete.Click += new EventHandler(butnProfileDelete_Click);
butnProfileRename.Click += new EventHandler(butnProfileRename_Click);
lboxProfile.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
var xProfile = (ProfileItem)lboxProfile.SelectedItem;
if (xProfile.Prefix != mViewModel.BuildProperties.Profile)
{
// Save existing profile
mViewModel.BuildProperties.SaveProfile(mViewModel.BuildProperties.Profile);
// Load newly selected profile
mViewModel.BuildProperties.LoadProfile(xProfile.Prefix);
mViewModel.BuildProperties.Profile = xProfile.Prefix;
UpdateUI();
}
};
#endregion
# region Deploy
lboxDeployment.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
var xValue = (DeploymentType)((EnumValue)lboxDeployment.SelectedItem).Value;
if (xValue != mViewModel.BuildProperties.Deployment)
{
mViewModel.BuildProperties.Deployment = xValue;
}
};
#endregion
# region Launch
lboxLaunch.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
var xValue = (LaunchType)((EnumValue)lboxLaunch.SelectedItem).Value;
if (xValue != mViewModel.BuildProperties.Launch)
{
mViewModel.BuildProperties.Launch = xValue;
// Bochs and Qemu requires an ISO. Force Deployment property.
if (xValue == LaunchType.Bochs)
{
if (DeploymentType.ISO != mViewModel.BuildProperties.Deployment)
{
foreach (EnumValue scannedValue in lboxDeployment.Items)
{
if (DeploymentType.ISO == (DeploymentType)scannedValue.Value)
{
lboxDeployment.SelectedItem = scannedValue;
break;
}
}
}
}
}
};
#endregion
#region Compile
comboFramework.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
var value = (Framework)((EnumValue)comboFramework.SelectedItem).Value;
if (value != mViewModel.BuildProperties.Framework)
{
mViewModel.BuildProperties.Framework = value;
}
};
comboBinFormat.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
var value = (BinFormat)((EnumValue)comboBinFormat.SelectedItem).Value;
if (value != mViewModel.BuildProperties.BinFormat)
{
mViewModel.BuildProperties.BinFormat = value;
}
};
#endregion
#region Assembler
checkUseInternalAssembler.CheckedChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
bool value = checkUseInternalAssembler.Checked;
if (value != mViewModel.BuildProperties.UseInternalAssembler)
{
mViewModel.BuildProperties.UseInternalAssembler = value;
}
};
#endregion
#region VMware
cmboVMwareEdition.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (VMwareEdition)((EnumValue)cmboVMwareEdition.SelectedItem).Value;
if (x != mViewModel.BuildProperties.VMwareEdition)
{
mViewModel.BuildProperties.VMwareEdition = x;
}
};
#endregion
#region PXE
comboPxeInterface.TextChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = comboPxeInterface.Text.Trim();
if (x != mViewModel.BuildProperties.PxeInterface)
{
mViewModel.BuildProperties.PxeInterface = x;
}
};
cmboSlavePort.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (string)cmboSlavePort.SelectedItem;
if (x != mViewModel.BuildProperties.SlavePort)
{
mViewModel.BuildProperties.SlavePort = x;
}
};
butnPxeRefresh.Click += new EventHandler(butnPxeRefresh_Click);
#endregion
#region Debug
comboDebugMode.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (DebugMode)((EnumValue)comboDebugMode.SelectedItem).Value;
if (x != mViewModel.BuildProperties.DebugMode)
{
mViewModel.BuildProperties.DebugMode = x;
}
};
chckEnableDebugStub.CheckedChanged += delegate (object aSender, EventArgs e)
{
if (FreezeEvents) return;
panlDebugSettings.Enabled = chckEnableDebugStub.Checked;
mViewModel.BuildProperties.DebugEnabled = chckEnableDebugStub.Checked;
};
comboTraceMode.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (TraceAssemblies)((EnumValue)comboTraceMode.SelectedItem).Value;
if (x != mViewModel.BuildProperties.TraceAssemblies)
{
mViewModel.BuildProperties.TraceAssemblies = x;
}
};
checkIgnoreDebugStubAttribute.CheckedChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
bool x = checkIgnoreDebugStubAttribute.Checked;
if (x != mViewModel.BuildProperties.IgnoreDebugStubAttribute)
{
mViewModel.BuildProperties.IgnoreDebugStubAttribute = x;
}
};
cmboCosmosDebugPort.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (string)cmboCosmosDebugPort.SelectedItem;
if (x != mViewModel.BuildProperties.CosmosDebugPort)
{
mViewModel.BuildProperties.CosmosDebugPort = x;
}
};
cmboVisualStudioDebugPort.SelectedIndexChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (string)cmboVisualStudioDebugPort.SelectedItem;
if (x != mViewModel.BuildProperties.VisualStudioDebugPort)
{
mViewModel.BuildProperties.VisualStudioDebugPort = x;
}
};
checkEnableGDB.CheckedChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
bool x = checkEnableGDB.Checked;
if (x != mViewModel.BuildProperties.EnableGDB)
{
mViewModel.BuildProperties.EnableGDB = x;
}
checkStartCosmosGDB.Enabled = x;
checkStartCosmosGDB.Checked = x;
};
checkStartCosmosGDB.CheckedChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
bool x = checkStartCosmosGDB.Checked;
if (x != mViewModel.BuildProperties.StartCosmosGDB)
{
mViewModel.BuildProperties.StartCosmosGDB = x;
}
};
checkEnableBochsDebug.CheckedChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
bool x = checkEnableBochsDebug.Checked;
if (x != mViewModel.BuildProperties.EnableBochsDebug)
{
mViewModel.BuildProperties.EnableBochsDebug = x;
}
checkStartBochsDebugGui.Enabled = x;
if (x == false)
{
checkStartBochsDebugGui.Checked = x;
}
};
checkStartBochsDebugGui.CheckedChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
bool x = checkStartBochsDebugGui.Checked;
if (x != mViewModel.BuildProperties.StartBochsDebugGui)
{
mViewModel.BuildProperties.StartBochsDebugGui = x;
}
};
checkBoxVBEMultiboot.CheckedChanged += delegate (object aSender, EventArgs e)
{
if (FreezeEvents) return;
mViewModel.BuildProperties.CompileVBEMultiboot = checkBoxVBEMultiboot.Checked;
if (checkBoxVBEMultiboot.Checked)
{
textBoxVBEResolution.Visible = true;
label2.Visible = true;
}
else
{
textBoxVBEResolution.Visible = false;
label2.Visible = false;
}
};
chckExtractMapFile.CheckedChanged += delegate (object aSender, EventArgs e)
{
if (!FreezeEvents)
{
mViewModel.BuildProperties.ExtractMapFile = chckExtractMapFile.Checked;
}
};
textBoxVBEResolution.TextChanged += delegate (object aSender, EventArgs e)
{
if (FreezeEvents) return;
mViewModel.BuildProperties.VBEResolution = textBoxVBEResolution.Text;
};
#endregion
FillProperties();
}
protected void RemoveTab(TabPage aTab)
{
if (TabControl1.TabPages.Contains(aTab))
{
TabControl1.TabPages.Remove(aTab);
}
}
protected void UpdateTabs()
{
var xTab = TabControl1.SelectedTab;
RemoveTab(tabDebug);
RemoveTab(tabDeployment);
RemoveTab(tabLaunch);
RemoveTab(tabVMware);
RemoveTab(tabHyperV);
RemoveTab(tabPXE);
RemoveTab(tabUSB);
RemoveTab(tabISO);
RemoveTab(tabSlave);
RemoveTab(tabBochs);
RemoveTab(tabQemu);
if (mShowTabDebug)
{
TabControl1.TabPages.Add(tabDebug);
}
if (mShowTabDeployment)
{
TabControl1.TabPages.Add(tabDeployment);
}
if (mShowTabPXE)
{
TabControl1.TabPages.Add(tabPXE);
}
if (mShowTabUSB)
{
TabControl1.TabPages.Add(tabUSB);
}
if (mShowTabISO)
{
TabControl1.TabPages.Add(tabISO);
}
if (mShowTabLaunch)
{
TabControl1.TabPages.Add(tabLaunch);
}
if (mShowTabVMware)
{
TabControl1.TabPages.Add(tabVMware);
}
if (mShowTabHyperV)
{
TabControl1.TabPages.Add(tabHyperV);
}
if (mShowTabSlave)
{
TabControl1.TabPages.Add(tabSlave);
}
if (mShowTabBochs)
{
TabControl1.TabPages.Add(tabBochs);
}
if (mShowTabQemu)
{
TabControl1.TabPages.Add(tabQemu);
}
if (TabControl1.TabPages.Contains(xTab))
{
TabControl1.SelectedTab = xTab;
}
else
{
TabControl1.SelectedTab = tabProfile;
}
}
protected void UpdatePresetsUI()
{
FreezeEvents = true;
mShowTabDebug = true;
cmboCosmosDebugPort.Enabled = true;
cmboVisualStudioDebugPort.Enabled = true;
checkBoxVBEMultiboot.Checked = false;
textBoxVBEResolution.Visible = false;
label2.Visible = false;
if (mViewModel.BuildProperties.Profile == "ISO")
{
mShowTabDebug = false;
chckEnableDebugStub.Checked = false;
}
else if (mViewModel.BuildProperties.Profile == "USB")
{
mShowTabDebug = false;
mShowTabUSB = true;
}
else if (mViewModel.BuildProperties.Profile == "VMware")
{
mShowTabVMware = true;
chckEnableDebugStub.Checked = true;
chkEnableStackCorruptionDetection.Checked = true;
cmboCosmosDebugPort.Enabled = false;
cmboVisualStudioDebugPort.Enabled = false;
cmboVisualStudioDebugPort.SelectedIndex = mVMwareAndBochsDebugPipe;
}
else if (mViewModel.BuildProperties.Profile == "HyperV")
{
mShowTabHyperV = true;
chckEnableDebugStub.Checked = true;
chkEnableStackCorruptionDetection.Checked = true;
cmboCosmosDebugPort.Enabled = false;
cmboVisualStudioDebugPort.Enabled = false;
cmboVisualStudioDebugPort.SelectedIndex = mHyperVDebugPipe;
}
else if (mViewModel.BuildProperties.Profile == "PXE")
{
chckEnableDebugStub.Checked = false;
}
else if (mViewModel.BuildProperties.Profile == "Bochs")
{
mShowTabBochs = true;
chckEnableDebugStub.Checked = true;
chkEnableStackCorruptionDetection.Checked = true;
cmboCosmosDebugPort.Enabled = false;
cmboVisualStudioDebugPort.Enabled = false;
cmboVisualStudioDebugPort.SelectedIndex = mVMwareAndBochsDebugPipe;
}
else if (mViewModel.BuildProperties.Profile == "Qemu")
{
mShowTabQemu = true;
chckEnableDebugStub.Checked = true;
chkEnableStackCorruptionDetection.Checked = true;
cmboCosmosDebugPort.Enabled = false;
cmboVisualStudioDebugPort.Enabled = false;
cmboVisualStudioDebugPort.SelectedIndex = mVMwareAndBochsDebugPipe;
}
else if (mViewModel.BuildProperties.Profile == "IntelEdison")
{
mShowTabBochs = false;
mShowTabVMware = false;
cmboVisualStudioDebugPort.Enabled = false;
}
FreezeEvents = false;
}
protected void UpdateUI()
{
UpdatePresetsUI();
var xProfile = (ProfileItem)lboxProfile.SelectedItem;
if (xProfile == null)
{
return;
}
if (mShowTabDebug == false)
{
chckEnableDebugStub.Checked = false;
}
lablCurrentProfile.Text = xProfile.Name;
lablDeployText.Text = mViewModel.BuildProperties.Description;
lboxDeployment.SelectedItem = mViewModel.BuildProperties.Deployment;
// Launch
lboxLaunch.SelectedItem = mViewModel.BuildProperties.Launch;
lablBuildOnly.Visible = mViewModel.BuildProperties.Launch == LaunchType.None;
lboxDeployment.SelectedItem = EnumValue.Find(lboxDeployment.Items, mViewModel.BuildProperties.Deployment);
lboxLaunch.SelectedItem = EnumValue.Find(lboxLaunch.Items, mViewModel.BuildProperties.Launch);
cmboVMwareEdition.SelectedItem = EnumValue.Find(cmboVMwareEdition.Items, mViewModel.BuildProperties.VMwareEdition);
chckEnableDebugStub.Checked = mViewModel.BuildProperties.DebugEnabled;
chkEnableStackCorruptionDetection.Checked = mViewModel.BuildProperties.StackCorruptionDetectionEnabled;
comboStackCorruptionDetectionLevel.SelectedItem = EnumValue.Find(comboStackCorruptionDetectionLevel.Items, mViewModel.BuildProperties.StackCorruptionDetectionLevel);
panlDebugSettings.Enabled = mViewModel.BuildProperties.DebugEnabled;
cmboCosmosDebugPort.SelectedIndex = cmboCosmosDebugPort.Items.IndexOf(mViewModel.BuildProperties.CosmosDebugPort);
if (!String.IsNullOrWhiteSpace(mViewModel.BuildProperties.VisualStudioDebugPort))
{
cmboVisualStudioDebugPort.SelectedIndex =
cmboVisualStudioDebugPort.Items.IndexOf(mViewModel.BuildProperties.VisualStudioDebugPort);
}
comboFramework.SelectedItem = EnumValue.Find(comboFramework.Items, mViewModel.BuildProperties.Framework);
comboBinFormat.SelectedItem = EnumValue.Find(comboBinFormat.Items, mViewModel.BuildProperties.BinFormat);
checkUseInternalAssembler.Checked = mViewModel.BuildProperties.UseInternalAssembler;
checkEnableGDB.Checked = mViewModel.BuildProperties.EnableGDB;
checkStartCosmosGDB.Checked = mViewModel.BuildProperties.StartCosmosGDB;
checkEnableBochsDebug.Checked = mViewModel.BuildProperties.EnableBochsDebug;
checkStartBochsDebugGui.Checked = mViewModel.BuildProperties.StartBochsDebugGui;
checkBoxVBEMultiboot.Checked = mViewModel.BuildProperties.CompileVBEMultiboot;
if (mViewModel.BuildProperties.CompileVBEMultiboot)
{
textBoxVBEResolution.Visible = true;
label2.Visible = true;
}
else
{
textBoxVBEResolution.Visible = false;
label2.Visible = false;
}
// Locked to COM1 for now.
//cmboCosmosDebugPort.SelectedIndex = 0;
#region Slave
cmboSlavePort.SelectedIndex = cmboSlavePort.Items.IndexOf(mViewModel.BuildProperties.SlavePort);
#endregion
checkIgnoreDebugStubAttribute.Checked = mViewModel.BuildProperties.IgnoreDebugStubAttribute;
comboDebugMode.SelectedItem = EnumValue.Find(comboDebugMode.Items, mViewModel.BuildProperties.DebugMode);
comboTraceMode.SelectedItem = EnumValue.Find(comboTraceMode.Items, mViewModel.BuildProperties.TraceAssemblies);
lablPreset.Visible = xProfile.IsPreset;
mShowTabDeployment = !xProfile.IsPreset;
mShowTabLaunch = !xProfile.IsPreset;
//
mShowTabISO = mViewModel.BuildProperties.Deployment == DeploymentType.ISO;
mShowTabUSB = mViewModel.BuildProperties.Deployment == DeploymentType.USB;
mShowTabPXE = mViewModel.BuildProperties.Deployment == DeploymentType.PXE;
//
mShowTabVMware = mViewModel.BuildProperties.Launch == LaunchType.VMware;
mShowTabHyperV = mViewModel.BuildProperties.Launch == LaunchType.HyperV;
mShowTabSlave = mViewModel.BuildProperties.Launch == LaunchType.Slave;
mShowTabBochs = mViewModel.BuildProperties.Launch == LaunchType.Bochs;
mShowTabQemu = mViewModel.BuildProperties.Launch == LaunchType.Qemu;
//
UpdateTabs();
}
protected int FillProfile(string aPrefix, string aName)
{
var xProfile = new ProfileItem { Prefix = aPrefix, Name = aName, IsPreset = true };
return lboxProfile.Items.Add(xProfile);
}
protected int FillProfile(int aID)
{
var xProfile = new ProfileItem { Prefix = "User" + aID.ToString("000"), IsPreset = false };
xProfile.Name = mViewModel.BuildProperties.GetProperty(xProfile.Prefix + "_Name");
return lboxProfile.Items.Add(xProfile);
}
protected void FillProfiles()
{
lboxProfile.Items.Clear();
foreach (var xPreset in mPresets)
{
FillProfile(xPreset.Key, xPreset.Value);
}
for (int i = 1; i < 100; i++)
{
if (!String.IsNullOrEmpty(mViewModel.BuildProperties.GetProperty("User" + i.ToString("000") + "_Name")))
{
FillProfile(i);
}
}
}
void butnProfileRename_Click(object sender, EventArgs e)
{
var xItem = (ProfileItem)lboxProfile.SelectedItem;
if (xItem == null)
{
// This should be impossible, but we check for it anwyays.
}
else if (xItem.IsPreset)
{
MessageBox.Show("Preset profiles cannot be renamed.");
}
else
{
string xName = Interaction.InputBox("Profile Name", "Rename Profile", mViewModel.BuildProperties.Name);
if (xName != "")
{
mViewModel.BuildProperties.Name = xName;
xItem.Name = xName;
typeof(ListBox).InvokeMember(
"RefreshItems",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod,
null,
lboxProfile,
new object[] { });
}
}
}
void butnProfileDelete_Click(object sender, EventArgs e)
{
var xItem = (ProfileItem)lboxProfile.SelectedItem;
if (xItem == null)
{
// This should be impossible, but we check for it anwyays.
}
else if (xItem.IsPreset)
{
MessageBox.Show("Preset profiles cannot be deleted.");
}
else if (MessageBox.Show("Delete profile '" + xItem.Name + "'?", "", MessageBoxButtons.YesNo)
== DialogResult.Yes)
{
// Select a new profile first, so the selectchange logic wont barf
lboxProfile.SelectedIndex = 0;
lboxProfile.Items.Remove(xItem);
mViewModel.BuildProperties.DeleteProfile(xItem.Prefix);
}
}
void butnProfileClone_Click(object sender, EventArgs e)
{
var xItem = (ProfileItem)lboxProfile.SelectedItem;
if (xItem == null)
{
// This should be impossible, but we check for it anwyays.
return;
}
int xID;
string xPrefix = null;
for (xID = 1; xID < 100; xID++)
{
xPrefix = "User" + xID.ToString("000");
if (mViewModel.BuildProperties.GetProperty(xPrefix + "_Name") == "")
{
break;
}
}
if (xID == 100)
{
MessageBox.Show("No more profile space is available.");
return;
}
mViewModel.BuildProperties.Name = xItem.Prefix + " User " + xID.ToString("000");
mViewModel.BuildProperties.Description = "";
mViewModel.BuildProperties.SaveProfile(xPrefix);
lboxProfile.SelectedIndex = FillProfile(xID);
}
void butnPxeRefresh_Click(object sender, EventArgs e)
{
FillNetworkInterfaces();
}
/// <summary>
/// Load properties for the given profile.
/// </summary>
/// <param name="aPrefix">Name of the profile for which load properties.</param>
protected void LoadProfileProps(string aPrefix)
{
string xPrefix = aPrefix + (aPrefix == "" ? "" : "_");
foreach (var xName in BuildProperties.PropNames)
{
if (!mViewModel.BuildProperties.ProjectIndependentProperties.Contains(xName))
{
string xValue = mViewModel.GetProjectProperty(xPrefix + xName);
// This is important that we dont copy empty values, so instead the defaults will be used.
if (!String.IsNullOrWhiteSpace(xValue))
{
mViewModel.BuildProperties.SetProperty(xPrefix + xName, xValue);
}
}
}
}
protected void LoadProps()
{
// Load mViewModel.BuildProperties from project config file.
// The reason for loading into mViewModel.BuildProperties seems to be so we can track changes, and cancel if necessary.
mViewModel.BuildProperties.Reset();
// Reset cache only on first one
// Get selected profile
mViewModel.LoadProfile();
mViewModel.LoadProjectProperties();
// Load selected profile props
LoadProfileProps("");
foreach (var xPreset in mPresets)
{
LoadProfileProps(xPreset.Key);
}
for (int id = 1; id < 100; id++)
{
var xPrefix = "User" + id.ToString("000");
LoadProfileProps(xPrefix);
}
}
private void FillProperties()
{
LoadProps();
FillProfiles();
foreach (ProfileItem xItem in lboxProfile.Items)
{
if (xItem.Prefix == mViewModel.BuildProperties.Profile)
{
lboxProfile.SelectedItem = xItem;
break;
}
}
lboxDeployment.Items.AddRange(EnumValue.GetEnumValues(typeof(DeploymentType), true));
comboFramework.Items.AddRange(EnumValue.GetEnumValues(typeof(Framework), true));
comboBinFormat.Items.AddRange(EnumValue.GetEnumValues(typeof(BinFormat), true));
lboxLaunch.Items.AddRange(EnumValue.GetEnumValues(typeof(LaunchType), true));
#region VMware
cmboVMwareEdition.Items.AddRange(EnumValue.GetEnumValues(typeof(VMwareEdition), true));
#endregion
#region Debug
cmboCosmosDebugPort.Items.Clear();
FillComPorts(cmboCosmosDebugPort.Items);
cmboVisualStudioDebugPort.Items.Clear();
FillComPorts(cmboVisualStudioDebugPort.Items);
mVMwareAndBochsDebugPipe = cmboVisualStudioDebugPort.Items.Add(@"Pipe: Cosmos\Serial");
mHyperVDebugPipe = cmboVisualStudioDebugPort.Items.Add(@"Pipe: CosmosSerial");
comboDebugMode.Items.AddRange(EnumValue.GetEnumValues(typeof(DebugMode), false));
comboTraceMode.Items.AddRange(EnumValue.GetEnumValues(typeof(TraceAssemblies), false));
comboStackCorruptionDetectionLevel.Items.AddRange(EnumValue.GetEnumValues(typeof(StackCorruptionDetectionLevel), true));
#endregion
#region PXE
FillNetworkInterfaces();
cmboSlavePort.Items.Clear();
cmboSlavePort.Items.Add("None");
FillComPorts(cmboSlavePort.Items);
#endregion
UpdateUI();
}
protected void FillComPorts(System.Collections.IList aList)
{
//TODO http://stackoverflow.com/questions/2937585/how-to-open-a-serial-port-by-friendly-name
foreach (string xPort in SerialPort.GetPortNames())
{
aList.Add("Serial: " + xPort);
}
}
protected void FillNetworkInterfaces()
{
comboPxeInterface.Items.Clear();
comboPxeInterface.Items.AddRange(GetNetworkInterfaces().ToArray());
if (mViewModel.BuildProperties.PxeInterface == String.Empty)
{
if (comboPxeInterface.Items.Count > 0)
{
comboPxeInterface.Text = comboPxeInterface.Items[0].ToString();
}
else
{
comboPxeInterface.Text = "192.168.42.1";
}
}
else
{
comboPxeInterface.Text = mViewModel.BuildProperties.PxeInterface;
}
}
protected List<string> GetNetworkInterfaces()
{
NetworkInterface[] nInterfaces = NetworkInterface.GetAllNetworkInterfaces();
var interfaces_list = new List<string>();
foreach (NetworkInterface nInterface in nInterfaces)
{
if (nInterface.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties ipProperties = nInterface.GetIPProperties();
foreach (var ip in ipProperties.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
interfaces_list.Add(ip.Address.ToString());
}
}
}
}
return interfaces_list;
}
private void chkEnableStackCorruptionDetection_CheckedChanged(object sender, EventArgs e)
{
if (!FreezeEvents)
{
mViewModel.BuildProperties.StackCorruptionDetectionEnabled = chkEnableStackCorruptionDetection.Checked;
comboStackCorruptionDetectionLevel.Enabled = mViewModel.BuildProperties.StackCorruptionDetectionEnabled;
}
}
private void stackCorruptionDetectionLevelComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (!FreezeEvents)
{
var x = (StackCorruptionDetectionLevel)((EnumValue) comboStackCorruptionDetectionLevel.SelectedItem).Value;
if (x != mViewModel.BuildProperties.StackCorruptionDetectionLevel)
{
mViewModel.BuildProperties.StackCorruptionDetectionLevel = x;
}
}
}
private void buttonAddFilesToISO_Click(object sender, EventArgs e)
{
var projectFolder = Path.GetDirectoryName(mViewModel.ProjectPath);
var isoFolder = Path.Combine(projectFolder, "isoFiles");
if (!Directory.Exists(isoFolder))
{
Directory.CreateDirectory(isoFolder);
}
Process.Start(isoFolder);
}
private void checkBoxVBEMultiboot_CheckedChanged(object sender, EventArgs e)
{
if (!FreezeEvents)
{
mViewModel.BuildProperties.CompileVBEMultiboot = checkBoxVBEMultiboot.Checked;
if (checkBoxVBEMultiboot.Checked)
{
textBoxVBEResolution.Visible = true;
label2.Visible = true;
}
else
{
textBoxVBEResolution.Visible = false;
label2.Visible = false;
}
}
}
private void textBoxVBEResolution_TextChanged(object sender, EventArgs e)
{
if (!FreezeEvents)
{
mViewModel.BuildProperties.VBEResolution = textBoxVBEResolution.Text;
}
}
private void chckExtractMapFile_CheckedChanged(object sender, EventArgs e)
{
if (!FreezeEvents)
{
mViewModel.BuildProperties.ExtractMapFile = chckExtractMapFile.Checked;
}
}
}
}
| |
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.LogicalTree;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Avalonia.VisualTree;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class ListBoxTests_Single
{
MouseTestHelper _mouse = new MouseTestHelper();
[Fact]
public void Focusing_Item_With_Tab_Should_Not_Select_It()
{
var target = new ListBox
{
Template = new FuncControlTemplate(CreateListBoxTemplate),
Items = new[] { "Foo", "Bar", "Baz " },
};
ApplyTemplate(target);
target.Presenter.Panel.Children[0].RaiseEvent(new GotFocusEventArgs
{
RoutedEvent = InputElement.GotFocusEvent,
NavigationMethod = NavigationMethod.Tab,
});
Assert.Equal(-1, target.SelectedIndex);
}
[Fact]
public void Focusing_Item_With_Arrow_Key_Should_Select_It()
{
var target = new ListBox
{
Template = new FuncControlTemplate(CreateListBoxTemplate),
Items = new[] { "Foo", "Bar", "Baz " },
};
ApplyTemplate(target);
target.Presenter.Panel.Children[0].RaiseEvent(new GotFocusEventArgs
{
RoutedEvent = InputElement.GotFocusEvent,
NavigationMethod = NavigationMethod.Directional,
});
Assert.Equal(0, target.SelectedIndex);
}
[Fact]
public void Clicking_Item_Should_Select_It()
{
var target = new ListBox
{
Template = new FuncControlTemplate(CreateListBoxTemplate),
Items = new[] { "Foo", "Bar", "Baz " },
};
ApplyTemplate(target);
_mouse.Click(target.Presenter.Panel.Children[0]);
Assert.Equal(0, target.SelectedIndex);
}
[Fact]
public void Clicking_Selected_Item_Should_Not_Deselect_It()
{
var target = new ListBox
{
Template = new FuncControlTemplate(CreateListBoxTemplate),
Items = new[] { "Foo", "Bar", "Baz " },
};
ApplyTemplate(target);
target.SelectedIndex = 0;
_mouse.Click(target.Presenter.Panel.Children[0]);
Assert.Equal(0, target.SelectedIndex);
}
[Fact]
public void Clicking_Item_Should_Select_It_When_SelectionMode_Toggle()
{
var target = new ListBox
{
Template = new FuncControlTemplate(CreateListBoxTemplate),
Items = new[] { "Foo", "Bar", "Baz " },
SelectionMode = SelectionMode.Single | SelectionMode.Toggle,
};
ApplyTemplate(target);
_mouse.Click(target.Presenter.Panel.Children[0]);
Assert.Equal(0, target.SelectedIndex);
}
[Fact]
public void Clicking_Selected_Item_Should_Deselect_It_When_SelectionMode_Toggle()
{
var target = new ListBox
{
Template = new FuncControlTemplate(CreateListBoxTemplate),
Items = new[] { "Foo", "Bar", "Baz " },
SelectionMode = SelectionMode.Toggle,
};
ApplyTemplate(target);
target.SelectedIndex = 0;
_mouse.Click(target.Presenter.Panel.Children[0]);
Assert.Equal(-1, target.SelectedIndex);
}
[Fact]
public void Clicking_Selected_Item_Should_Not_Deselect_It_When_SelectionMode_ToggleAlwaysSelected()
{
var target = new ListBox
{
Template = new FuncControlTemplate(CreateListBoxTemplate),
Items = new[] { "Foo", "Bar", "Baz " },
SelectionMode = SelectionMode.Toggle | SelectionMode.AlwaysSelected,
};
ApplyTemplate(target);
target.SelectedIndex = 0;
_mouse.Click(target.Presenter.Panel.Children[0]);
Assert.Equal(0, target.SelectedIndex);
}
[Fact]
public void Clicking_Another_Item_Should_Select_It_When_SelectionMode_Toggle()
{
var target = new ListBox
{
Template = new FuncControlTemplate(CreateListBoxTemplate),
Items = new[] { "Foo", "Bar", "Baz " },
SelectionMode = SelectionMode.Single | SelectionMode.Toggle,
};
ApplyTemplate(target);
target.SelectedIndex = 1;
_mouse.Click(target.Presenter.Panel.Children[0]);
Assert.Equal(0, target.SelectedIndex);
}
[Fact]
public void Setting_Item_IsSelected_Sets_ListBox_Selection()
{
var target = new ListBox
{
Template = new FuncControlTemplate(CreateListBoxTemplate),
Items = new[] { "Foo", "Bar", "Baz " },
};
ApplyTemplate(target);
((ListBoxItem)target.GetLogicalChildren().ElementAt(1)).IsSelected = true;
Assert.Equal("Bar", target.SelectedItem);
Assert.Equal(1, target.SelectedIndex);
}
[Fact]
public void SelectedItem_Should_Not_Cause_StackOverflow()
{
var viewModel = new TestStackOverflowViewModel()
{
Items = new List<string> { "foo", "bar", "baz" }
};
var target = new ListBox
{
Template = new FuncControlTemplate(CreateListBoxTemplate),
DataContext = viewModel,
Items = viewModel.Items
};
target.Bind(ListBox.SelectedItemProperty,
new Binding("SelectedItem") { Mode = BindingMode.TwoWay });
Assert.Equal(0, viewModel.SetterInvokedCount);
// In Issue #855, a Stackoverflow occured here.
target.SelectedItem = viewModel.Items[2];
Assert.Equal(viewModel.Items[1], target.SelectedItem);
Assert.Equal(1, viewModel.SetterInvokedCount);
}
private class TestStackOverflowViewModel : INotifyPropertyChanged
{
public List<string> Items { get; set; }
public int SetterInvokedCount { get; private set; }
public const int MaxInvokedCount = 1000;
private string _selectedItem;
public event PropertyChangedEventHandler PropertyChanged;
public string SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
SetterInvokedCount++;
int index = Items.IndexOf(value);
if (MaxInvokedCount > SetterInvokedCount && index > 0)
{
_selectedItem = Items[index - 1];
}
else
{
_selectedItem = value;
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItem)));
}
}
}
}
private Control CreateListBoxTemplate(ITemplatedControl parent, INameScope scope)
{
return new ScrollViewer
{
Template = new FuncControlTemplate(CreateScrollViewerTemplate),
Content = new ItemsPresenter
{
Name = "PART_ItemsPresenter",
[~ItemsPresenter.ItemsProperty] = parent.GetObservable(ItemsControl.ItemsProperty).ToBinding(),
}.RegisterInNameScope(scope)
};
}
private Control CreateScrollViewerTemplate(ITemplatedControl parent, INameScope scope)
{
return new ScrollContentPresenter
{
Name = "PART_ContentPresenter",
[~ContentPresenter.ContentProperty] =
parent.GetObservable(ContentControl.ContentProperty).ToBinding(),
}.RegisterInNameScope(scope);
}
private void ApplyTemplate(ListBox target)
{
// Apply the template to the ListBox itself.
target.ApplyTemplate();
// Then to its inner ScrollViewer.
var scrollViewer = (ScrollViewer)target.GetVisualChildren().Single();
scrollViewer.ApplyTemplate();
// Then make the ScrollViewer create its child.
((ContentPresenter)scrollViewer.Presenter).UpdateChild();
// Now the ItemsPresenter should be reigstered, so apply its template.
target.Presenter.ApplyTemplate();
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Threading;
using Mono.Collections.Generic;
namespace Mono.Cecil.Cil {
public sealed class MethodBody {
readonly internal MethodDefinition method;
internal ParameterDefinition this_parameter;
internal int max_stack_size;
internal int code_size;
internal bool init_locals;
internal MetadataToken local_var_token;
internal Collection<Instruction> instructions;
internal Collection<ExceptionHandler> exceptions;
internal Collection<VariableDefinition> variables;
public MethodDefinition Method {
get { return method; }
}
public int MaxStackSize {
get { return max_stack_size; }
set { max_stack_size = value; }
}
public int CodeSize {
get { return code_size; }
}
public bool InitLocals {
get { return init_locals; }
set { init_locals = value; }
}
public MetadataToken LocalVarToken {
get { return local_var_token; }
set { local_var_token = value; }
}
public Collection<Instruction> Instructions {
get {
if (instructions == null)
Interlocked.CompareExchange (ref instructions, new InstructionCollection (method), null);
return instructions;
}
}
public bool HasExceptionHandlers {
get { return !exceptions.IsNullOrEmpty (); }
}
public Collection<ExceptionHandler> ExceptionHandlers {
get {
if (exceptions == null)
Interlocked.CompareExchange (ref exceptions, new Collection<ExceptionHandler> (), null);
return exceptions;
}
}
public bool HasVariables {
get { return !variables.IsNullOrEmpty (); }
}
public Collection<VariableDefinition> Variables {
get {
if (variables == null)
Interlocked.CompareExchange (ref variables, new VariableDefinitionCollection (this.method), null);
return variables;
}
}
public ParameterDefinition ThisParameter {
get {
if (method == null || method.DeclaringType == null)
throw new NotSupportedException ();
if (!method.HasThis)
return null;
if (this_parameter == null)
Interlocked.CompareExchange (ref this_parameter, CreateThisParameter (method), null);
return this_parameter;
}
}
static ParameterDefinition CreateThisParameter (MethodDefinition method)
{
var parameter_type = method.DeclaringType as TypeReference;
if (parameter_type.HasGenericParameters) {
var instance = new GenericInstanceType (parameter_type, parameter_type.GenericParameters.Count);
for (int i = 0; i < parameter_type.GenericParameters.Count; i++)
instance.GenericArguments.Add (parameter_type.GenericParameters [i]);
parameter_type = instance;
}
if (parameter_type.IsValueType || parameter_type.IsPrimitive)
parameter_type = new ByReferenceType (parameter_type);
return new ParameterDefinition (parameter_type, method);
}
public MethodBody (MethodDefinition method)
{
this.method = method;
}
public ILProcessor GetILProcessor ()
{
return new ILProcessor (this);
}
}
sealed class VariableDefinitionCollection : Collection<VariableDefinition> {
readonly MethodDefinition method;
internal VariableDefinitionCollection (MethodDefinition method)
{
this.method = method;
}
internal VariableDefinitionCollection (MethodDefinition method, int capacity)
: base (capacity)
{
this.method = method;
}
protected override void OnAdd (VariableDefinition item, int index)
{
item.index = index;
}
protected override void OnInsert (VariableDefinition item, int index)
{
item.index = index;
UpdateVariableIndices (index, 1);
}
protected override void OnSet (VariableDefinition item, int index)
{
item.index = index;
}
protected override void OnRemove (VariableDefinition item, int index)
{
UpdateVariableIndices (index + 1, -1, item);
item.index = -1;
}
void UpdateVariableIndices (int startIndex, int offset, VariableDefinition variableToRemove = null)
{
for (int i = startIndex; i < size; i++)
items [i].index = i + offset;
var debug_info = method == null ? null : method.debug_info;
if (debug_info == null || debug_info.Scope == null)
return;
foreach (var scope in debug_info.GetScopes ()) {
if (!scope.HasVariables)
continue;
var variables = scope.Variables;
int variableDebugInfoIndexToRemove = -1;
for (int i = 0; i < variables.Count; i++) {
var variable = variables [i];
// If a variable is being removed detect if it has debug info counterpart, if so remove that as well.
// Note that the debug info can be either resolved (has direct reference to the VariableDefinition)
// or unresolved (has only the number index of the variable) - this needs to handle both cases.
if (variableToRemove != null &&
((variable.index.IsResolved && variable.index.ResolvedVariable == variableToRemove) ||
(!variable.index.IsResolved && variable.Index == variableToRemove.Index))) {
variableDebugInfoIndexToRemove = i;
continue;
}
// For unresolved debug info updates indeces to keep them pointing to the same variable.
if (!variable.index.IsResolved && variable.Index >= startIndex) {
variable.index = new VariableIndex (variable.Index + offset);
}
}
if (variableDebugInfoIndexToRemove >= 0)
variables.RemoveAt (variableDebugInfoIndexToRemove);
}
}
}
class InstructionCollection : Collection<Instruction> {
readonly MethodDefinition method;
internal InstructionCollection (MethodDefinition method)
{
this.method = method;
}
internal InstructionCollection (MethodDefinition method, int capacity)
: base (capacity)
{
this.method = method;
}
protected override void OnAdd (Instruction item, int index)
{
if (index == 0)
return;
var previous = items [index - 1];
previous.next = item;
item.previous = previous;
}
protected override void OnInsert (Instruction item, int index)
{
int startOffset = 0;
if (size != 0) {
var current = items [index];
if (current == null) {
var last = items [index - 1];
last.next = item;
item.previous = last;
return;
}
startOffset = current.Offset;
var previous = current.previous;
if (previous != null) {
previous.next = item;
item.previous = previous;
}
current.previous = item;
item.next = current;
}
UpdateLocalScopes (null, null);
}
protected override void OnSet (Instruction item, int index)
{
var current = items [index];
item.previous = current.previous;
item.next = current.next;
current.previous = null;
current.next = null;
UpdateLocalScopes (item, current);
}
protected override void OnRemove (Instruction item, int index)
{
var previous = item.previous;
if (previous != null)
previous.next = item.next;
var next = item.next;
if (next != null)
next.previous = item.previous;
RemoveSequencePoint (item);
UpdateLocalScopes (item, next ?? previous);
item.previous = null;
item.next = null;
}
void RemoveSequencePoint (Instruction instruction)
{
var debug_info = method.debug_info;
if (debug_info == null || !debug_info.HasSequencePoints)
return;
var sequence_points = debug_info.sequence_points;
for (int i = 0; i < sequence_points.Count; i++) {
if (sequence_points [i].Offset == instruction.offset) {
sequence_points.RemoveAt (i);
return;
}
}
}
void UpdateLocalScopes (Instruction removedInstruction, Instruction existingInstruction)
{
var debug_info = method.debug_info;
if (debug_info == null)
return;
// Local scopes store start/end pair of "instruction offsets". Instruction offset can be either resolved, in which case it
// has a reference to Instruction, or unresolved in which case it stores numerical offset (instruction offset in the body).
// Typically local scopes loaded from PE/PDB files will be resolved, but it's not a requirement.
// Each instruction has its own offset, which is populated on load, but never updated (this would be pretty expensive to do).
// Instructions created during the editting will typically have offset 0 (so incorrect).
// Local scopes created during editing will also likely be resolved (so no numerical offsets).
// So while local scopes which are unresolved are relatively rare if they appear, manipulating them based
// on the offsets allone is pretty hard (since we can't rely on correct offsets of instructions).
// On the other hand resolved local scopes are easy to maintain, since they point to instructions and thus inserting
// instructions is basically a no-op and removing instructions is as easy as changing the pointer.
// For this reason the algorithm here is:
// - First make sure that all instruction offsets are resolved - if not - resolve them
// - First time this will be relatively expensinve as it will walk the entire method body to convert offsets to instruction pointers
// Almost all local scopes are stored in the "right" order (sequentially per start offsets), so the code uses a simple one-item
// cache instruction<->offset to avoid walking instructions multiple times (that would only happen for scopes which are out of order).
// - Subsequent calls should be cheap as it will only walk all local scopes without doing anything
// - If there was an edit on local scope which makes some of them unresolved, the cost is proportional
// - Then update as necessary by manipulaitng instruction references alone
InstructionOffsetCache cache = new InstructionOffsetCache () {
Offset = 0,
Index = 0,
Instruction = items [0]
};
UpdateLocalScope (debug_info.Scope, removedInstruction, existingInstruction, ref cache);
}
void UpdateLocalScope (ScopeDebugInformation scope, Instruction removedInstruction, Instruction existingInstruction, ref InstructionOffsetCache cache)
{
if (scope == null)
return;
if (!scope.Start.IsResolved)
scope.Start = ResolveInstructionOffset (scope.Start, ref cache);
if (!scope.Start.IsEndOfMethod && scope.Start.ResolvedInstruction == removedInstruction)
scope.Start = new InstructionOffset (existingInstruction);
if (scope.HasScopes) {
foreach (var subScope in scope.Scopes)
UpdateLocalScope (subScope, removedInstruction, existingInstruction, ref cache);
}
if (!scope.End.IsResolved)
scope.End = ResolveInstructionOffset (scope.End, ref cache);
if (!scope.End.IsEndOfMethod && scope.End.ResolvedInstruction == removedInstruction)
scope.End = new InstructionOffset (existingInstruction);
}
struct InstructionOffsetCache {
public int Offset;
public int Index;
public Instruction Instruction;
}
InstructionOffset ResolveInstructionOffset(InstructionOffset inputOffset, ref InstructionOffsetCache cache)
{
if (inputOffset.IsResolved)
return inputOffset;
int offset = inputOffset.Offset;
if (cache.Offset == offset)
return new InstructionOffset (cache.Instruction);
if (cache.Offset > offset) {
// This should be rare - we're resolving offset pointing to a place before the current cache position
// resolve by walking the instructions from start and don't cache the result.
int size = 0;
for (int i = 0; i < items.Length; i++) {
if (size == offset)
return new InstructionOffset (items [i]);
if (size > offset)
return new InstructionOffset (items [i - 1]);
size += items [i].GetSize ();
}
// Offset is larger than the size of the body - so it points after the end
return new InstructionOffset ();
} else {
// The offset points after the current cache position - so continue counting and update the cache
int size = cache.Offset;
for (int i = cache.Index; i < items.Length; i++) {
cache.Index = i;
cache.Offset = size;
var item = items [i];
// Allow for trailing null values in the case of
// instructions.Size < instructions.Capacity
if (item == null)
break;
cache.Instruction = item;
if (cache.Offset == offset)
return new InstructionOffset (cache.Instruction);
if (cache.Offset > offset)
return new InstructionOffset (items [i - 1]);
size += item.GetSize ();
}
return new InstructionOffset ();
}
}
}
}
| |
// 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 Fixtures.Azure.AcceptanceTestsHead
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
/// <summary>
/// HttpSuccessOperations operations.
/// </summary>
internal partial class HttpSuccessOperations : IServiceOperations<AutoRestHeadTestService>, IHttpSuccessOperations
{
/// <summary>
/// Initializes a new instance of the HttpSuccessOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal HttpSuccessOperations(AutoRestHeadTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHeadTestService
/// </summary>
public AutoRestHeadTestService Client { get; private set; }
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> Head200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "Head200", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/200").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 404)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
_result.Body = (_statusCode == HttpStatusCode.OK);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> Head204WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "Head204", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/204").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 404)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
_result.Body = (_statusCode == HttpStatusCode.NoContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 404 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> Head404WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "Head404", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/404").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 404)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
_result.Body = (_statusCode == HttpStatusCode.NoContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// Literal.cs
//
// Author:
// Gabriel Burt <gabriel.burt@gmail.com>
// Stephane Delcroix <stephane@delcroix.org>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2007-2009 Novell, Inc.
// Copyright (C) 2007 Gabriel Burt
// Copyright (C) 2007-2009 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// This has to do with Finding photos based on tags
// http://mail.gnome.org/archives/f-spot-list/2005-November/msg00053.html
// http://bugzilla-attachments.gnome.org/attachment.cgi?id=54566
using System;
using System.Collections.Generic;
using System.Text;
using Mono.Unix;
using Gtk;
using Gdk;
using FSpot.Core;
namespace FSpot
{
public abstract class AbstractLiteral : Term
{
protected AbstractLiteral (Term parent, Literal after) : base (parent, after)
{
}
public override Term Invert (bool recurse)
{
is_negated = !is_negated;
return this;
}
}
// TODO rename to TagLiteral?
public class Literal : AbstractLiteral
{
public Literal (Tag tag) : this (null, tag, null)
{
}
public Literal (Term parent, Tag tag, Literal after) : base (parent, after)
{
Tag = tag;
}
static Literal ()
{
FocusedLiterals = new List<Literal> ();
}
#region Properties
public static List<Literal> FocusedLiterals { get; set; }
public Tag Tag { get; private set; }
public override bool IsNegated {
get {
return is_negated;
}
set {
if (is_negated == value)
return;
is_negated = value;
NormalIcon = null;
NegatedIcon = null;
Update ();
if (NegatedToggled != null)
NegatedToggled (this);
}
}
private Pixbuf NegatedIcon {
get {
if (negated_icon != null)
return negated_icon;
if (NormalIcon == null)
return null;
negated_icon = NormalIcon.Copy ();
int offset = ICON_SIZE - overlay_size;
NegatedOverlay.Composite (negated_icon, offset, 0, overlay_size, overlay_size, offset, 0, 1.0, 1.0, InterpType.Bilinear, 200);
return negated_icon;
}
set {
negated_icon = null;
}
}
public Widget Widget {
get {
if (widget != null)
return widget;
container = new EventBox ();
box = new HBox ();
handle_box = new LiteralBox ();
handle_box.BorderWidth = 1;
label = new Label (System.Web.HttpUtility.HtmlEncode (Tag.Name));
label.UseMarkup = true;
image = new Gtk.Image (NormalIcon);
container.CanFocus = true;
container.KeyPressEvent += KeyHandler;
container.ButtonPressEvent += HandleButtonPress;
container.ButtonReleaseEvent += HandleButtonRelease;
container.EnterNotifyEvent += HandleMouseIn;
container.LeaveNotifyEvent += HandleMouseOut;
//new PopupManager (new LiteralPopup (container, this));
// Setup this widget as a drag source (so tags can be moved after being placed)
container.DragDataGet += HandleDragDataGet;
container.DragBegin += HandleDragBegin;
container.DragEnd += HandleDragEnd;
Gtk.Drag.SourceSet (container, Gdk.ModifierType.Button1Mask | Gdk.ModifierType.Button3Mask,
tag_target_table, DragAction.Copy | DragAction.Move);
// Setup this widget as a drag destination (so tags can be added to our parent's Term)
container.DragDataReceived += HandleDragDataReceived;
container.DragMotion += HandleDragMotion;
container.DragLeave += HandleDragLeave;
Gtk.Drag.DestSet (container, DestDefaults.All, tag_dest_target_table,
DragAction.Copy | DragAction.Move);
container.TooltipText = Tag.Name;
label.Show ();
image.Show ();
if (Tag.Icon == null)
handle_box.Add (label);
else
handle_box.Add (image);
handle_box.Show ();
box.Add (handle_box);
box.Show ();
container.Add (box);
widget = container;
return widget;
}
}
private Pixbuf NormalIcon {
get {
if (normal_icon != null)
return normal_icon;
Pixbuf scaled = null;
scaled = Tag.Icon;
for (Category category = Tag.Category; category != null && scaled == null; category = category.Category) {
scaled = category.Icon;
}
if (scaled == null)
return null;
if (scaled.Width != ICON_SIZE)
scaled = scaled.ScaleSimple (ICON_SIZE, ICON_SIZE, InterpType.Bilinear);
normal_icon = scaled;
return normal_icon;
}
set {
normal_icon = null;
}
}
#endregion
#region Methods
public void Update ()
{
// Clear out the old icons
normal_icon = null;
negated_icon = null;
if (IsNegated) {
widget.TooltipText = String.Format (Catalog.GetString ("Not {0}"), Tag.Name);
label.Text = "<s>" + System.Web.HttpUtility.HtmlEncode (Tag.Name) + "</s>";
image.Pixbuf = NegatedIcon;
} else {
widget.TooltipText = Tag.Name;
label.Text = System.Web.HttpUtility.HtmlEncode (Tag.Name);
image.Pixbuf = NormalIcon;
}
label.UseMarkup = true;
// Show the icon unless it's null
if (Tag.Icon == null && container.Children [0] == image) {
container.Remove (image);
container.Add (label);
} else if (Tag.Icon != null && container.Children [0] == label) {
container.Remove (label);
container.Add (image);
}
if (isHoveredOver && image.Pixbuf != null) {
// Brighten the image slightly
Pixbuf brightened = image.Pixbuf.Copy ();
image.Pixbuf.SaturateAndPixelate (brightened, 1.85f, false);
//Pixbuf brightened = PixbufUtils.Glow (image.Pixbuf, .6f);
image.Pixbuf = brightened;
}
}
public void RemoveSelf ()
{
if (Removing != null)
Removing (this);
if (Parent != null)
Parent.Remove (this);
if (Removed != null)
Removed (this);
}
public override string SqlCondition ()
{
var ids = new StringBuilder (Tag.Id.ToString ());
if (Tag is Category) {
var tags = new List<Tag> ();
(Tag as Category).AddDescendentsTo (tags);
foreach (var t in tags)
{
ids.Append (", " + t.Id.ToString ());
}
}
return String.Format (
"id {0}IN (SELECT photo_id FROM photo_tags WHERE tag_id IN ({1}))",
(IsNegated ? "NOT " : String.Empty), ids.ToString ());
}
public override Gtk.Widget SeparatorWidget ()
{
return new Label ("ERR");
}
private static Pixbuf NegatedOverlay {
get {
if (negated_overlay == null) {
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetCallingAssembly ();
negated_overlay = new Pixbuf (assembly.GetManifestResourceStream ("f-spot-not.png"));
negated_overlay = negated_overlay.ScaleSimple (overlay_size, overlay_size, InterpType.Bilinear);
}
return negated_overlay;
}
}
public static void RemoveFocusedLiterals ()
{
if (focusedLiterals != null)
foreach (Literal literal in focusedLiterals) {
literal.RemoveSelf ();
}
}
#endregion
#region Handlers
private void KeyHandler (object o, KeyPressEventArgs args)
{
args.RetVal = false;
switch (args.Event.Key) {
case Gdk.Key.Delete:
RemoveFocusedLiterals ();
args.RetVal = true;
return;
}
}
private void HandleButtonPress (object o, ButtonPressEventArgs args)
{
args.RetVal = true;
switch (args.Event.Type) {
case EventType.TwoButtonPress:
if (args.Event.Button == 1)
IsNegated = !IsNegated;
else
args.RetVal = false;
return;
case EventType.ButtonPress:
Widget.GrabFocus ();
if (args.Event.Button == 1) {
// TODO allow multiple selection of literals so they can be deleted, modified all at once
//if ((args.Event.State & ModifierType.ControlMask) != 0) {
//}
} else if (args.Event.Button == 3) {
LiteralPopup popup = new LiteralPopup ();
popup.Activate (args.Event, this);
}
return;
default:
args.RetVal = false;
return;
}
}
private void HandleButtonRelease (object o, ButtonReleaseEventArgs args)
{
args.RetVal = true;
switch (args.Event.Type) {
case EventType.TwoButtonPress:
args.RetVal = false;
return;
case EventType.ButtonPress:
if (args.Event.Button == 1) {
}
return;
default:
args.RetVal = false;
return;
}
}
private void HandleMouseIn (object o, EnterNotifyEventArgs args)
{
isHoveredOver = true;
Update ();
}
private void HandleMouseOut (object o, LeaveNotifyEventArgs args)
{
isHoveredOver = false;
Update ();
}
void HandleDragDataGet (object sender, DragDataGetArgs args)
{
args.RetVal = true;
if (args.Info == DragDropTargets.TagListEntry.Info || args.Info == DragDropTargets.TagQueryEntry.Info) {
// FIXME: do really write data
Byte [] data = Encoding.UTF8.GetBytes (String.Empty);
Atom [] targets = args.Context.Targets;
args.SelectionData.Set (targets [0], 8, data, data.Length);
return;
}
// Drop cancelled
args.RetVal = false;
foreach (Widget w in hiddenWidgets) {
w.Visible = true;
}
focusedLiterals = null;
}
void HandleDragBegin (object sender, DragBeginArgs args)
{
Gtk.Drag.SetIconPixbuf (args.Context, image.Pixbuf, 0, 0);
focusedLiterals.Add (this);
// Hide the tag and any separators that only exist because of it
container.Visible = false;
hiddenWidgets.Add (container);
foreach (Widget w in LogicWidget.Box.HangersOn (this)) {
hiddenWidgets.Add (w);
w.Visible = false;
}
}
void HandleDragEnd (object sender, DragEndArgs args)
{
// Remove any literals still marked as focused, because
// the user is throwing them away.
RemoveFocusedLiterals ();
focusedLiterals = new List<Literal> ();
args.RetVal = true;
}
private void HandleDragDataReceived (object o, DragDataReceivedArgs args)
{
args.RetVal = true;
if (args.Info == DragDropTargets.TagListEntry.Info) {
if (TagsAdded != null)
TagsAdded (args.SelectionData.GetTagsData (), Parent, this);
return;
}
if (args.Info == DragDropTargets.TagQueryEntry.Info) {
if (! focusedLiterals.Contains (this))
if (LiteralsMoved != null)
LiteralsMoved (focusedLiterals, Parent, this);
// Unmark the literals as focused so they don't get nixed
focusedLiterals = null;
}
}
private bool preview = false;
private Gtk.Widget preview_widget;
private void HandleDragMotion (object o, DragMotionArgs args)
{
if (preview)
return;
if (preview_widget == null) {
preview_widget = new Gtk.Label (" | ");
box.Add (preview_widget);
}
preview_widget.Show ();
}
private void HandleDragLeave (object o, EventArgs args)
{
preview = false;
preview_widget.Hide ();
}
public void HandleToggleNegatedCommand (object o, EventArgs args)
{
IsNegated = !IsNegated;
}
public void HandleRemoveCommand (object o, EventArgs args)
{
RemoveSelf ();
}
public void HandleAttachTagCommand (Tag t)
{
if (AttachTag != null)
AttachTag (t, Parent, this);
}
public void HandleRequireTag (object sender, EventArgs args)
{
if (RequireTag != null)
RequireTag (new[] {this.Tag});
}
public void HandleUnRequireTag (object sender, EventArgs args)
{
if (UnRequireTag != null)
UnRequireTag (new[] {this.Tag});
}
private const int ICON_SIZE = 24;
private const int overlay_size = (int)(.40 * ICON_SIZE);
private static TargetEntry[] tag_target_table =
new[] { DragDropTargets.TagQueryEntry };
private static TargetEntry[] tag_dest_target_table =
new[] {
DragDropTargets.TagListEntry,
DragDropTargets.TagQueryEntry
};
private static List<Literal> focusedLiterals = new List<Literal> ();
private static List<Widget> hiddenWidgets = new List<Widget> ();
private Gtk.Container container;
private LiteralBox handle_box;
private Gtk.Box box;
private Gtk.Image image;
private Gtk.Label label;
private Pixbuf normal_icon;
//private EventBox widget;
private Widget widget;
private Pixbuf negated_icon;
private static Pixbuf negated_overlay;
private bool isHoveredOver = false;
public delegate void NegatedToggleHandler (Literal group);
public event NegatedToggleHandler NegatedToggled;
public delegate void RemovingHandler (Literal group);
public event RemovingHandler Removing;
public delegate void RemovedHandler (Literal group);
public event RemovedHandler Removed;
public delegate void TagsAddedHandler (Tag[] tags,Term parent,Literal after);
public event TagsAddedHandler TagsAdded;
public delegate void AttachTagHandler (Tag tag,Term parent,Literal after);
public event AttachTagHandler AttachTag;
public delegate void TagRequiredHandler (Tag[] tags);
public event TagRequiredHandler RequireTag;
public delegate void TagUnRequiredHandler (Tag[] tags);
public event TagUnRequiredHandler UnRequireTag;
public delegate void LiteralsMovedHandler (List<Literal> literals,Term parent,Literal after);
public event LiteralsMovedHandler LiteralsMoved;
#endregion
}
public class TextLiteral : AbstractLiteral
{
private string text;
public TextLiteral (Term parent, string text) : base (parent, null)
{
this.text = text;
}
public override string SqlCondition ()
{
return String.Format (
"id {0}IN (SELECT id FROM photos WHERE base_uri LIKE '%{1}%' OR filename LIKE '%{1}%' OR description LIKE '%{1}%')",
(IsNegated ? "NOT " : ""), EscapeQuotes (text)
);
}
protected static string EscapeQuotes (string v)
{
return v == null ? String.Empty : v.Replace ("'", "''");
}
}
}
| |
// Copyright (c) 2007-2014 SIL International
// Licensed under the MIT license: opensource.org/licenses/MIT
namespace SolidGui
{
partial class RecordNavigatorView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RecordNavigatorView));
this._previousButton = new System.Windows.Forms.Button();
this._nextButton = new System.Windows.Forms.Button();
this._recordNumber = new System.Windows.Forms.Label();
this._firstButton = new System.Windows.Forms.Button();
this._findButton = new System.Windows.Forms.Button();
this.RefreshButton = new System.Windows.Forms.Button();
this.buttonTree = new System.Windows.Forms.Button();
this.buttonFlat = new System.Windows.Forms.Button();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this._descriptionLabel = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.flowLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// _previousButton
//
this._previousButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._previousButton.FlatAppearance.BorderSize = 0;
this._previousButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._previousButton.Image = global::SolidGui.Properties.Resources.BackwordOne;
this._previousButton.Location = new System.Drawing.Point(142, 3);
this._previousButton.Name = "_previousButton";
this._previousButton.Size = new System.Drawing.Size(25, 25);
this._previousButton.TabIndex = 1;
this._previousButton.UseVisualStyleBackColor = true;
this._previousButton.Click += new System.EventHandler(this._PreviousButton_Click);
//
// _nextButton
//
this._nextButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._nextButton.BackColor = System.Drawing.SystemColors.InactiveCaption;
this._nextButton.FlatAppearance.BorderSize = 0;
this._nextButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._nextButton.Image = global::SolidGui.Properties.Resources.ForwardOne;
this._nextButton.Location = new System.Drawing.Point(210, 3);
this._nextButton.Name = "_nextButton";
this._nextButton.Size = new System.Drawing.Size(25, 25);
this._nextButton.TabIndex = 2;
this._nextButton.UseVisualStyleBackColor = false;
this._nextButton.Click += new System.EventHandler(this._nextButton_Click);
//
// _recordNumber
//
this._recordNumber.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._recordNumber.ForeColor = System.Drawing.Color.Yellow;
this._recordNumber.Location = new System.Drawing.Point(173, 3);
this._recordNumber.Margin = new System.Windows.Forms.Padding(3);
this._recordNumber.Name = "_recordNumber";
this._recordNumber.Size = new System.Drawing.Size(31, 25);
this._recordNumber.TabIndex = 3;
this._recordNumber.Text = "17";
this._recordNumber.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// _firstButton
//
this._firstButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._firstButton.FlatAppearance.BorderColor = System.Drawing.Color.White;
this._firstButton.FlatAppearance.BorderSize = 0;
this._firstButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._firstButton.Image = ((System.Drawing.Image)(resources.GetObject("_firstButton.Image")));
this._firstButton.Location = new System.Drawing.Point(111, 3);
this._firstButton.Name = "_firstButton";
this._firstButton.Size = new System.Drawing.Size(25, 25);
this._firstButton.TabIndex = 5;
this._firstButton.UseVisualStyleBackColor = true;
this._firstButton.Click += new System.EventHandler(this._firstButton_Click);
//
// _findButton
//
this._findButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._findButton.FlatAppearance.BorderSize = 0;
this._findButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._findButton.Image = global::SolidGui.Properties.Resources.Search;
this._findButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._findButton.Location = new System.Drawing.Point(80, 3);
this._findButton.Name = "_findButton";
this._findButton.Size = new System.Drawing.Size(25, 25);
this._findButton.TabIndex = 6;
this._findButton.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._findButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this._findButton.UseVisualStyleBackColor = true;
this._findButton.Click += new System.EventHandler(this._findButton_Click);
//
// RefreshButton
//
this.RefreshButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.RefreshButton.FlatAppearance.BorderSize = 0;
this.RefreshButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.RefreshButton.Image = global::SolidGui.Properties.Resources.RecheckRecord;
this.RefreshButton.Location = new System.Drawing.Point(241, 3);
this.RefreshButton.Name = "RefreshButton";
this.RefreshButton.Size = new System.Drawing.Size(25, 25);
this.RefreshButton.TabIndex = 8;
this.RefreshButton.UseVisualStyleBackColor = true;
this.RefreshButton.Click += new System.EventHandler(this.RefreshButton_Click);
//
// buttonTree
//
this.buttonTree.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonTree.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.buttonTree.FlatAppearance.BorderSize = 0;
this.buttonTree.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonTree.Image = ((System.Drawing.Image)(resources.GetObject("buttonTree.Image")));
this.buttonTree.Location = new System.Drawing.Point(54, 3);
this.buttonTree.Name = "buttonTree";
this.buttonTree.Size = new System.Drawing.Size(20, 25);
this.buttonTree.TabIndex = 9;
this.buttonTree.UseVisualStyleBackColor = true;
this.buttonTree.Click += new System.EventHandler(this.buttonTree_Click);
//
// buttonFlat
//
this.buttonFlat.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonFlat.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.buttonFlat.FlatAppearance.BorderSize = 0;
this.buttonFlat.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonFlat.Image = ((System.Drawing.Image)(resources.GetObject("buttonFlat.Image")));
this.buttonFlat.Location = new System.Drawing.Point(28, 3);
this.buttonFlat.Name = "buttonFlat";
this.buttonFlat.Size = new System.Drawing.Size(20, 25);
this.buttonFlat.TabIndex = 10;
this.buttonFlat.UseVisualStyleBackColor = true;
this.buttonFlat.Click += new System.EventHandler(this.buttonFlat_Click);
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Controls.Add(this.RefreshButton);
this.flowLayoutPanel1.Controls.Add(this._nextButton);
this.flowLayoutPanel1.Controls.Add(this._recordNumber);
this.flowLayoutPanel1.Controls.Add(this._previousButton);
this.flowLayoutPanel1.Controls.Add(this._firstButton);
this.flowLayoutPanel1.Controls.Add(this._findButton);
this.flowLayoutPanel1.Controls.Add(this.buttonTree);
this.flowLayoutPanel1.Controls.Add(this.buttonFlat);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Right;
this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft;
this.flowLayoutPanel1.Location = new System.Drawing.Point(201, 0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(269, 34);
this.flowLayoutPanel1.TabIndex = 11;
//
// _descriptionLabel
//
this._descriptionLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._descriptionLabel.ForeColor = System.Drawing.Color.Yellow;
this._descriptionLabel.Location = new System.Drawing.Point(82, 10);
this._descriptionLabel.Name = "_descriptionLabel";
this._descriptionLabel.Size = new System.Drawing.Size(205, 16);
this._descriptionLabel.TabIndex = 0;
this._descriptionLabel.Text = "19 Records contain \"\\xe out of order\"";
this._descriptionLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
this.label2.Location = new System.Drawing.Point(6, 6);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(70, 20);
this.label2.TabIndex = 7;
this.label2.Text = "Lexicon";
//
// RecordNavigatorView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.InactiveCaption;
this.Controls.Add(this.flowLayoutPanel1);
this.Controls.Add(this.label2);
this.Controls.Add(this._descriptionLabel);
this.Name = "RecordNavigatorView";
this.Size = new System.Drawing.Size(470, 34);
this.Load += new System.EventHandler(this.RecordNavigatorView_Load);
this.flowLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button _previousButton;
private System.Windows.Forms.Button _nextButton;
private System.Windows.Forms.Label _recordNumber;
private System.Windows.Forms.Button _firstButton;
private System.Windows.Forms.Button _findButton;
public System.Windows.Forms.Button RefreshButton;
private System.Windows.Forms.Button buttonTree;
private System.Windows.Forms.Button buttonFlat;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Label _descriptionLabel;
private System.Windows.Forms.Label label2;
}
}
| |
#if !UNITY_EDITOR_OSX || MAC_FORCE_TESTS
using System;
using System.Linq;
using NUnit.Framework;
using UnityEngine;
using System.Collections.Generic;
using UnityEditor.VFX.Operator;
using UnityEngine.Experimental.VFX;
using UnityEditor.VFX.Block;
namespace UnityEditor.VFX.Test
{
[TestFixture]
internal class VFXSpacePropagationTest
{
public static IEnumerable<VFXExpression> CollectParentExpression(VFXExpression expression, HashSet<VFXExpression> hashSet = null)
{
if (expression != null)
{
if (hashSet == null)
{
hashSet = new HashSet<VFXExpression>();
}
if (!hashSet.Contains(expression))
{
hashSet.Add(expression);
yield return expression;
foreach (var parent in expression.parents)
{
var parents = CollectParentExpression(parent, hashSet);
foreach (var exp in parents)
{
yield return exp;
}
}
}
}
}
[Test]
public void Sphere_Type_Should_Be_Spaceable()
{
var inline = ScriptableObject.CreateInstance<VFXInlineOperator>();
inline.SetSettingValue("m_Type", (SerializableType)typeof(Sphere));
Assert.IsTrue(inline.inputSlots[0].spaceable);
}
[Test]
public void SpaceUniformisation_Between_World_And_Local()
{
var add = ScriptableObject.CreateInstance<Add>();
add.SetOperandType(0, typeof(Position));
add.SetOperandType(1, typeof(Position));
Assert.AreEqual(add.outputSlots[0].property.type, typeof(Position));
Assert.AreEqual(add.outputSlots[0].space, VFXCoordinateSpace.Local);
add.inputSlots[0].space = VFXCoordinateSpace.World;
Assert.AreEqual(add.inputSlots[0].space, VFXCoordinateSpace.World);
Assert.AreEqual(add.inputSlots[1].space, VFXCoordinateSpace.Local);
Assert.AreEqual(add.outputSlots[0].space, VFXCoordinateSpace.World);
var context = new VFXExpression.Context(VFXExpressionContextOption.CPUEvaluation);
var result = context.Compile(add.outputSlots[0].GetExpression());
var allExpr = CollectParentExpression(result).ToArray();
Assert.IsTrue(allExpr.Count(o =>
{
return o.operation == VFXExpressionOperation.LocalToWorld;
}) == 1);
}
#pragma warning disable 0414
private static Type[] SpaceTransmissionType = { typeof(Position), typeof(Sphere) };
#pragma warning restore 0414
[Test]
public void SpaceTransmission_From_An_Operator_To_Another([ValueSource("SpaceTransmissionType")] Type type)
{
var position_A = ScriptableObject.CreateInstance<VFXInlineOperator>();
var position_B = ScriptableObject.CreateInstance<VFXInlineOperator>();
position_A.SetSettingValue("m_Type", (SerializableType)type);
position_B.SetSettingValue("m_Type", (SerializableType)type);
position_A.inputSlots[0].space = VFXCoordinateSpace.World;
Assert.AreEqual(VFXCoordinateSpace.World, position_A.outputSlots[0].space);
position_B.inputSlots[0].space = VFXCoordinateSpace.Local;
Assert.AreEqual(VFXCoordinateSpace.Local, position_B.outputSlots[0].space);
position_B.inputSlots[0].Link(position_A.outputSlots[0]);
Assert.AreEqual(VFXCoordinateSpace.World, position_B.outputSlots[0].space);
position_A.inputSlots[0].space = VFXCoordinateSpace.Local;
Assert.AreEqual(VFXCoordinateSpace.Local, position_B.outputSlots[0].space);
}
[Test]
public void SpaceConversion_Vector3_To_ArcSphere_Center_DoesntExcept_Conversion()
{
var rotate3D = ScriptableObject.CreateInstance<Rotate3D>();
var arcSphere = ScriptableObject.CreateInstance<VFXInlineOperator>();
arcSphere.SetSettingValue("m_Type", (SerializableType)typeof(ArcSphere));
arcSphere.inputSlots[0][0][0].Link(rotate3D.outputSlots[0]); //link result of rotate3D to center of arcSphere
var context = new VFXExpression.Context(VFXExpressionContextOption.CPUEvaluation);
var resultCenter = context.Compile(arcSphere.inputSlots[0][0][0].GetExpression());
var allExprCenter = CollectParentExpression(resultCenter).ToArray();
Assert.IsFalse(allExprCenter.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal)); //everything is within the same space by default
arcSphere.inputSlots[0].space = VFXCoordinateSpace.World;
resultCenter = context.Compile(arcSphere.inputSlots[0][0][0].GetExpression());
allExprCenter = CollectParentExpression(resultCenter).ToArray();
Assert.IsTrue(allExprCenter.Count(o => o.operation == VFXExpressionOperation.LocalToWorld) == 1);
}
[Test]
public void SpaceConversion_Sphere_Unexpected_Linking_MasterSlot()
{
var sphere_A = ScriptableObject.CreateInstance<VFXInlineOperator>();
var sphere_B = ScriptableObject.CreateInstance<VFXInlineOperator>();
sphere_A.SetSettingValue("m_Type", (SerializableType)typeof(Sphere));
sphere_B.SetSettingValue("m_Type", (SerializableType)typeof(Sphere));
sphere_A.inputSlots[0].space = VFXCoordinateSpace.World;
sphere_B.inputSlots[0].space = VFXCoordinateSpace.Local;
Assert.AreEqual(VFXCoordinateSpace.World, sphere_A.outputSlots[0].space);
Assert.AreEqual(VFXCoordinateSpace.Local, sphere_B.outputSlots[0].space);
sphere_B.inputSlots[0][1].Link(sphere_A.outputSlots[0][1]); //link radius to other radius
Assert.AreEqual(VFXCoordinateSpace.Local, sphere_B.outputSlots[0].space);
var context = new VFXExpression.Context(VFXExpressionContextOption.CPUEvaluation);
var resultCenter = context.Compile(sphere_B.outputSlots[0][0].GetExpression());
var resultRadius = context.Compile(sphere_B.outputSlots[0][1].GetExpression());
var allExprCenter = CollectParentExpression(resultCenter).ToArray();
var allExprRadius = CollectParentExpression(resultRadius).ToArray();
Assert.IsFalse(allExprCenter.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
Assert.IsFalse(allExprRadius.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
}
[Test]
public void SpaceConversion_Sphere_Expected_Linking_Subslot()
{
var sphere_A = ScriptableObject.CreateInstance<VFXInlineOperator>();
var sphere_B = ScriptableObject.CreateInstance<VFXInlineOperator>();
sphere_A.SetSettingValue("m_Type", (SerializableType)typeof(Sphere));
sphere_B.SetSettingValue("m_Type", (SerializableType)typeof(Sphere));
sphere_A.inputSlots[0][0].value = new Vector3(1, 2, 3);
sphere_A.inputSlots[0].space = VFXCoordinateSpace.World;
sphere_B.inputSlots[0][0].value = new Vector3(4, 5, 6);
sphere_B.inputSlots[0].space = VFXCoordinateSpace.Local;
Assert.AreEqual(VFXCoordinateSpace.World, sphere_A.outputSlots[0].space);
Assert.AreEqual(VFXCoordinateSpace.Local, sphere_B.outputSlots[0].space);
sphere_B.inputSlots[0][0].Link(sphere_A.outputSlots[0][0]); //link sphere center to other sphere center
Assert.AreEqual(VFXCoordinateSpace.Local, sphere_B.outputSlots[0].space);
var allExprCenter = CollectParentExpression(sphere_B.outputSlots[0][0].GetExpression()).ToArray();
var allExprRadius = CollectParentExpression(sphere_B.outputSlots[0][1].GetExpression()).ToArray();
Assert.IsTrue(allExprCenter.Count(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal) == 1);
Assert.IsFalse(allExprRadius.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
}
[Test]
public void SpaceConversion_Position_Unexpected_Linking_Subslot()
{
var position_A = ScriptableObject.CreateInstance<VFXInlineOperator>();
var position_B = ScriptableObject.CreateInstance<VFXInlineOperator>();
position_A.SetSettingValue("m_Type", (SerializableType)typeof(Position));
position_B.SetSettingValue("m_Type", (SerializableType)typeof(Position));
position_A.inputSlots[0][0].value = new Vector3(1, 2, 3);
position_A.inputSlots[0].space = VFXCoordinateSpace.World;
position_B.inputSlots[0][0].value = new Vector3(4, 5, 6);
position_B.inputSlots[0].space = VFXCoordinateSpace.Local;
for (int i = 0; i < 3; ++i)
{
position_A.outputSlots[0][0][i].Link(position_B.inputSlots[0][0][i]);
}
var allExprPosition = CollectParentExpression(position_B.outputSlots[0][0].GetExpression()).ToArray();
Assert.AreEqual(VFXCoordinateSpace.World, position_A.outputSlots[0].space);
Assert.AreEqual(VFXCoordinateSpace.Local, position_B.outputSlots[0].space);
Assert.IsFalse(allExprPosition.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
}
[Test]
public void SpaceConversion_Conversion_Expected_Linking_Position_To_Line()
{
var position_A = ScriptableObject.CreateInstance<VFXInlineOperator>();
var position_B = ScriptableObject.CreateInstance<VFXInlineOperator>();
position_A.SetSettingValue("m_Type", (SerializableType)typeof(Position));
position_B.SetSettingValue("m_Type", (SerializableType)typeof(Position));
position_A.inputSlots[0][0].value = new Vector3(1, 2, 3);
position_A.inputSlots[0].space = VFXCoordinateSpace.World;
position_B.inputSlots[0][0].value = new Vector3(4, 5, 6);
position_B.inputSlots[0].space = VFXCoordinateSpace.Local;
var line = ScriptableObject.CreateInstance<VFXInlineOperator>();
line.SetSettingValue("m_Type", (SerializableType)typeof(Line));
line.inputSlots[0].space = VFXCoordinateSpace.Local;
line.inputSlots[0][0].Link(position_A.outputSlots[0]);
line.inputSlots[0][1].Link(position_B.outputSlots[0]);
var lineOutputSlotA = CollectParentExpression(line.outputSlots[0][0].GetExpression()).ToArray();
var lineOutputSlotB = CollectParentExpression(line.outputSlots[0][1].GetExpression()).ToArray();
Assert.AreEqual(line.inputSlots[0].space, VFXCoordinateSpace.Local);
Assert.IsTrue(lineOutputSlotA.Count(o => o.operation == VFXExpressionOperation.WorldToLocal) == 1);
Assert.IsFalse(lineOutputSlotB.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
line.inputSlots[0].space = VFXCoordinateSpace.World;
lineOutputSlotA = CollectParentExpression(line.outputSlots[0][0].GetExpression()).ToArray();
lineOutputSlotB = CollectParentExpression(line.outputSlots[0][1].GetExpression()).ToArray();
Assert.AreEqual(line.inputSlots[0].space, VFXCoordinateSpace.World);
Assert.IsFalse(lineOutputSlotA.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
Assert.IsTrue(lineOutputSlotB.Count(o => o.operation == VFXExpressionOperation.LocalToWorld) == 1);
}
[Test]
public void SpaceConversion_Conversion_Expected_Between_Slot_Block_And_Context()
{
var initializeContext = ScriptableObject.CreateInstance<VFXBasicInitialize>();
var positionSphere = ScriptableObject.CreateInstance<PositionSphere>();
initializeContext.AddChild(positionSphere);
//Default is expected to be in same space between block & context
var slotSpherePositionExpressions = CollectParentExpression(positionSphere.inputSlots[0][0][0].GetExpression()).ToArray();
Assert.IsTrue(slotSpherePositionExpressions.Any());
Assert.IsFalse(slotSpherePositionExpressions.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
//Now switch space of block
initializeContext.space = VFXCoordinateSpace.World;
slotSpherePositionExpressions = CollectParentExpression(positionSphere.inputSlots[0][0][0].GetExpression()).ToArray();
Assert.IsTrue(slotSpherePositionExpressions.Count(o => o.operation == VFXExpressionOperation.LocalToWorld) == 1);
}
[Test]
public void SpaceConversion_Verify_Expected_Invalidation_Of_Space()
{
var inlineVector = ScriptableObject.CreateInstance<VFXInlineOperator>();
inlineVector.SetSettingValue("m_Type", (SerializableType)typeof(Vector3));
var transformSpace = ScriptableObject.CreateInstance<ChangeSpace>();
transformSpace.SetOperandType(typeof(Position));
transformSpace.outputSlots[0].Link(inlineVector.inputSlots[0]);
//Local => Local
var slotVectorExpression = CollectParentExpression(inlineVector.outputSlots[0].GetExpression()).ToArray();
Assert.AreEqual(VFXCoordinateSpace.Local, transformSpace.inputSlots[0].space);
Assert.IsFalse(slotVectorExpression.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
//World => Local
transformSpace.inputSlots[0].space = VFXCoordinateSpace.World;
slotVectorExpression = CollectParentExpression(inlineVector.outputSlots[0].GetExpression()).ToArray();
Assert.IsTrue(slotVectorExpression.Count(o => o.operation == VFXExpressionOperation.LocalToWorld) == 0);
Assert.IsTrue(slotVectorExpression.Count(o => o.operation == VFXExpressionOperation.WorldToLocal) == 1);
//World => World
transformSpace.SetSettingValue("m_targetSpace", VFXCoordinateSpace.World);
slotVectorExpression = CollectParentExpression(inlineVector.outputSlots[0].GetExpression()).ToArray();
Assert.IsFalse(slotVectorExpression.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
//Local => World
transformSpace.inputSlots[0].space = VFXCoordinateSpace.Local;
slotVectorExpression = CollectParentExpression(inlineVector.outputSlots[0].GetExpression()).ToArray();
Assert.IsTrue(slotVectorExpression.Count(o => o.operation == VFXExpressionOperation.LocalToWorld) == 1);
Assert.IsTrue(slotVectorExpression.Count(o => o.operation == VFXExpressionOperation.WorldToLocal) == 0);
}
[Test]
public void SpaceConversion_Verify_Direction_Use_TransformDir()
{
var transformSpace = ScriptableObject.CreateInstance<ChangeSpace>();
transformSpace.SetOperandType(typeof(DirectionType));
transformSpace.SetSettingValue("m_targetSpace", VFXCoordinateSpace.World);
var expressions = CollectParentExpression(transformSpace.outputSlots[0].GetExpression()).ToArray();
Assert.IsTrue(expressions.Count(o => o is VFXExpressionTransformDirection) == 1);
}
[Test]
public void SpaceConversion_Verify_Vector_Use_TransformVec()
{
var transformSpace = ScriptableObject.CreateInstance<ChangeSpace>();
transformSpace.SetOperandType(typeof(Vector));
transformSpace.SetSettingValue("m_targetSpace", VFXCoordinateSpace.World);
var expressions = CollectParentExpression(transformSpace.outputSlots[0].GetExpression()).ToArray();
Assert.IsTrue(expressions.Count(o => o is VFXExpressionTransformVector) == 1);
}
[Test]
public void SpaceConversion_Propagation_Of_Space_With_Different_Type()
{
var position = ScriptableObject.CreateInstance<VFXInlineOperator>();
position.SetSettingValue("m_Type", (SerializableType)typeof(Position));
var vector = ScriptableObject.CreateInstance<VFXInlineOperator>();
vector.SetSettingValue("m_Type", (SerializableType)typeof(Vector));
var direction = ScriptableObject.CreateInstance<VFXInlineOperator>();
direction.SetSettingValue("m_Type", (SerializableType)typeof(DirectionType));
position.outputSlots[0].Link(vector.inputSlots[0]);
vector.outputSlots[0].Link(direction.inputSlots[0]);
Assert.AreEqual(VFXCoordinateSpace.Local, direction.outputSlots[0].space);
position.inputSlots[0].space = VFXCoordinateSpace.World;
Assert.AreEqual(VFXCoordinateSpace.World, direction.outputSlots[0].space);
}
[Test]
public void Space_Main_Camera()
{
var mainCamera = ScriptableObject.CreateInstance<MainCamera>();
mainCamera.Invalidate(VFXModel.InvalidationCause.kUIChanged);
Assert.AreEqual(VFXCoordinateSpace.World, mainCamera.outputSlots[0].space);
foreach (var slot in mainCamera.outputSlots[0].GetExpressionSlots())
{
var expressions = CollectParentExpression(slot.GetExpression()).ToArray();
Assert.IsFalse(expressions.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
}
}
[Test]
public void Space_MainCamera_To_Block_ProjectOnDepth()
{
var mainCamera = ScriptableObject.CreateInstance<MainCamera>();
var initialize = ScriptableObject.CreateInstance<VFXBasicInitialize>();
var projectOnDepth = ScriptableObject.CreateInstance<PositionDepth>();
projectOnDepth.SetSettingValue("camera", CameraMode.Custom);
initialize.space = VFXCoordinateSpace.World;
mainCamera.outputSlots[0].Link(projectOnDepth.inputSlots[0]);
initialize.AddChild(projectOnDepth);
foreach (var slot in mainCamera.outputSlots[0].GetExpressionSlots())
{
var expressions = CollectParentExpression(slot.GetExpression()).ToArray();
Assert.IsFalse(expressions.Any(o => o.operation == VFXExpressionOperation.LocalToWorld || o.operation == VFXExpressionOperation.WorldToLocal));
}
var slotMatrixMainCameraOutput = mainCamera.outputSlots[0][0];
var slotMatrixProjectInput = projectOnDepth.inputSlots[0][0];
var expressionSlotMatrix = CollectParentExpression(slotMatrixMainCameraOutput.GetExpression()).ToArray();
Assert.IsTrue(expressionSlotMatrix.Any(o => o.operation == VFXExpressionOperation.ExtractMatrixFromMainCamera));
Assert.IsFalse(expressionSlotMatrix.Any(o => o.operation == VFXExpressionOperation.WorldToLocal || o.operation == VFXExpressionOperation.LocalToWorld));
expressionSlotMatrix = CollectParentExpression(slotMatrixProjectInput.GetExpression()).ToArray();
Assert.IsTrue(expressionSlotMatrix.Any(o => o.operation == VFXExpressionOperation.ExtractMatrixFromMainCamera));
Assert.IsFalse(expressionSlotMatrix.Any(o => o.operation == VFXExpressionOperation.WorldToLocal || o.operation == VFXExpressionOperation.LocalToWorld));
initialize.space = VFXCoordinateSpace.Local;
expressionSlotMatrix = CollectParentExpression(slotMatrixMainCameraOutput.GetExpression()).ToArray();
Assert.IsTrue(expressionSlotMatrix.Any(o => o.operation == VFXExpressionOperation.ExtractMatrixFromMainCamera));
Assert.IsFalse(expressionSlotMatrix.Any(o => o.operation == VFXExpressionOperation.WorldToLocal || o.operation == VFXExpressionOperation.LocalToWorld)); //never at this stage
expressionSlotMatrix = CollectParentExpression(slotMatrixProjectInput.GetExpression()).ToArray();
Assert.IsTrue(expressionSlotMatrix.Any(o => o.operation == VFXExpressionOperation.ExtractMatrixFromMainCamera));
Assert.IsTrue(expressionSlotMatrix.Any(o => o.operation == VFXExpressionOperation.WorldToLocal)); //context in local, transform World to Local is excpected
}
[Test]
public void Space_Slot_Sanitize_Still_Possible_Simple_Sphere()
{
var branch = ScriptableObject.CreateInstance<Operator.Branch>();
branch.SetOperandType(typeof(Sphere));
var slot = branch.inputSlots[1];
Assert.AreEqual(typeof(Sphere), slot.property.type);
slot.space = VFXCoordinateSpace.World;
Assert.AreEqual(VFXCoordinateSpace.World, slot.space);
slot.AddChild(VFXSlot.Create(new VFXProperty(typeof(float), "hacked"), VFXSlot.Direction.kInput), -1, false);
slot.Sanitize(-1);
Assert.AreEqual(VFXCoordinateSpace.World, branch.inputSlots[1].space);
}
#pragma warning disable 0414
private static bool[] trueOrFalse = { true, false };
#pragma warning restore 0414
[Test]
public void Space_Slot_Sanitize_Still_Possible_ArcSphere([ValueSource("trueOrFalse")] bool fromParentToChildSanitize, [ValueSource("trueOrFalse")] bool hackChildSphere)
{
var branch = ScriptableObject.CreateInstance<Operator.Branch>();
branch.SetOperandType(typeof(ArcSphere));
var slot = branch.inputSlots[1];
Assert.AreEqual(typeof(ArcSphere), slot.property.type);
slot.space = VFXCoordinateSpace.World;
Assert.AreEqual(VFXCoordinateSpace.World, slot.space);
var slotToHack = hackChildSphere ? slot : slot.children.First();
slotToHack.AddChild(VFXSlot.Create(new VFXProperty(typeof(float), "hacked"), VFXSlot.Direction.kInput), -1, false);
if (fromParentToChildSanitize)
{
slot.Sanitize(-1);
slot.children.First().Sanitize(-1);
}
else
{
slot.children.First().Sanitize(-1);
slot.Sanitize(-1);
}
Assert.AreEqual(VFXCoordinateSpace.World, branch.inputSlots[1].space);
}
[Test]
public void Space_Slot_Sanitize_Still_Possible_Even_With_Linked_Slot([ValueSource("trueOrFalse")] bool reverseSanitizeOrdering, [ValueSource("trueOrFalse")] bool hackArcSphere, [ValueSource("trueOrFalse")] bool hackSphere)
{
var inlineOpSphere = ScriptableObject.CreateInstance<VFXInlineOperator>();
inlineOpSphere.SetSettingValue("m_Type", (SerializableType)typeof(Sphere));
inlineOpSphere.inputSlots[0].space = VFXCoordinateSpace.World;
var inlineOpArcSphere = ScriptableObject.CreateInstance<VFXInlineOperator>();
inlineOpArcSphere.SetSettingValue("m_Type", (SerializableType)typeof(ArcSphere));
inlineOpArcSphere.inputSlots[0].space = VFXCoordinateSpace.Local;
inlineOpSphere.outputSlots[0].Link(inlineOpArcSphere.inputSlots[0][0]);
Assert.IsTrue(inlineOpSphere.outputSlots[0].HasLink());
{
var allExpr = CollectParentExpression(inlineOpArcSphere.outputSlots[0][0][0].GetExpression()).ToArray();
Assert.IsTrue(allExpr.Count(o =>
{
return o.operation == VFXExpressionOperation.WorldToLocal;
}) == 1);
}
var objs = new HashSet<ScriptableObject>();
inlineOpSphere.CollectDependencies(objs);
inlineOpArcSphere.CollectDependencies(objs);
//Hacking type to simulation a change of type description
var allSlot = objs.OfType<VFXSlot>();
var hackedSlot = Enumerable.Empty<VFXSlot>();
if (hackArcSphere)
{
hackedSlot = hackedSlot.Concat(allSlot.Where(o => o.property.type == typeof(ArcSphere)));
}
if (hackSphere)
{
hackedSlot = hackedSlot.Concat(allSlot.Where(o => o.property.type == typeof(Sphere)));
}
foreach (var slotToHack in hackedSlot)
{
slotToHack.AddChild(VFXSlot.Create(new VFXProperty(typeof(float), "hacked"), VFXSlot.Direction.kInput), -1, false);
}
//Apply Sanitize
var objsEnumerable = objs.AsEnumerable<ScriptableObject>();
if (reverseSanitizeOrdering)
{
objsEnumerable = objsEnumerable.Reverse();
}
foreach (var obj in objsEnumerable.OfType<VFXModel>())
{
obj.Sanitize(-1);
}
if (!hackArcSphere)
{
Assert.IsTrue(inlineOpSphere.outputSlots[0].HasLink());
} // else, expected disconnection, parent has changed (log a message like this " didnt match the type layout. It is recreated and all links are lost.")
if (inlineOpSphere.outputSlots[0].HasLink())
{
var allExpr = CollectParentExpression(inlineOpArcSphere.outputSlots[0][0][0].GetExpression()).ToArray();
Assert.IsTrue(allExpr.Count(o =>
{
return o.operation == VFXExpressionOperation.WorldToLocal;
}) == 1);
}
}
}
}
#endif
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PrimerProObjects;
using PrimerProLocalization;
using GenLib;
namespace PrimerProForms
{
public partial class FormBuildableWordsTD : Form
{
private Font m_Font;
private GraphemeInventory m_GI;
private string m_Lang;
private ArrayList m_Graphemes;
private ArrayList m_Highlights;
private bool m_ParaFormat;
private bool m_NoDuplicates;
public FormBuildableWordsTD(GraphemeInventory gi, GraphemeTaughtOrder gto, Font fnt)
{
InitializeComponent();
m_Font = fnt;
m_GI = gi;
this.tbGraphemes.Text = this.GetGraphemesTaught(gto);
this.tbHighlights.Text = "";
this.chkParaFmt.Checked = false;
this.chkNoDup.Checked = true;
this.tbGraphemes.Font = m_Font;
this.tbHighlights.Font = m_Font;
m_Lang = "";
}
public FormBuildableWordsTD(GraphemeInventory gi, GraphemeTaughtOrder gto, Font fnt, LocalizationTable table, string Lang)
{
InitializeComponent();
m_Font = fnt;
m_GI = gi;
m_Lang = Lang;
this.tbGraphemes.Text = this.GetGraphemesTaught(gto);
this.tbHighlights.Text = "";
this.chkParaFmt.Checked = false;
this.chkNoDup.Checked = true;
this.tbGraphemes.Font = m_Font;
this.tbHighlights.Font = m_Font;
this.UpdateFormForLocalization(table);
}
public ArrayList Graphemes
{
get { return m_Graphemes; }
}
public ArrayList Highlights
{
get { return m_Highlights; }
}
public bool ParaFormat
{
get { return m_ParaFormat; }
}
public bool NoDuplicates
{
get { return m_NoDuplicates; }
}
private void btnOK_Click(object sender, EventArgs e)
{
string strGrfs = tbGraphemes.Text.Trim();
string strHlts = tbHighlights.Text.Trim();
if (strGrfs != "")
{
ArrayList alGrfs = null;
ArrayList alHlts = null;
alGrfs = Funct.ConvertStringToArrayList(strGrfs, Constants.Space.ToString());
alHlts = Funct.ConvertStringToArrayList(strHlts, Constants.Space.ToString());
m_Graphemes = alGrfs;
m_Highlights = alHlts;
m_ParaFormat = chkParaFmt.Checked;
m_NoDuplicates = chkNoDup.Checked;
}
else
{
m_Graphemes = null;
m_Highlights = null;
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
m_Graphemes = null;
m_Highlights = null;
m_ParaFormat = false;
m_NoDuplicates = false;
this.Close();
}
private void btnGraphemes_Click(object sender, EventArgs e)
{
GraphemeInventory gi = m_GI;
ArrayList alGI = new ArrayList();
ArrayList alSelection = new ArrayList();
for (int i = 0; i < gi.ConsonantCount(); i++)
alGI.Add(gi.GetConsonant(i).Symbol);
for (int i = 0; i < gi.VowelCount(); i++)
alGI.Add(gi.GetVowel(i).Symbol);
for (int i = 0; i < gi.ToneCount(); i++)
alGI.Add(gi.GetTone(i).Symbol);
for (int i = 0; i < gi.SyllographCount(); i++)
alGI.Add(gi.GetSyllograph(i).Symbol);
alSelection = Funct.ConvertStringToArrayList(this.tbGraphemes.Text, Constants.Space.ToString());
if ((m_Lang != "") && (m_Lang == OptionList.kFrench))
{
FormItemSelectionFrench form = new FormItemSelectionFrench(alGI, alSelection, labGrapheme.Text, m_Font);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
ArrayList al = form.Selection();
string strGraphemes = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
this.tbGraphemes.Text = strGraphemes;
}
}
else if ((m_Lang != "") && (m_Lang == OptionList.kSpanish))
{
FormItemSelectionSpanish form = new FormItemSelectionSpanish(alGI, alSelection, labGrapheme.Text, m_Font);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
ArrayList al = form.Selection();
string strGraphemes = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
this.tbGraphemes.Text = strGraphemes;
}
}
else
{
FormItemSelection form = new FormItemSelection(alGI, alSelection, labGrapheme.Text, m_Font);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
ArrayList al = form.Selection();
string strGraphemes = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
this.tbGraphemes.Text = strGraphemes;
}
}
}
private void btnHighlight_Click(object sender, EventArgs e)
{
ArrayList alAvailable = Funct.ConvertStringToArrayList(tbGraphemes.Text, Constants.Space.ToString());
ArrayList alHighlight = Funct.ConvertStringToArrayList(tbHighlights.Text, Constants.Space.ToString());
string strSymbol = "";
// remove underscores
for (int i = 0; i < alAvailable.Count; i++)
{
strSymbol = alAvailable[i].ToString();
strSymbol = strSymbol.Replace(Syllable.Underscore, "");
alAvailable[i] = strSymbol;
}
if ((m_Lang != "") && (m_Lang == OptionList.kFrench))
{
FormItemSelectionFrench form = new FormItemSelectionFrench(alAvailable, alHighlight, labHighlight.Text, m_Font);
form.ShowDialog();
if (form.DialogResult == DialogResult.OK)
{
ArrayList al = form.Selection();
this.tbHighlights.Text = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
}
}
else if ((m_Lang != "") && (m_Lang == OptionList.kSpanish))
{
FormItemSelectionSpanish form = new FormItemSelectionSpanish(alAvailable, alHighlight, labHighlight.Text, m_Font);
form.ShowDialog();
if (form.DialogResult == DialogResult.OK)
{
ArrayList al = form.Selection();
this.tbHighlights.Text = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
}
}
else
{
FormItemSelection form = new FormItemSelection(alAvailable, alHighlight, labHighlight.Text, m_Font);
form.ShowDialog();
if (form.DialogResult == DialogResult.OK)
{
ArrayList al = form.Selection();
this.tbHighlights.Text = Funct.ConvertArrayListToString(al, Constants.Space.ToString());
}
}
}
private void chkParaFmt_CheckedChanged(object sender, EventArgs e)
{
if (chkParaFmt.Checked)
{
tbHighlights.Enabled = false;
tbHighlights.Text = "";
}
else tbHighlights.Enabled = true;
}
private void chkNoDup_CheckedChanged(object sender, EventArgs e)
{
if (chkNoDup.Checked)
{
chkParaFmt.Enabled = false;
chkParaFmt.Checked = false;
}
else chkParaFmt.Enabled = true;
}
private string GetGraphemesTaught(GraphemeTaughtOrder gto)
{
string strText = "";
for (int i = 0; i < gto.Count(); i++)
{
strText += gto.GetGrapheme(i).Trim() + Constants.Space;
}
strText = strText.Trim();
return strText;
}
private void UpdateFormForLocalization(LocalizationTable table)
{
string strText = "";
strText = table.GetForm("FormBuildableWordsTDT");
if (strText != "")
this.Text = strText;
strText = table.GetForm("FormBuildableWordsTD0");
if (strText != "")
this.labTitle.Text = strText;
strText = table.GetForm("FormBuildableWordsTD1");
if (strText != "")
this.labGrapheme.Text = strText;
strText = table.GetForm("FormBuildableWordsTD3");
if (strText != "")
this.btnGraphemes.Text = strText;
strText = table.GetForm("FormBuildableWordsTD4");
if (strText != "")
this.labHighlight.Text = strText;
strText = table.GetForm("FormBuildableWordsTD6");
if (strText != "")
this.btnHighlight.Text = strText;
strText = table.GetForm("FormBuildableWordsTD7");
if (strText != "")
this.chkParaFmt.Text = strText;
//strText = table.GetForm("FormBuildableWordsTD7A");
//if (strText != "")
// this.chkNoDup.Text = strText;
strText = table.GetForm("FormBuildableWordsTD8");
if (strText != "")
this.btnOK.Text = strText;
strText = table.GetForm("FormBuildableWordsTD9");
if (strText != "")
this.btnCancel.Text = strText;
return;
}
}
}
| |
// LzmaEncoder.cs
using System;
namespace SevenZip.Compression.LZMA
{
using RangeCoder;
public class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties
{
enum EMatchFinderType
{
BT2,
BT4,
};
const UInt32 kIfinityPrice = 0xFFFFFFF;
static Byte[] g_FastPos = new Byte[1 << 11];
static Encoder()
{
const Byte kFastSlots = 22;
int c = 2;
g_FastPos[0] = 0;
g_FastPos[1] = 1;
for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++)
{
UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1));
for (UInt32 j = 0; j < k; j++, c++)
g_FastPos[c] = slotFast;
}
}
static UInt32 GetPosSlot(UInt32 pos)
{
if (pos < (1 << 11))
return g_FastPos[pos];
if (pos < (1 << 21))
return (UInt32)(g_FastPos[pos >> 10] + 20);
return (UInt32)(g_FastPos[pos >> 20] + 40);
}
static UInt32 GetPosSlot2(UInt32 pos)
{
if (pos < (1 << 17))
return (UInt32)(g_FastPos[pos >> 6] + 12);
if (pos < (1 << 27))
return (UInt32)(g_FastPos[pos >> 16] + 32);
return (UInt32)(g_FastPos[pos >> 26] + 52);
}
Base.State _state = new Base.State();
Byte _previousByte;
UInt32[] _repDistances = new UInt32[Base.kNumRepDistances];
void BaseInit()
{
_state.Init();
_previousByte = 0;
for (UInt32 i = 0; i < Base.kNumRepDistances; i++)
_repDistances[i] = 0;
}
const int kDefaultDictionaryLogSize = 22;
const UInt32 kNumFastBytesDefault = 0x20;
class LiteralEncoder
{
public struct Encoder2
{
BitEncoder[] m_Encoders;
public void Create() { m_Encoders = new BitEncoder[0x300]; }
public void Init() { for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); }
public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol)
{
uint context = 1;
for (int i = 7; i >= 0; i--)
{
uint bit = (uint)((symbol >> i) & 1);
m_Encoders[context].Encode(rangeEncoder, bit);
context = (context << 1) | bit;
}
}
public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol)
{
uint context = 1;
bool same = true;
for (int i = 7; i >= 0; i--)
{
uint bit = (uint)((symbol >> i) & 1);
uint state = context;
if (same)
{
uint matchBit = (uint)((matchByte >> i) & 1);
state += ((1 + matchBit) << 8);
same = (matchBit == bit);
}
m_Encoders[state].Encode(rangeEncoder, bit);
context = (context << 1) | bit;
}
}
public uint GetPrice(bool matchMode, byte matchByte, byte symbol)
{
uint price = 0;
uint context = 1;
int i = 7;
if (matchMode)
{
for (; i >= 0; i--)
{
uint matchBit = (uint)(matchByte >> i) & 1;
uint bit = (uint)(symbol >> i) & 1;
price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit);
context = (context << 1) | bit;
if (matchBit != bit)
{
i--;
break;
}
}
}
for (; i >= 0; i--)
{
uint bit = (uint)(symbol >> i) & 1;
price += m_Encoders[context].GetPrice(bit);
context = (context << 1) | bit;
}
return price;
}
}
Encoder2[] m_Coders;
int m_NumPrevBits;
int m_NumPosBits;
uint m_PosMask;
public void Create(int numPosBits, int numPrevBits)
{
if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits)
return;
m_NumPosBits = numPosBits;
m_PosMask = ((uint)1 << numPosBits) - 1;
m_NumPrevBits = numPrevBits;
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
m_Coders = new Encoder2[numStates];
for (uint i = 0; i < numStates; i++)
m_Coders[i].Create();
}
public void Init()
{
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
for (uint i = 0; i < numStates; i++)
m_Coders[i].Init();
}
public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte)
{ return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; }
}
class LenEncoder
{
RangeCoder.BitEncoder _choice = new RangeCoder.BitEncoder();
RangeCoder.BitEncoder _choice2 = new RangeCoder.BitEncoder();
RangeCoder.BitTreeEncoder[] _lowCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax];
RangeCoder.BitTreeEncoder[] _midCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax];
RangeCoder.BitTreeEncoder _highCoder = new RangeCoder.BitTreeEncoder(Base.kNumHighLenBits);
public LenEncoder()
{
for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++)
{
_lowCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumLowLenBits);
_midCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumMidLenBits);
}
}
public void Init(UInt32 numPosStates)
{
_choice.Init();
_choice2.Init();
for (UInt32 posState = 0; posState < numPosStates; posState++)
{
_lowCoder[posState].Init();
_midCoder[posState].Init();
}
_highCoder.Init();
}
public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
{
if (symbol < Base.kNumLowLenSymbols)
{
_choice.Encode(rangeEncoder, 0);
_lowCoder[posState].Encode(rangeEncoder, symbol);
}
else
{
symbol -= Base.kNumLowLenSymbols;
_choice.Encode(rangeEncoder, 1);
if (symbol < Base.kNumMidLenSymbols)
{
_choice2.Encode(rangeEncoder, 0);
_midCoder[posState].Encode(rangeEncoder, symbol);
}
else
{
_choice2.Encode(rangeEncoder, 1);
_highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols);
}
}
}
public void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32[] prices, UInt32 st)
{
UInt32 a0 = _choice.GetPrice0();
UInt32 a1 = _choice.GetPrice1();
UInt32 b0 = a1 + _choice2.GetPrice0();
UInt32 b1 = a1 + _choice2.GetPrice1();
UInt32 i = 0;
for (i = 0; i < Base.kNumLowLenSymbols; i++)
{
if (i >= numSymbols)
return;
prices[st + i] = a0 + _lowCoder[posState].GetPrice(i);
}
for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++)
{
if (i >= numSymbols)
return;
prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols);
}
for (; i < numSymbols; i++)
prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols);
}
};
const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols;
class LenPriceTableEncoder : LenEncoder
{
UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax];
UInt32 _tableSize;
UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax];
public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; }
public UInt32 GetPrice(UInt32 symbol, UInt32 posState)
{
return _prices[posState * Base.kNumLenSymbols + symbol];
}
void UpdateTable(UInt32 posState)
{
SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols);
_counters[posState] = _tableSize;
}
public void UpdateTables(UInt32 numPosStates)
{
for (UInt32 posState = 0; posState < numPosStates; posState++)
UpdateTable(posState);
}
public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
{
base.Encode(rangeEncoder, symbol, posState);
if (--_counters[posState] == 0)
UpdateTable(posState);
}
}
const UInt32 kNumOpts = 1 << 12;
class Optimal
{
public Base.State State;
public bool Prev1IsChar;
public bool Prev2;
public UInt32 PosPrev2;
public UInt32 BackPrev2;
public UInt32 Price;
public UInt32 PosPrev;
public UInt32 BackPrev;
public UInt32 Backs0;
public UInt32 Backs1;
public UInt32 Backs2;
public UInt32 Backs3;
public void MakeAsChar() { BackPrev = 0xFFFFFFFF; Prev1IsChar = false; }
public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; }
public bool IsShortRep() { return (BackPrev == 0); }
};
Optimal[] _optimum = new Optimal[kNumOpts];
LZ.IMatchFinder _matchFinder = null;
RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder();
RangeCoder.BitEncoder[] _isMatch = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
RangeCoder.BitEncoder[] _isRep = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRepG0 = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRepG1 = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRepG2 = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRep0Long = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates];
RangeCoder.BitEncoder[] _posEncoders = new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex];
RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits);
LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder();
LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder();
LiteralEncoder _literalEncoder = new LiteralEncoder();
UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2];
UInt32 _numFastBytes = kNumFastBytesDefault;
UInt32 _longestMatchLength;
UInt32 _numDistancePairs;
UInt32 _additionalOffset;
UInt32 _optimumEndIndex;
UInt32 _optimumCurrentIndex;
bool _longestMatchWasFound;
UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)];
UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits];
UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize];
UInt32 _alignPriceCount;
UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2);
int _posStateBits = 2;
UInt32 _posStateMask = (4 - 1);
int _numLiteralPosStateBits = 0;
int _numLiteralContextBits = 3;
UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize);
UInt32 _dictionarySizePrev = 0xFFFFFFFF;
UInt32 _numFastBytesPrev = 0xFFFFFFFF;
Int64 nowPos64;
bool _finished;
System.IO.Stream _inStream;
EMatchFinderType _matchFinderType = EMatchFinderType.BT4;
bool _writeEndMark = false;
bool _needReleaseMFStream;
void Create()
{
if (_matchFinder == null)
{
LZ.BinTree bt = new LZ.BinTree();
int numHashBytes = 4;
if (_matchFinderType == EMatchFinderType.BT2)
numHashBytes = 2;
bt.SetType(numHashBytes);
_matchFinder = bt;
}
_literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits);
if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes)
return;
_matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1);
_dictionarySizePrev = _dictionarySize;
_numFastBytesPrev = _numFastBytes;
}
public Encoder()
{
for (int i = 0; i < kNumOpts; i++)
_optimum[i] = new Optimal();
for (int i = 0; i < Base.kNumLenToPosStates; i++)
_posSlotEncoder[i] = new RangeCoder.BitTreeEncoder(Base.kNumPosSlotBits);
}
void SetWriteEndMarkerMode(bool writeEndMarker)
{
_writeEndMark = writeEndMarker;
}
void Init()
{
BaseInit();
_rangeEncoder.Init();
uint i;
for (i = 0; i < Base.kNumStates; i++)
{
for (uint j = 0; j <= _posStateMask; j++)
{
uint complexState = (i << Base.kNumPosStatesBitsMax) + j;
_isMatch[complexState].Init();
_isRep0Long[complexState].Init();
}
_isRep[i].Init();
_isRepG0[i].Init();
_isRepG1[i].Init();
_isRepG2[i].Init();
}
_literalEncoder.Init();
for (i = 0; i < Base.kNumLenToPosStates; i++)
_posSlotEncoder[i].Init();
for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++)
_posEncoders[i].Init();
_lenEncoder.Init((UInt32)1 << _posStateBits);
_repMatchLenEncoder.Init((UInt32)1 << _posStateBits);
_posAlignEncoder.Init();
_longestMatchWasFound = false;
_optimumEndIndex = 0;
_optimumCurrentIndex = 0;
_additionalOffset = 0;
}
void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs)
{
lenRes = 0;
numDistancePairs = _matchFinder.GetMatches(_matchDistances);
if (numDistancePairs > 0)
{
lenRes = _matchDistances[numDistancePairs - 2];
if (lenRes == _numFastBytes)
lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1],
Base.kMatchMaxLen - lenRes);
}
_additionalOffset++;
}
void MovePos(UInt32 num)
{
if (num > 0)
{
_matchFinder.Skip(num);
_additionalOffset += num;
}
}
UInt32 GetRepLen1Price(Base.State state, UInt32 posState)
{
return _isRepG0[state.Index].GetPrice0() +
_isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0();
}
UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState)
{
UInt32 price;
if (repIndex == 0)
{
price = _isRepG0[state.Index].GetPrice0();
price += _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
}
else
{
price = _isRepG0[state.Index].GetPrice1();
if (repIndex == 1)
price += _isRepG1[state.Index].GetPrice0();
else
{
price += _isRepG1[state.Index].GetPrice1();
price += _isRepG2[state.Index].GetPrice(repIndex - 2);
}
}
return price;
}
UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState)
{
UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState);
return price + GetPureRepPrice(repIndex, state, posState);
}
UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState)
{
UInt32 price;
UInt32 lenToPosState = Base.GetLenToPosState(len);
if (pos < Base.kNumFullDistances)
price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos];
else
price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] +
_alignPrices[pos & Base.kAlignMask];
return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState);
}
UInt32 Backward(out UInt32 backRes, UInt32 cur)
{
_optimumEndIndex = cur;
UInt32 posMem = _optimum[cur].PosPrev;
UInt32 backMem = _optimum[cur].BackPrev;
do
{
if (_optimum[cur].Prev1IsChar)
{
_optimum[posMem].MakeAsChar();
_optimum[posMem].PosPrev = posMem - 1;
if (_optimum[cur].Prev2)
{
_optimum[posMem - 1].Prev1IsChar = false;
_optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2;
_optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2;
}
}
UInt32 posPrev = posMem;
UInt32 backCur = backMem;
backMem = _optimum[posPrev].BackPrev;
posMem = _optimum[posPrev].PosPrev;
_optimum[posPrev].BackPrev = backCur;
_optimum[posPrev].PosPrev = cur;
cur = posPrev;
}
while (cur > 0);
backRes = _optimum[0].BackPrev;
_optimumCurrentIndex = _optimum[0].PosPrev;
return _optimumCurrentIndex;
}
UInt32[] reps = new UInt32[Base.kNumRepDistances];
UInt32[] repLens = new UInt32[Base.kNumRepDistances];
UInt32 GetOptimum(UInt32 position, out UInt32 backRes)
{
if (_optimumEndIndex != _optimumCurrentIndex)
{
UInt32 lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex;
backRes = _optimum[_optimumCurrentIndex].BackPrev;
_optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev;
return lenRes;
}
_optimumCurrentIndex = _optimumEndIndex = 0;
UInt32 lenMain, numDistancePairs;
if (!_longestMatchWasFound)
{
ReadMatchDistances(out lenMain, out numDistancePairs);
}
else
{
lenMain = _longestMatchLength;
numDistancePairs = _numDistancePairs;
_longestMatchWasFound = false;
}
UInt32 numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1;
if (numAvailableBytes < 2)
{
backRes = 0xFFFFFFFF;
return 1;
}
if (numAvailableBytes > Base.kMatchMaxLen)
numAvailableBytes = Base.kMatchMaxLen;
UInt32 repMaxIndex = 0;
UInt32 i;
for (i = 0; i < Base.kNumRepDistances; i++)
{
reps[i] = _repDistances[i];
repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen);
if (repLens[i] > repLens[repMaxIndex])
repMaxIndex = i;
}
if (repLens[repMaxIndex] >= _numFastBytes)
{
backRes = repMaxIndex;
UInt32 lenRes = repLens[repMaxIndex];
MovePos(lenRes - 1);
return lenRes;
}
if (lenMain >= _numFastBytes)
{
backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances;
MovePos(lenMain - 1);
return lenMain;
}
Byte currentByte = _matchFinder.GetIndexByte(0 - 1);
Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - 1));
if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2)
{
backRes = (UInt32)0xFFFFFFFF;
return 1;
}
_optimum[0].State = _state;
UInt32 posState = (position & _posStateMask);
_optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() +
_literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte);
_optimum[1].MakeAsChar();
UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1();
if (matchByte == currentByte)
{
UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState);
if (shortRepPrice < _optimum[1].Price)
{
_optimum[1].Price = shortRepPrice;
_optimum[1].MakeAsShortRep();
}
}
UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]);
if(lenEnd < 2)
{
backRes = _optimum[1].BackPrev;
return 1;
}
_optimum[1].PosPrev = 0;
_optimum[0].Backs0 = reps[0];
_optimum[0].Backs1 = reps[1];
_optimum[0].Backs2 = reps[2];
_optimum[0].Backs3 = reps[3];
UInt32 len = lenEnd;
do
_optimum[len--].Price = kIfinityPrice;
while (len >= 2);
for (i = 0; i < Base.kNumRepDistances; i++)
{
UInt32 repLen = repLens[i];
if (repLen < 2)
continue;
UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState);
do
{
UInt32 curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState);
Optimal optimum = _optimum[repLen];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = 0;
optimum.BackPrev = i;
optimum.Prev1IsChar = false;
}
}
while (--repLen >= 2);
}
UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0();
len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
if (len <= lenMain)
{
UInt32 offs = 0;
while (len > _matchDistances[offs])
offs += 2;
for (; ; len++)
{
UInt32 distance = _matchDistances[offs + 1];
UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState);
Optimal optimum = _optimum[len];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = 0;
optimum.BackPrev = distance + Base.kNumRepDistances;
optimum.Prev1IsChar = false;
}
if (len == _matchDistances[offs])
{
offs += 2;
if (offs == numDistancePairs)
break;
}
}
}
UInt32 cur = 0;
while (true)
{
cur++;
if (cur == lenEnd)
return Backward(out backRes, cur);
UInt32 newLen;
ReadMatchDistances(out newLen, out numDistancePairs);
if (newLen >= _numFastBytes)
{
_numDistancePairs = numDistancePairs;
_longestMatchLength = newLen;
_longestMatchWasFound = true;
return Backward(out backRes, cur);
}
position++;
UInt32 posPrev = _optimum[cur].PosPrev;
Base.State state;
if (_optimum[cur].Prev1IsChar)
{
posPrev--;
if (_optimum[cur].Prev2)
{
state = _optimum[_optimum[cur].PosPrev2].State;
if (_optimum[cur].BackPrev2 < Base.kNumRepDistances)
state.UpdateRep();
else
state.UpdateMatch();
}
else
state = _optimum[posPrev].State;
state.UpdateChar();
}
else
state = _optimum[posPrev].State;
if (posPrev == cur - 1)
{
if (_optimum[cur].IsShortRep())
state.UpdateShortRep();
else
state.UpdateChar();
}
else
{
UInt32 pos;
if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2)
{
posPrev = _optimum[cur].PosPrev2;
pos = _optimum[cur].BackPrev2;
state.UpdateRep();
}
else
{
pos = _optimum[cur].BackPrev;
if (pos < Base.kNumRepDistances)
state.UpdateRep();
else
state.UpdateMatch();
}
Optimal opt = _optimum[posPrev];
if (pos < Base.kNumRepDistances)
{
if (pos == 0)
{
reps[0] = opt.Backs0;
reps[1] = opt.Backs1;
reps[2] = opt.Backs2;
reps[3] = opt.Backs3;
}
else if (pos == 1)
{
reps[0] = opt.Backs1;
reps[1] = opt.Backs0;
reps[2] = opt.Backs2;
reps[3] = opt.Backs3;
}
else if (pos == 2)
{
reps[0] = opt.Backs2;
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs3;
}
else
{
reps[0] = opt.Backs3;
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs2;
}
}
else
{
reps[0] = (pos - Base.kNumRepDistances);
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs2;
}
}
_optimum[cur].State = state;
_optimum[cur].Backs0 = reps[0];
_optimum[cur].Backs1 = reps[1];
_optimum[cur].Backs2 = reps[2];
_optimum[cur].Backs3 = reps[3];
UInt32 curPrice = _optimum[cur].Price;
currentByte = _matchFinder.GetIndexByte(0 - 1);
matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1));
posState = (position & _posStateMask);
UInt32 curAnd1Price = curPrice +
_isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() +
_literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)).
GetPrice(!state.IsCharState(), matchByte, currentByte);
Optimal nextOptimum = _optimum[cur + 1];
bool nextIsChar = false;
if (curAnd1Price < nextOptimum.Price)
{
nextOptimum.Price = curAnd1Price;
nextOptimum.PosPrev = cur;
nextOptimum.MakeAsChar();
nextIsChar = true;
}
matchPrice = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1();
if (matchByte == currentByte &&
!(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0))
{
UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState);
if (shortRepPrice <= nextOptimum.Price)
{
nextOptimum.Price = shortRepPrice;
nextOptimum.PosPrev = cur;
nextOptimum.MakeAsShortRep();
nextIsChar = true;
}
}
UInt32 numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1;
numAvailableBytesFull = Math.Min(kNumOpts - 1 - cur, numAvailableBytesFull);
numAvailableBytes = numAvailableBytesFull;
if (numAvailableBytes < 2)
continue;
if (numAvailableBytes > _numFastBytes)
numAvailableBytes = _numFastBytes;
if (!nextIsChar && matchByte != currentByte)
{
// try Literal + rep0
UInt32 t = Math.Min(numAvailableBytesFull - 1, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateChar();
UInt32 posStateNext = (position + 1) & _posStateMask;
UInt32 nextRepMatchPrice = curAnd1Price +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1() +
_isRep[state2.Index].GetPrice1();
{
UInt32 offset = cur + 1 + lenTest2;
while (lenEnd < offset)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(
0, lenTest2, state2, posStateNext);
Optimal optimum = _optimum[offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = false;
}
}
}
}
UInt32 startLen = 2; // speed optimization
for (UInt32 repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++)
{
UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes);
if (lenTest < 2)
continue;
UInt32 lenTestTemp = lenTest;
do
{
while (lenEnd < cur + lenTest)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState);
Optimal optimum = _optimum[cur + lenTest];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur;
optimum.BackPrev = repIndex;
optimum.Prev1IsChar = false;
}
}
while(--lenTest >= 2);
lenTest = lenTestTemp;
if (repIndex == 0)
startLen = lenTest + 1;
if (lenTest < numAvailableBytesFull)
{
UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, reps[repIndex], t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateRep();
UInt32 posStateNext = (position + lenTest) & _posStateMask;
UInt32 curAndLenCharPrice =
repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() +
_literalEncoder.GetSubCoder(position + lenTest,
_matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true,
_matchFinder.GetIndexByte((Int32)((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1))),
_matchFinder.GetIndexByte((Int32)lenTest - 1));
state2.UpdateChar();
posStateNext = (position + lenTest + 1) & _posStateMask;
UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1();
UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1();
// for(; lenTest2 >= 2; lenTest2--)
{
UInt32 offset = lenTest + 1 + lenTest2;
while(lenEnd < cur + offset)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext);
Optimal optimum = _optimum[cur + offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + lenTest + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = true;
optimum.PosPrev2 = cur;
optimum.BackPrev2 = repIndex;
}
}
}
}
}
if (newLen > numAvailableBytes)
{
newLen = numAvailableBytes;
for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ;
_matchDistances[numDistancePairs] = newLen;
numDistancePairs += 2;
}
if (newLen >= startLen)
{
normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0();
while (lenEnd < cur + newLen)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 offs = 0;
while (startLen > _matchDistances[offs])
offs += 2;
for (UInt32 lenTest = startLen; ; lenTest++)
{
UInt32 curBack = _matchDistances[offs + 1];
UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState);
Optimal optimum = _optimum[cur + lenTest];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur;
optimum.BackPrev = curBack + Base.kNumRepDistances;
optimum.Prev1IsChar = false;
}
if (lenTest == _matchDistances[offs])
{
if (lenTest < numAvailableBytesFull)
{
UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, curBack, t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateMatch();
UInt32 posStateNext = (position + lenTest) & _posStateMask;
UInt32 curAndLenCharPrice = curAndLenPrice +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() +
_literalEncoder.GetSubCoder(position + lenTest,
_matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).
GetPrice(true,
_matchFinder.GetIndexByte((Int32)lenTest - (Int32)(curBack + 1) - 1),
_matchFinder.GetIndexByte((Int32)lenTest - 1));
state2.UpdateChar();
posStateNext = (position + lenTest + 1) & _posStateMask;
UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1();
UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1();
UInt32 offset = lenTest + 1 + lenTest2;
while (lenEnd < cur + offset)
_optimum[++lenEnd].Price = kIfinityPrice;
curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext);
optimum = _optimum[cur + offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + lenTest + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = true;
optimum.PosPrev2 = cur;
optimum.BackPrev2 = curBack + Base.kNumRepDistances;
}
}
}
offs += 2;
if (offs == numDistancePairs)
break;
}
}
}
}
}
bool ChangePair(UInt32 smallDist, UInt32 bigDist)
{
const int kDif = 7;
return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif));
}
void WriteEndMarker(UInt32 posState)
{
if (!_writeEndMark)
return;
_isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1);
_isRep[_state.Index].Encode(_rangeEncoder, 0);
_state.UpdateMatch();
UInt32 len = Base.kMatchMinLen;
_lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1;
UInt32 lenToPosState = Base.GetLenToPosState(len);
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
int footerBits = 30;
UInt32 posReduced = (((UInt32)1) << footerBits) - 1;
_rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits);
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask);
}
void Flush(UInt32 nowPos)
{
ReleaseMFStream();
WriteEndMarker(nowPos & _posStateMask);
_rangeEncoder.FlushData();
_rangeEncoder.FlushStream();
}
public void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished)
{
inSize = 0;
outSize = 0;
finished = true;
if (_inStream != null)
{
_matchFinder.SetStream(_inStream);
_matchFinder.Init();
_needReleaseMFStream = true;
_inStream = null;
if (_trainSize > 0)
_matchFinder.Skip(_trainSize);
}
if (_finished)
return;
_finished = true;
Int64 progressPosValuePrev = nowPos64;
if (nowPos64 == 0)
{
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
UInt32 len, numDistancePairs; // it's not used
ReadMatchDistances(out len, out numDistancePairs);
UInt32 posState = (UInt32)(nowPos64) & _posStateMask;
_isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0);
_state.UpdateChar();
Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset));
_literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte);
_previousByte = curByte;
_additionalOffset--;
nowPos64++;
}
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
while (true)
{
UInt32 pos;
UInt32 len = GetOptimum((UInt32)nowPos64, out pos);
UInt32 posState = ((UInt32)nowPos64) & _posStateMask;
UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState;
if (len == 1 && pos == 0xFFFFFFFF)
{
_isMatch[complexState].Encode(_rangeEncoder, 0);
Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset));
LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte);
if (!_state.IsCharState())
{
Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset));
subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte);
}
else
subCoder.Encode(_rangeEncoder, curByte);
_previousByte = curByte;
_state.UpdateChar();
}
else
{
_isMatch[complexState].Encode(_rangeEncoder, 1);
if (pos < Base.kNumRepDistances)
{
_isRep[_state.Index].Encode(_rangeEncoder, 1);
if (pos == 0)
{
_isRepG0[_state.Index].Encode(_rangeEncoder, 0);
if (len == 1)
_isRep0Long[complexState].Encode(_rangeEncoder, 0);
else
_isRep0Long[complexState].Encode(_rangeEncoder, 1);
}
else
{
_isRepG0[_state.Index].Encode(_rangeEncoder, 1);
if (pos == 1)
_isRepG1[_state.Index].Encode(_rangeEncoder, 0);
else
{
_isRepG1[_state.Index].Encode(_rangeEncoder, 1);
_isRepG2[_state.Index].Encode(_rangeEncoder, pos - 2);
}
}
if (len == 1)
_state.UpdateShortRep();
else
{
_repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
_state.UpdateRep();
}
UInt32 distance = _repDistances[pos];
if (pos != 0)
{
for (UInt32 i = pos; i >= 1; i--)
_repDistances[i] = _repDistances[i - 1];
_repDistances[0] = distance;
}
}
else
{
_isRep[_state.Index].Encode(_rangeEncoder, 0);
_state.UpdateMatch();
_lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
pos -= Base.kNumRepDistances;
UInt32 posSlot = GetPosSlot(pos);
UInt32 lenToPosState = Base.GetLenToPosState(len);
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
if (posSlot >= Base.kStartPosModelIndex)
{
int footerBits = (int)((posSlot >> 1) - 1);
UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits);
UInt32 posReduced = pos - baseVal;
if (posSlot < Base.kEndPosModelIndex)
RangeCoder.BitTreeEncoder.ReverseEncode(_posEncoders,
baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced);
else
{
_rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits);
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask);
_alignPriceCount++;
}
}
UInt32 distance = pos;
for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--)
_repDistances[i] = _repDistances[i - 1];
_repDistances[0] = distance;
_matchPriceCount++;
}
_previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset));
}
_additionalOffset -= len;
nowPos64 += len;
if (_additionalOffset == 0)
{
if (_matchPriceCount >= (1 << 7))
FillDistancesPrices();
if (_alignPriceCount >= Base.kAlignTableSize)
FillAlignPrices();
inSize = nowPos64;
outSize = _rangeEncoder.GetProcessedSizeAdd();
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
if (nowPos64 - progressPosValuePrev >= (1 << 12))
{
_finished = false;
finished = false;
return;
}
}
}
}
void ReleaseMFStream()
{
if (_matchFinder != null && _needReleaseMFStream)
{
_matchFinder.ReleaseStream();
_needReleaseMFStream = false;
}
}
void SetOutStream(System.IO.Stream outStream) { _rangeEncoder.SetStream(outStream); }
void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); }
void ReleaseStreams()
{
ReleaseMFStream();
ReleaseOutStream();
}
void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize)
{
_inStream = inStream;
_finished = false;
Create();
SetOutStream(outStream);
Init();
{
FillDistancesPrices();
FillAlignPrices();
}
_lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen);
_lenEncoder.UpdateTables((UInt32)1 << _posStateBits);
_repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen);
_repMatchLenEncoder.UpdateTables((UInt32)1 << _posStateBits);
nowPos64 = 0;
}
public void Code(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize, ICodeProgress progress)
{
_needReleaseMFStream = false;
try
{
SetStreams(inStream, outStream, inSize, outSize);
while (true)
{
Int64 processedInSize;
Int64 processedOutSize;
bool finished;
CodeOneBlock(out processedInSize, out processedOutSize, out finished);
if (finished)
return;
if (progress != null)
{
progress.SetProgress(processedInSize, processedOutSize);
}
}
}
finally
{
ReleaseStreams();
}
}
const int kPropSize = 5;
Byte[] properties = new Byte[kPropSize];
public void WriteCoderProperties(System.IO.Stream outStream)
{
properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits);
for (int i = 0; i < 4; i++)
properties[1 + i] = (Byte)(_dictionarySize >> (8 * i));
outStream.Write(properties, 0, kPropSize);
}
UInt32[] tempPrices = new UInt32[Base.kNumFullDistances];
UInt32 _matchPriceCount;
void FillDistancesPrices()
{
for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++)
{
UInt32 posSlot = GetPosSlot(i);
int footerBits = (int)((posSlot >> 1) - 1);
UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits);
tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders,
baseVal - posSlot - 1, footerBits, i - baseVal);
}
for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++)
{
UInt32 posSlot;
RangeCoder.BitTreeEncoder encoder = _posSlotEncoder[lenToPosState];
UInt32 st = (lenToPosState << Base.kNumPosSlotBits);
for (posSlot = 0; posSlot < _distTableSize; posSlot++)
_posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot);
for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++)
_posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << RangeCoder.BitEncoder.kNumBitPriceShiftBits);
UInt32 st2 = lenToPosState * Base.kNumFullDistances;
UInt32 i;
for (i = 0; i < Base.kStartPosModelIndex; i++)
_distancesPrices[st2 + i] = _posSlotPrices[st + i];
for (; i < Base.kNumFullDistances; i++)
_distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i];
}
_matchPriceCount = 0;
}
void FillAlignPrices()
{
for (UInt32 i = 0; i < Base.kAlignTableSize; i++)
_alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i);
_alignPriceCount = 0;
}
static string[] kMatchFinderIDs =
{
"BT2",
"BT4",
};
static int FindMatchFinder(string s)
{
for (int m = 0; m < kMatchFinderIDs.Length; m++)
if (s == kMatchFinderIDs[m])
return m;
return -1;
}
public void SetCoderProperties(CoderPropID[] propIDs, object[] properties)
{
for (UInt32 i = 0; i < properties.Length; i++)
{
object prop = properties[i];
switch (propIDs[i])
{
case CoderPropID.NumFastBytes:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 numFastBytes = (Int32)prop;
if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen)
throw new InvalidParamException();
_numFastBytes = (UInt32)numFastBytes;
break;
}
case CoderPropID.Algorithm:
{
break;
}
case CoderPropID.MatchFinder:
{
if (!(prop is String))
throw new InvalidParamException();
EMatchFinderType matchFinderIndexPrev = _matchFinderType;
int m = FindMatchFinder(((string)prop).ToUpper());
if (m < 0)
throw new InvalidParamException();
_matchFinderType = (EMatchFinderType)m;
if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType)
{
_dictionarySizePrev = 0xFFFFFFFF;
_matchFinder = null;
}
break;
}
case CoderPropID.DictionarySize:
{
const int kDicLogSizeMaxCompress = 30;
if (!(prop is Int32))
throw new InvalidParamException(); ;
Int32 dictionarySize = (Int32)prop;
if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) ||
dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress))
throw new InvalidParamException();
_dictionarySize = (UInt32)dictionarySize;
int dicLogSize;
for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++)
if (dictionarySize <= ((UInt32)(1) << dicLogSize))
break;
_distTableSize = (UInt32)dicLogSize * 2;
break;
}
case CoderPropID.PosStateBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax)
throw new InvalidParamException();
_posStateBits = (int)v;
_posStateMask = (((UInt32)1) << (int)_posStateBits) - 1;
break;
}
case CoderPropID.LitPosBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumLitPosStatesBitsEncodingMax)
throw new InvalidParamException();
_numLiteralPosStateBits = (int)v;
break;
}
case CoderPropID.LitContextBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumLitContextBitsMax)
throw new InvalidParamException(); ;
_numLiteralContextBits = (int)v;
break;
}
case CoderPropID.EndMarker:
{
if (!(prop is Boolean))
throw new InvalidParamException();
SetWriteEndMarkerMode((Boolean)prop);
break;
}
default:
throw new InvalidParamException();
}
}
}
uint _trainSize = 0;
public void SetTrainSize(uint trainSize)
{
_trainSize = trainSize;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="FontUnit.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.ComponentModel;
using System.Globalization;
using System.Security.Permissions;
using System.Web.Util;
/// <devdoc>
/// <para>Respresent the font unit.</para>
/// </devdoc>
[
TypeConverterAttribute(typeof(FontUnitConverter))
]
[Serializable]
public struct FontUnit {
/// <devdoc>
/// <para>Specifies an empty <see cref='System.Web.UI.WebControls.FontUnit'/>. This field is read only. </para>
/// </devdoc>
public static readonly FontUnit Empty = new FontUnit();
/// <devdoc>
/// <para>Specifies a <see cref='System.Web.UI.WebControls.FontUnit'/> with
/// <see langword='FontSize.Smaller'/> font. This field is read only. </para>
/// </devdoc>
public static readonly FontUnit Smaller = new FontUnit(FontSize.Smaller);
/// <devdoc>
/// <para>Specifies a <see cref='System.Web.UI.WebControls.FontUnit'/> with <see langword='FontSize.Larger'/>
/// font. This field is read only.</para>
/// </devdoc>
public static readonly FontUnit Larger = new FontUnit(FontSize.Larger);
/// <devdoc>
/// <para>Specifies a <see cref='System.Web.UI.WebControls.FontUnit'/> with
/// <see langword='FontSize.XXSmall'/> font. This field is read only.</para>
/// </devdoc>
public static readonly FontUnit XXSmall = new FontUnit(FontSize.XXSmall);
/// <devdoc>
/// <para>Specifies a <see cref='System.Web.UI.WebControls.FontUnit'/> with <see langword='FontSize.XSmall'/>
/// font. This field is read only.</para>
/// </devdoc>
public static readonly FontUnit XSmall = new FontUnit(FontSize.XSmall);
/// <devdoc>
/// <para>Specifies a <see cref='System.Web.UI.WebControls.FontUnit'/> with <see langword='FontSize.Small'/>
/// font. This field is read only.</para>
/// </devdoc>
public static readonly FontUnit Small = new FontUnit(FontSize.Small);
/// <devdoc>
/// <para>Specifies a <see cref='System.Web.UI.WebControls.FontUnit'/> with <see langword='FontSize.Medium'/>
/// font. This field is read only.</para>
/// </devdoc>
public static readonly FontUnit Medium = new FontUnit(FontSize.Medium);
/// <devdoc>
/// <para>Specifies a <see cref='System.Web.UI.WebControls.FontUnit'/> with <see langword='FontSize.Large'/>
/// font. This field is read only.</para>
/// </devdoc>
public static readonly FontUnit Large = new FontUnit(FontSize.Large);
/// <devdoc>
/// <para>Specifies a <see cref='System.Web.UI.WebControls.FontUnit'/> with <see langword='FontSize.XLarge'/>
/// font. This field is read only.</para>
/// </devdoc>
public static readonly FontUnit XLarge = new FontUnit(FontSize.XLarge);
/// <devdoc>
/// Specifies a <see cref='System.Web.UI.WebControls.FontUnit'/> with
/// <see langword='FontSize.XXLarge'/> font. This field is read only.
/// </devdoc>
public static readonly FontUnit XXLarge = new FontUnit(FontSize.XXLarge);
private readonly FontSize type;
private readonly Unit value;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.FontUnit'/> class with a <see cref='System.Web.UI.WebControls.FontSize'/>.</para>
/// </devdoc>
public FontUnit(FontSize type) {
if (type < FontSize.NotSet || type > FontSize.XXLarge) {
throw new ArgumentOutOfRangeException("type");
}
this.type = type;
if (this.type == FontSize.AsUnit) {
value = Unit.Point(10);
}
else {
value = Unit.Empty;
}
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.FontUnit'/> class with a <see cref='System.Web.UI.WebControls.Unit'/>.</para>
/// </devdoc>
public FontUnit(Unit value) {
this.type = FontSize.NotSet;
if (value.IsEmpty == false) {
this.type = FontSize.AsUnit;
this.value = value;
}
else {
this.value = Unit.Empty;
}
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.FontUnit'/> class with an integer value.</para>
/// </devdoc>
public FontUnit(int value) {
this.type = FontSize.AsUnit;
this.value = Unit.Point(value);
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.FontUnit'/> class with a double value.</para>
/// </devdoc>
public FontUnit(double value) : this(new Unit(value, UnitType.Point)) {
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.FontUnit'/> class with a double value.</para>
/// </devdoc>
public FontUnit(double value, UnitType type) : this(new Unit(value, type)) {
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.FontUnit'/> class with a string.</para>
/// </devdoc>
public FontUnit(string value) : this(value, CultureInfo.CurrentCulture) {
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public FontUnit(string value, CultureInfo culture) {
this.type = FontSize.NotSet;
this.value = Unit.Empty;
if (!String.IsNullOrEmpty(value)) {
// This is invariant because it acts like an enum with a number together.
// The enum part is invariant, but the number uses current culture.
char firstChar = Char.ToLower(value[0], CultureInfo.InvariantCulture);
if (firstChar == 'x') {
if (String.Equals(value, "xx-small", StringComparison.OrdinalIgnoreCase) ||
String.Equals(value, "xxsmall", StringComparison.OrdinalIgnoreCase)) {
this.type = FontSize.XXSmall;
return;
}
else if (String.Equals(value, "x-small", StringComparison.OrdinalIgnoreCase) ||
String.Equals(value, "xsmall", StringComparison.OrdinalIgnoreCase)) {
this.type = FontSize.XSmall;
return;
}
else if (String.Equals(value, "x-large", StringComparison.OrdinalIgnoreCase) ||
String.Equals(value, "xlarge", StringComparison.OrdinalIgnoreCase)) {
this.type = FontSize.XLarge;
return;
}
else if (String.Equals(value, "xx-large", StringComparison.OrdinalIgnoreCase) ||
String.Equals(value, "xxlarge", StringComparison.OrdinalIgnoreCase)) {
this.type = FontSize.XXLarge;
return;
}
}
else if (firstChar == 's') {
if (String.Equals(value, "small", StringComparison.OrdinalIgnoreCase)) {
this.type = FontSize.Small;
return;
}
else if (String.Equals(value, "smaller", StringComparison.OrdinalIgnoreCase)) {
this.type = FontSize.Smaller;
return;
}
}
else if (firstChar == 'l') {
if (String.Equals(value, "large", StringComparison.OrdinalIgnoreCase)) {
this.type = FontSize.Large;
return;
}
if (String.Equals(value, "larger", StringComparison.OrdinalIgnoreCase)) {
this.type = FontSize.Larger;
return;
}
}
else if ((firstChar == 'm') && String.Equals(value, "medium", StringComparison.OrdinalIgnoreCase)) {
this.type = FontSize.Medium;
return;
}
this.value = new Unit(value, culture, UnitType.Point);
this.type = FontSize.AsUnit;
}
}
/// <devdoc>
/// <para>Indicates whether the font size has been set.</para>
/// </devdoc>
public bool IsEmpty {
get {
return type == FontSize.NotSet;
}
}
/// <devdoc>
/// <para>Indicates the font size by type.</para>
/// </devdoc>
public FontSize Type {
get {
return type;
}
}
/// <devdoc>
/// <para>Indicates the font size by <see cref='System.Web.UI.WebControls.Unit'/>.</para>
/// </devdoc>
public Unit Unit {
get {
return value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int GetHashCode() {
return HashCodeCombiner.CombineHashCodes(type.GetHashCode(), value.GetHashCode());
}
/// <devdoc>
/// <para>Determines if the specified <see cref='System.Object' qualify='true'/> is equivilent to the <see cref='System.Web.UI.WebControls.FontUnit'/> represented by this instance.</para>
/// </devdoc>
public override bool Equals(object obj) {
if (obj == null || !(obj is FontUnit))
return false;
FontUnit f = (FontUnit)obj;
if ((f.type == type) && (f.value == value)) {
return true;
}
return false;
}
/// <devdoc>
/// <para>Compares two <see cref='System.Web.UI.WebControls.FontUnit'/> objects for equality.</para>
/// </devdoc>
public static bool operator ==(FontUnit left, FontUnit right) {
return ((left.type == right.type) && (left.value == right.value));
}
/// <devdoc>
/// <para>Compares two <see cref='System.Web.UI.WebControls.FontUnit'/> objects
/// for inequality.</para>
/// </devdoc>
public static bool operator !=(FontUnit left, FontUnit right) {
return ((left.type != right.type) || (left.value != right.value));
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static FontUnit Parse(string s) {
return new FontUnit(s, CultureInfo.InvariantCulture);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static FontUnit Parse(string s, CultureInfo culture) {
return new FontUnit(s, culture);
}
/// <devdoc>
/// <para>Creates a <see cref='System.Web.UI.WebControls.FontUnit'/> of type Point from an integer value.</para>
/// </devdoc>
public static FontUnit Point(int n) {
return new FontUnit(n);
}
/// <devdoc>
/// <para>Convert a <see cref='System.Web.UI.WebControls.FontUnit'/> to a string.</para>
/// </devdoc>
public override string ToString() {
return ToString((IFormatProvider)CultureInfo.CurrentCulture);
}
public string ToString(CultureInfo culture) {
return ToString((IFormatProvider)culture);
}
public string ToString(IFormatProvider formatProvider) {
string s = String.Empty;
if (IsEmpty)
return s;
switch (type) {
case FontSize.AsUnit:
s = value.ToString(formatProvider);
break;
case FontSize.XXSmall:
s = "XX-Small";
break;
case FontSize.XSmall:
s = "X-Small";
break;
case FontSize.XLarge:
s = "X-Large";
break;
case FontSize.XXLarge:
s = "XX-Large";
break;
default:
s = PropertyConverter.EnumToString(typeof(FontSize), type);
break;
}
return s;
}
/// <devdoc>
/// <para>Implicitly creates a <see cref='System.Web.UI.WebControls.FontUnit'/> of type Point from an integer value.</para>
/// </devdoc>
public static implicit operator FontUnit(int n) {
return FontUnit.Point(n);
}
}
}
| |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Don't warn about using .Handle; see comment below about SafeHandle
#pragma warning disable 618
using System;
using System.IO;
using System.Linq;
using PolyToolkit;
namespace PolyToolkitInternal {
public class RawImage {
public UnityEngine.Color32[] colorData;
public int colorWidth;
public int colorHeight;
public UnityEngine.TextureFormat format;
}
// ----------------------------------------------------------------------
public interface IBufferReader : IDisposable {
void Read(IntPtr destination, int readStart, int readSize);
/// <summary>
/// Reads bytes into the given byte buffer.
/// </summary>
/// <param name="destination">The byte buffer to write the results of the read into.</param>
/// <param name="destinationOffset">The offset in <c>destination</c> to start writing.</param>
/// <param name="readStart">The offset in the source buffer to start reading from.</param>
/// <param name="readSize">The number of bytes to read.</param>
void Read(byte[] destination, int destinationOffset, int readStart, int readSize);
/// <summary>
/// Returns the length of the content, if known in advance.
/// </summary>
/// <returns>The length of the content, or -1 if not known in advance.</returns>
long GetContentLength();
}
public interface IUriLoader {
/// <summary>
/// Returns an object that can read bytes from the passed uri
/// </summary>
/// <param name="uri">The relative uri to load</param>
IBufferReader Load(string uri);
/// <summary>
/// Returns true if the method LoadAsImage() is supported.
/// </summary>
bool CanLoadImages();
/// <summary>
/// Returns the contents of the passed uri as a decoded image.
/// Should raise NotSupportedException if not supported.
/// </summary>
/// <param name="uri">The relative uri to load</param>
RawImage LoadAsImage(string uri);
}
// ----------------------------------------------------------------------
public class Reader : IBufferReader {
private byte[] data;
public Reader(byte[] data) {
this.data = data;
}
public void Dispose() { }
public void Read(IntPtr destination, int readStart, int readSize) {
System.Runtime.InteropServices.Marshal.Copy(
data, readStart, destination, readSize);
}
public void Read(byte[] dest, int destOffset, int readStart, int readSize) {
Buffer.BlockCopy(data, readStart, dest, destOffset, readSize);
}
public long GetContentLength() {
return data.Length;
}
}
/// Performs reads just-in-time from a FileStream.
public class BufferedStreamLoader : IUriLoader {
private string uriBase;
private int bufferSize;
public BufferedStreamLoader(string uriBase, int bufferSize=4096) {
this.uriBase = uriBase;
this.bufferSize = bufferSize;
}
public IBufferReader Load(string uri) {
string path = Path.Combine(uriBase, uri);
long length = new FileInfo(path).Length;
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return new BufferedStreamReader(stream, bufferSize, length);
}
public bool CanLoadImages() { return false; }
public RawImage LoadAsImage(string uri) { throw new NotSupportedException(); }
}
// URI Loader that loads files from the file system, but maps paths to hashed file names.
// This allows the "virtual" file system to map cleanly to a flat folder of files that
// are named after the MD5 hashes of each path.
public class HashedPathBufferedStreamLoader : IUriLoader {
private string uriBase;
private int bufferSize;
public HashedPathBufferedStreamLoader(string uriBase, int bufferSize=4096) {
this.uriBase = uriBase;
this.bufferSize = bufferSize;
}
public bool CanLoadImages() { return false; }
public RawImage LoadAsImage(string uri) { throw new NotSupportedException(); }
public IBufferReader Load(string uri) {
uri = PolyInternalUtils.ConvertFilePathToHash(uri);
string path = Path.Combine(uriBase, uri);
long length = new FileInfo(path).Length;
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return new BufferedStreamReader(stream, bufferSize, length);
}
}
/// Takes an arbitrary seekable stream and reads it chunk-by-chunk,
/// because there's otherwise no way to read into an IntPtr.
///
/// PRO: doesn't need to buffer the entire .bin into memory
/// CON: still needs a tiny buffer to stage the data
/// CON: an extra copy
sealed class BufferedStreamReader : IBufferReader {
Stream stream;
byte[] tempBuffer;
long contentLength;
// Takes ownership of the stream
public BufferedStreamReader(Stream stream, int bufferSize, long contentLength) {
this.stream = stream;
this.tempBuffer = new byte[bufferSize];
this.contentLength = contentLength;
}
public void Dispose() {
if (stream != null) { stream.Dispose(); }
}
public void Read(IntPtr destination, int readStart, int readSize) {
stream.Seek(readStart, SeekOrigin.Begin);
// Invariant: (destination + readSize) == (currentDestination + currentReadSize)
int currentReadSize = readSize;
// operator + (IntPtr, int) didn't come along until .net 4
Int64 currentDestination = destination.ToInt64();
while (currentReadSize > 0) {
int numRead = stream.Read(tempBuffer, 0, Math.Min(currentReadSize, tempBuffer.Length));
if (numRead <= 0) {
break;
}
System.Runtime.InteropServices.Marshal.Copy(
tempBuffer, 0, (IntPtr)currentDestination, numRead);
currentReadSize -= numRead;
currentDestination += numRead;
}
}
public void Read(byte[] dest, int destOffset, int readStart, int readSize) {
stream.Seek(readStart, SeekOrigin.Begin);
while (readSize > 0) {
int bytesRead = stream.Read(dest, destOffset, readSize);
if (bytesRead <= 0) break;
destOffset += bytesRead;
readSize -= bytesRead;
}
}
public long GetContentLength() {
return contentLength;
}
}
// ----------------------------------------------------------------------
/// Fully-buffers the data to memory, then reads chunks out of it.
public class FullyBufferedLoader : IUriLoader {
private string uriBase;
public FullyBufferedLoader(string uriBase) {
this.uriBase = uriBase;
}
public IBufferReader Load(string uri) {
return new Reader(File.ReadAllBytes(Path.Combine(uriBase, uri)));
}
public bool CanLoadImages() { return false; }
public RawImage LoadAsImage(string uri) { throw new NotSupportedException(); }
}
// ----------------------------------------------------------------------
// Load "files" from a PolyFormat
public class FormatLoader : IUriLoader {
private PolyFormat format;
public FormatLoader(PolyFormat format) {
this.format = format;
}
public IBufferReader Load(string uri) {
// The file loader throws a FileNotFound exception if it's not found
// Analagously, this throws some sort of linq exception if there is no First()
var resource = format.resources.Where(r => r.relativePath == uri).First();
return new Reader(resource.contents);
}
public bool CanLoadImages() { return false; }
public RawImage LoadAsImage(string uri) { throw new NotSupportedException(); }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using StorageDemo.Api.Areas.HelpPage.ModelDescriptions;
using StorageDemo.Api.Areas.HelpPage.Models;
namespace StorageDemo.Api.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// <copyright file="StepDefinition.cs" company="Jason Diamond">
//
// Copyright (c) 2009-2010 Jason Diamond
//
// This source code is released under the MIT License.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
namespace BehaveN
{
/// <summary>
/// Represents a step definition.
/// </summary>
[DebuggerDisplay("{_methodInfo}")]
public class StepDefinition
{
/// <summary>
/// Initializes a new instance of the <see cref="StepDefinition"/> class.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="methodInfo">The method info.</param>
public StepDefinition(object target, MethodInfo methodInfo)
{
_target = target;
_methodInfo = methodInfo;
_regexes = new List<Regex>();
_regexes.Add(new Regex("^" + PatternMaker.GetPattern(_methodInfo) + "$", RegexOptions.IgnoreCase));
foreach (StepAttribute stepAttribute in Attribute.GetCustomAttributes(_methodInfo, typeof(StepAttribute)))
{
_regexes.Add(new Regex("^" + PatternMaker.GetPattern(stepAttribute.Text, _methodInfo) + "$", RegexOptions.IgnoreCase));
}
}
private object _target;
private MethodInfo _methodInfo;
private List<Regex> _regexes;
/// <summary>
/// Tries to execute the step.
/// </summary>
/// <param name="step">The step.</param>
/// <returns>True if the step was able to be executed.</returns>
public bool TryExecute(Step step)
{
Match m = GetMatch(step);
if (!m.Success)
return false;
object[] parameters = GetParametersForMethodFromMatch(m, step.Block, step.Exception);
Invoke(parameters);
CheckOutputParameters(m, step, parameters);
return true;
}
/// <summary>
/// Gets the name of the method.
/// </summary>
/// <value>The name of the method.</value>
public string MethodName
{
get { return _methodInfo.Name; }
}
/// <summary>
/// Determines if the step definition matches the specified step.
/// </summary>
/// <param name="step">The step.</param>
/// <returns>True or false.</returns>
public bool Matches(Step step)
{
return GetMatch(step).Success;
}
private static readonly Regex firstWordReplacer = new Regex(@"^\S+");
private Match GetMatch(Step step)
{
string text = firstWordReplacer.Replace(step.Text, step.Type.ToString());
text = StringExtensions.RemovePunctuationFromOutsideQuotedParts(text);
foreach (var regex in _regexes)
{
Match m = regex.Match(text);
if (m.Success)
return m;
}
return Match.Empty;
}
private object[] GetParametersForMethodFromMatch(Match match, IBlock block, Exception e)
{
object[] parameters = null;
if (_methodInfo.GetParameters().Length > 0)
{
parameters = new object[_methodInfo.GetParameters().Length];
int i = 0;
foreach (ParameterInfo pi in _methodInfo.GetParameters())
{
if (pi.ParameterType == typeof (Exception))
{
parameters[i] = e;
}
else if (!pi.IsOut)
{
object parameter = GetParameterFromMatch(pi, match, block);
if (parameter != null)
{
parameters[i] = parameter;
}
}
i++;
}
}
return parameters;
}
private object GetParameterFromMatch(ParameterInfo pi, Match match, IBlock block)
{
if (InlineTypes.InlineTypeExistsFor(pi.ParameterType))
{
if (match.Groups[pi.Name].Success)
{
string value = match.Groups[pi.Name].Value;
return ValueParser.ParseValue(value, pi.ParameterType);
}
}
else if (block != null && BlockTypes.BlockTypeExistsFor(pi.ParameterType))
{
BlockType blockType = BlockTypes.GetBlockTypeFor(pi.ParameterType);
return blockType.GetObject(pi.ParameterType, block);
}
return null;
}
private void Invoke(object[] parameters)
{
_methodInfo.Invoke(_target, parameters);
}
private void CheckOutputParameters(Match match, Step step, object[] parameters)
{
bool passed = true;
if (_methodInfo.GetParameters().Length > 0)
{
int i = 0;
foreach (ParameterInfo pi in _methodInfo.GetParameters())
{
if (pi.IsOut)
{
passed = CheckOutputParameter(match, step, pi, parameters[i]);
}
i++;
}
}
if (!passed)
{
throw new VerificationException(new Exception("One or more output parameters were not correct."));
}
}
private bool CheckOutputParameter(Match match, Step step, ParameterInfo pi, object parameter)
{
Type type = pi.ParameterType.GetElementType();
if (InlineTypes.InlineTypeExistsFor(type))
{
object expectedValue = ValueParser.ParseValue(match.Groups[pi.Name].Value, type);
object actualValue = parameter;
if (!object.Equals(actualValue, expectedValue))
{
Match m = GetMatch(step);
Group group = m.Groups[pi.Name];
step.Text = step.Text.Substring(0, group.Index)
+ string.Format("{0} (was {1})", expectedValue, actualValue)
+ step.Text.Substring(group.Index + group.Length);
return false;
}
}
else if (step.Block != null && BlockTypes.BlockTypeExistsFor(type))
{
return step.Block.Check(parameter);
}
return true;
}
/// <summary>
/// Determines whether the step definition can handle an exception.
/// </summary>
/// <returns>
/// <c>true</c> if the step can handler an exception; otherwise, <c>false</c>.
/// </returns>
public bool CanHandleException()
{
foreach (ParameterInfo pi in this._methodInfo.GetParameters())
{
if (pi.ParameterType == typeof(Exception))
{
return true;
}
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Xunit;
namespace Microsoft.AspNetCore.Authentication.Test.OpenIdConnect
{
/// <summary>
/// This helper class is used to check that query string parameters are as expected.
/// </summary>
internal class TestSettings
{
private readonly Action<OpenIdConnectOptions> _configureOptions;
private OpenIdConnectOptions _options;
public TestSettings() : this(configure: null)
{
}
public TestSettings(Action<OpenIdConnectOptions> configure)
{
_configureOptions = o =>
{
configure?.Invoke(o);
_options = o;
_options.BackchannelHttpHandler = new MockBackchannel();
};
}
public UrlEncoder Encoder => UrlEncoder.Default;
public string ExpectedState { get; set; }
public TestServer CreateTestServer(AuthenticationProperties properties = null, Func<HttpContext, Task> handler = null) => TestServerBuilder.CreateServer(_configureOptions, handler: handler, properties: properties);
public IDictionary<string, string> ValidateChallengeFormPost(string responseBody, params string[] parametersToValidate)
{
IDictionary<string, string> formInputs = null;
var errors = new List<string>();
var xdoc = XDocument.Parse(responseBody.Replace("doctype", "DOCTYPE"));
var forms = xdoc.Descendants("form");
if (forms.Count() != 1)
{
errors.Add("Only one form element is expected in response body.");
}
else
{
formInputs = forms.Single()
.Elements("input")
.ToDictionary(elem => elem.Attribute("name").Value,
elem => elem.Attribute("value").Value);
ValidateParameters(formInputs, parametersToValidate, errors, htmlEncoded: false);
}
if (errors.Any())
{
var buf = new StringBuilder();
buf.AppendLine("The challenge form post is not valid.");
// buf.AppendLine();
foreach (var error in errors)
{
buf.AppendLine(error);
}
Debug.WriteLine(buf.ToString());
Assert.True(false, buf.ToString());
}
return formInputs;
}
public IDictionary<string, string> ValidateSignoutFormPost(TestTransaction transaction, params string[] parametersToValidate)
{
IDictionary<string, string> formInputs = null;
var errors = new List<string>();
var xdoc = XDocument.Parse(transaction.ResponseText.Replace("doctype", "DOCTYPE"));
var forms = xdoc.Descendants("form");
if (forms.Count() != 1)
{
errors.Add("Only one form element is expected in response body.");
}
else
{
formInputs = forms.Single()
.Elements("input")
.ToDictionary(elem => elem.Attribute("name").Value,
elem => elem.Attribute("value").Value);
ValidateParameters(formInputs, parametersToValidate, errors, htmlEncoded: false);
}
if (errors.Any())
{
var buf = new StringBuilder();
buf.AppendLine("The signout form post is not valid.");
// buf.AppendLine();
foreach (var error in errors)
{
buf.AppendLine(error);
}
Debug.WriteLine(buf.ToString());
Assert.True(false, buf.ToString());
}
return formInputs;
}
public IDictionary<string, string> ValidateChallengeRedirect(Uri redirectUri, params string[] parametersToValidate) =>
ValidateRedirectCore(redirectUri, OpenIdConnectRequestType.Authentication, parametersToValidate);
public IDictionary<string, string> ValidateSignoutRedirect(Uri redirectUri, params string[] parametersToValidate) =>
ValidateRedirectCore(redirectUri, OpenIdConnectRequestType.Logout, parametersToValidate);
private IDictionary<string, string> ValidateRedirectCore(Uri redirectUri, OpenIdConnectRequestType requestType, string[] parametersToValidate)
{
var errors = new List<string>();
// Validate the authority
ValidateExpectedAuthority(redirectUri.AbsoluteUri, errors, requestType);
// Convert query to dictionary
var queryDict = string.IsNullOrEmpty(redirectUri.Query) ?
new Dictionary<string, string>() :
redirectUri.Query.TrimStart('?').Split('&').Select(part => part.Split('=')).ToDictionary(parts => parts[0], parts => parts[1]);
// Validate the query string parameters
ValidateParameters(queryDict, parametersToValidate, errors, htmlEncoded: true);
if (errors.Any())
{
var buf = new StringBuilder();
buf.AppendLine("The redirect uri is not valid.");
buf.AppendLine(redirectUri.AbsoluteUri);
foreach (var error in errors)
{
buf.AppendLine(error);
}
Debug.WriteLine(buf.ToString());
Assert.True(false, buf.ToString());
}
return queryDict;
}
private void ValidateParameters(
IDictionary<string, string> actualValues,
IEnumerable<string> parametersToValidate,
ICollection<string> errors,
bool htmlEncoded)
{
foreach (var paramToValidate in parametersToValidate)
{
switch (paramToValidate)
{
case OpenIdConnectParameterNames.ClientId:
ValidateClientId(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.ResponseType:
ValidateResponseType(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.ResponseMode:
ValidateResponseMode(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.Scope:
ValidateScope(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.RedirectUri:
ValidateRedirectUri(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.Resource:
ValidateResource(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.State:
ValidateState(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.SkuTelemetry:
ValidateSkuTelemetry(actualValues, errors);
break;
case OpenIdConnectParameterNames.VersionTelemetry:
ValidateVersionTelemetry(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.PostLogoutRedirectUri:
ValidatePostLogoutRedirectUri(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.MaxAge:
ValidateMaxAge(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.Prompt:
ValidatePrompt(actualValues, errors, htmlEncoded);
break;
default:
throw new InvalidOperationException($"Unknown parameter \"{paramToValidate}\".");
}
}
}
private void ValidateExpectedAuthority(string absoluteUri, ICollection<string> errors, OpenIdConnectRequestType requestType)
{
string expectedAuthority;
switch (requestType)
{
case OpenIdConnectRequestType.Token:
expectedAuthority = _options.Configuration?.TokenEndpoint ?? _options.Authority + @"/oauth2/token";
break;
case OpenIdConnectRequestType.Logout:
expectedAuthority = _options.Configuration?.EndSessionEndpoint ?? _options.Authority + @"/oauth2/logout";
break;
default:
expectedAuthority = _options.Configuration?.AuthorizationEndpoint ?? _options.Authority + @"/oauth2/authorize";
break;
}
if (!absoluteUri.StartsWith(expectedAuthority, StringComparison.Ordinal))
{
errors.Add($"ExpectedAuthority: {expectedAuthority}");
}
}
private void ValidateClientId(IDictionary<string, string> actualParams, ICollection<string> errors, bool htmlEncoded) =>
ValidateParameter(OpenIdConnectParameterNames.ClientId, _options.ClientId, actualParams, errors, htmlEncoded);
private void ValidateResponseType(IDictionary<string, string> actualParams, ICollection<string> errors, bool htmlEncoded) =>
ValidateParameter(OpenIdConnectParameterNames.ResponseType, _options.ResponseType, actualParams, errors, htmlEncoded);
private void ValidateResponseMode(IDictionary<string, string> actualParams, ICollection<string> errors, bool htmlEncoded) =>
ValidateParameter(OpenIdConnectParameterNames.ResponseMode, _options.ResponseMode, actualParams, errors, htmlEncoded);
private void ValidateScope(IDictionary<string, string> actualParams, ICollection<string> errors, bool htmlEncoded) =>
ValidateParameter(OpenIdConnectParameterNames.Scope, string.Join(" ", _options.Scope), actualParams, errors, htmlEncoded);
private void ValidateRedirectUri(IDictionary<string, string> actualParams, ICollection<string> errors, bool htmlEncoded) =>
ValidateParameter(OpenIdConnectParameterNames.RedirectUri, TestServerBuilder.TestHost + _options.CallbackPath, actualParams, errors, htmlEncoded);
private void ValidateResource(IDictionary<string, string> actualParams, ICollection<string> errors, bool htmlEncoded) =>
ValidateParameter(OpenIdConnectParameterNames.RedirectUri, _options.Resource, actualParams, errors, htmlEncoded);
private void ValidateState(IDictionary<string, string> actualParams, ICollection<string> errors, bool htmlEncoded) =>
ValidateParameter(OpenIdConnectParameterNames.State, ExpectedState, actualParams, errors, htmlEncoded);
private static void ValidateSkuTelemetry(IDictionary<string, string> actualParams, ICollection<string> errors)
{
if (!actualParams.ContainsKey(OpenIdConnectParameterNames.SkuTelemetry))
{
errors.Add($"Parameter {OpenIdConnectParameterNames.SkuTelemetry} is missing");
}
}
private void ValidateVersionTelemetry(IDictionary<string, string> actualParams, ICollection<string> errors, bool htmlEncoded) =>
ValidateParameter(OpenIdConnectParameterNames.VersionTelemetry, typeof(OpenIdConnectMessage).GetTypeInfo().Assembly.GetName().Version.ToString(), actualParams, errors, htmlEncoded);
private void ValidatePostLogoutRedirectUri(IDictionary<string, string> actualParams, ICollection<string> errors, bool htmlEncoded) =>
ValidateParameter(OpenIdConnectParameterNames.PostLogoutRedirectUri, "https://example.com/signout-callback-oidc", actualParams, errors, htmlEncoded);
private void ValidateMaxAge(IDictionary<string, string> actualQuery, ICollection<string> errors, bool htmlEncoded)
{
if(_options.MaxAge.HasValue)
{
Assert.Equal(TimeSpan.FromMinutes(20), _options.MaxAge.Value);
string expectedMaxAge = "1200";
ValidateParameter(OpenIdConnectParameterNames.MaxAge, expectedMaxAge, actualQuery, errors, htmlEncoded);
}
else if(actualQuery.ContainsKey(OpenIdConnectParameterNames.MaxAge))
{
errors.Add($"Parameter {OpenIdConnectParameterNames.MaxAge} is present but it should be absent");
}
}
private void ValidatePrompt(IDictionary<string, string> actualParams, ICollection<string> errors, bool htmlEncoded) =>
ValidateParameter(OpenIdConnectParameterNames.Prompt, _options.Prompt, actualParams, errors, htmlEncoded);
private void ValidateParameter(
string parameterName,
string expectedValue,
IDictionary<string, string> actualParams,
ICollection<string> errors,
bool htmlEncoded)
{
string actualValue;
if (actualParams.TryGetValue(parameterName, out actualValue))
{
if (htmlEncoded)
{
expectedValue = Encoder.Encode(expectedValue);
}
if (actualValue != expectedValue)
{
errors.Add($"Parameter {parameterName}'s expected value is '{expectedValue}' but its actual value is '{actualValue}'");
}
}
else
{
errors.Add($"Parameter {parameterName} is missing");
}
}
private class MockBackchannel : HttpMessageHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri.AbsoluteUri.Equals("https://login.microsoftonline.com/common/.well-known/openid-configuration"))
{
return await ReturnResource("wellknownconfig.json");
}
if (request.RequestUri.AbsoluteUri.Equals("https://login.microsoftonline.com/common/discovery/keys"))
{
return await ReturnResource("wellknownkeys.json");
}
throw new NotImplementedException();
}
private async Task<HttpResponseMessage> ReturnResource(string resource)
{
var resourceName = "Microsoft.AspNetCore.Authentication.Test.OpenIdConnect." + resource;
using (var stream = typeof(MockBackchannel).Assembly.GetManifestResourceStream(resourceName))
using (var reader = new StreamReader(stream))
{
var body = await reader.ReadToEndAsync();
var content = new StringContent(body, Encoding.UTF8, "application/json");
return new HttpResponseMessage()
{
Content = content,
};
}
}
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.10.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Groups Migration API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/google-apps/groups-migration/'>Groups Migration API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20140416 (0)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/google-apps/groups-migration/'>
* https://developers.google.com/google-apps/groups-migration/</a>
* <tr><th>Discovery Name<td>groupsmigration
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Groups Migration API can be found at
* <a href='https://developers.google.com/google-apps/groups-migration/'>https://developers.google.com/google-apps/groups-migration/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.GroupsMigration.v1
{
/// <summary>The GroupsMigration Service.</summary>
public class GroupsMigrationService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public GroupsMigrationService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public GroupsMigrationService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
archive = new ArchiveResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "groupsmigration"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/groups/v1/groups/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "groups/v1/groups/"; }
}
/// <summary>Available OAuth 2.0 scopes for use with the Groups Migration API.</summary>
public class Scope
{
/// <summary>Manage messages in groups on your domain</summary>
public static string AppsGroupsMigration = "https://www.googleapis.com/auth/apps.groups.migration";
}
private readonly ArchiveResource archive;
/// <summary>Gets the Archive resource.</summary>
public virtual ArchiveResource Archive
{
get { return archive; }
}
}
///<summary>A base abstract class for GroupsMigration requests.</summary>
public abstract class GroupsMigrationBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new GroupsMigrationBaseServiceRequest instance.</summary>
protected GroupsMigrationBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes GroupsMigration parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "archive" collection of methods.</summary>
public class ArchiveResource
{
private const string Resource = "archive";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ArchiveResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
/// <param name="groupId">The group ID</param>
public virtual InsertRequest Insert(string groupId)
{
return new InsertRequest(service, groupId);
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
public class InsertRequest : GroupsMigrationBaseServiceRequest<Google.Apis.GroupsMigration.v1.Data.Groups>
{
/// <summary>Constructs a new Insert request.</summary>
public InsertRequest(Google.Apis.Services.IClientService service, string groupId)
: base(service)
{
GroupId = groupId;
InitParameters();
}
/// <summary>The group ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "insert"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{groupId}/archive"; }
}
/// <summary>Initializes Insert parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"groupId", new Google.Apis.Discovery.Parameter
{
Name = "groupId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
/// <param name="groupId">The group ID</param>
/// <param name="stream">The stream to upload.</param>
/// <param name="contentType">The content type of the stream to upload.</param>
public virtual InsertMediaUpload Insert(string groupId, System.IO.Stream stream, string contentType)
{
return new InsertMediaUpload(service, groupId, stream, contentType);
}
/// <summary>Insert media upload which supports resumable upload.</summary>
public class InsertMediaUpload : Google.Apis.Upload.ResumableUpload<string, Google.Apis.GroupsMigration.v1.Data.Groups>
{
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and
/// reports. Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are
/// provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>The group ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupId { get; private set; }
/// <summary>Constructs a new Insert media upload instance.</summary>
public InsertMediaUpload(Google.Apis.Services.IClientService service, string
groupId, System.IO.Stream stream, string contentType)
: base(service, string.Format("/{0}/{1}{2}", "upload", service.BasePath, "{groupId}/archive"), "POST", stream, contentType)
{
GroupId = groupId;
}
}
}
}
namespace Google.Apis.GroupsMigration.v1.Data
{
/// <summary>JSON response template for groups migration API.</summary>
public class Groups : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The kind of insert resource this is.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The status of the insert request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("responseCode")]
public virtual string ResponseCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace xDockPanel
{
public class FloatWindow : Form, INestedPanesContainer, IDockDragSource
{
private NestedPaneCollection m_nestedPanes;
internal const int WM_CHECKDISPOSE = (int)(Win32.Msgs.WM_USER + 1);
internal protected FloatWindow(DockPanel dockPanel, DockPane pane)
{
InternalConstruct(dockPanel, pane, false, Rectangle.Empty);
}
internal protected FloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds)
{
InternalConstruct(dockPanel, pane, true, bounds);
}
private void InternalConstruct(DockPanel dockPanel, DockPane pane, bool boundsSpecified, Rectangle bounds)
{
if (dockPanel == null)
throw new Exception();
m_nestedPanes = new NestedPaneCollection(this);
FormBorderStyle = FormBorderStyle.SizableToolWindow;
ShowInTaskbar = false;
SuspendLayout();
if (boundsSpecified)
{
Bounds = bounds;
StartPosition = FormStartPosition.Manual;
}
else
{
StartPosition = FormStartPosition.WindowsDefaultLocation;
Size = dockPanel.DefaultFloatWindowSize;
}
m_dockPanel = dockPanel;
Owner = DockPanel.FindForm();
DockPanel.AddFloatWindow(this);
if (pane != null)
pane.FloatWindow = this;
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (DockPanel != null)
DockPanel.RemoveFloatWindow(this);
m_dockPanel = null;
}
base.Dispose(disposing);
}
private bool m_doubleClickTitleBarToDock = true;
public bool DoubleClickTitleBarToDock
{
get { return m_doubleClickTitleBarToDock; }
set { m_doubleClickTitleBarToDock = value; }
}
public NestedPaneCollection NestedPanes
{
get { return m_nestedPanes; }
}
public VisibleNestedPaneCollection VisibleNestedPanes
{
get { return NestedPanes.VisibleNestedPanes; }
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
public DockState DockState
{
get { return DockState.Float; }
}
public bool IsFloat
{
get { return DockState == DockState.Float; }
}
internal bool IsDockStateValid(DockState dockState)
{
foreach (DockPane pane in NestedPanes)
foreach (IDockContent content in pane.Contents)
if (!DockHelper.IsDockValid(dockState, content.DockHandler.DockAreas))
return false;
return true;
}
protected override void OnActivated(EventArgs e)
{
DockPanel.FloatWindows.BringWindowToFront(this);
base.OnActivated (e);
// Propagate the Activated event to the visible panes content objects
foreach (DockPane pane in VisibleNestedPanes)
foreach (IDockContent content in pane.Contents)
content.OnActivated(e);
}
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
// Propagate the Deactivate event to the visible panes content objects
foreach (DockPane pane in VisibleNestedPanes)
foreach (IDockContent content in pane.Contents)
content.OnDeactivate(e);
}
protected override void OnLayout(LayoutEventArgs levent)
{
VisibleNestedPanes.Refresh();
RefreshChanges();
Visible = (VisibleNestedPanes.Count > 0);
SetText();
base.OnLayout(levent);
}
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.Control.set_Text(System.String)")]
internal void SetText()
{
DockPane theOnlyPane = (VisibleNestedPanes.Count == 1) ? VisibleNestedPanes[0] : null;
if (theOnlyPane == null || theOnlyPane.ActiveContent == null)
{
Text = " "; // use " " instead of string.Empty because the whole title bar will disappear when ControlBox is set to false.
Icon = null;
}
else
{
Text = theOnlyPane.ActiveContent.DockHandler.TabText;
Icon = theOnlyPane.ActiveContent.DockHandler.Icon;
}
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
Rectangle rectWorkArea = SystemInformation.VirtualScreen;
if (y + height > rectWorkArea.Bottom)
y -= (y + height) - rectWorkArea.Bottom;
if (y < rectWorkArea.Top)
y += rectWorkArea.Top - y;
base.SetBoundsCore (x, y, width, height, specified);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case (int)Win32.Msgs.WM_NCLBUTTONDOWN:
{
if (IsDisposed)
return;
uint result = NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam);
if (result == 2) // HITTEST_CAPTION
{
Activate();
m_dockPanel.BeginDrag(this);
}
else
base.WndProc(ref m);
return;
}
case (int)Win32.Msgs.WM_NCRBUTTONDOWN:
{
uint result = NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam);
if (result == 2) // HITTEST_CAPTION
{
DockPane theOnlyPane = (VisibleNestedPanes.Count == 1) ? VisibleNestedPanes[0] : null;
if (theOnlyPane != null && theOnlyPane.ActiveContent != null)
{
theOnlyPane.ShowTabPageContextMenu(this, PointToClient(Control.MousePosition));
return;
}
}
base.WndProc(ref m);
return;
}
case (int)Win32.Msgs.WM_CLOSE:
if (NestedPanes.Count == 0)
{
base.WndProc(ref m);
return;
}
for (int i = NestedPanes.Count - 1; i >= 0; i--)
{
DockContentCollection contents = NestedPanes[i].Contents;
for (int j = contents.Count - 1; j >= 0; j--)
{
IDockContent content = contents[j];
if (content.DockHandler.DockState != DockState.Float)
continue;
if (!content.DockHandler.CloseButton)
continue;
if (content.DockHandler.HideOnClose)
content.DockHandler.Hide();
else
content.DockHandler.Close();
}
}
return;
case (int)Win32.Msgs.WM_NCLBUTTONDBLCLK:
{
uint result = !DoubleClickTitleBarToDock ? 0
: NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam);
if (result != 2) // HITTEST_CAPTION
{
base.WndProc(ref m);
return;
}
DockPanel.SuspendLayout(true);
// Restore to panel
foreach (DockPane pane in NestedPanes)
{
if (pane.DockState != DockState.Float)
continue;
pane.RestoreToPanel();
}
DockPanel.ResumeLayout(true, true);
return;
}
case WM_CHECKDISPOSE:
if (NestedPanes.Count == 0)
Dispose();
return;
}
base.WndProc(ref m);
}
internal void RefreshChanges()
{
if (IsDisposed)
return;
if (VisibleNestedPanes.Count == 0)
{
ControlBox = true;
return;
}
for (int i=VisibleNestedPanes.Count - 1; i>=0; i--)
{
DockContentCollection contents = VisibleNestedPanes[i].Contents;
for (int j=contents.Count - 1; j>=0; j--)
{
IDockContent content = contents[j];
if (content.DockHandler.DockState != DockState.Float)
continue;
if (content.DockHandler.CloseButton && content.DockHandler.CloseButtonVisible)
{
ControlBox = true;
return;
}
}
}
//Only if there is a ControlBox do we turn it off
//old code caused a flash of the window.
if (ControlBox)
ControlBox = false;
}
public virtual Rectangle DisplayingRectangle
{
get { return ClientRectangle; }
}
internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline)
{
if (VisibleNestedPanes.Count == 1)
{
DockPane pane = VisibleNestedPanes[0];
if (!dragSource.CanDockTo(pane))
return;
Point ptMouse = Control.MousePosition;
uint lParam = Win32Helper.MakeLong(ptMouse.X, ptMouse.Y);
if (NativeMethods.SendMessage(Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, lParam) == (uint)Win32.HitTest.HTCAPTION)
dockOutline.Show(VisibleNestedPanes[0], -1);
}
}
#region IDockDragSource Members
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
#endregion
bool IDockDragSource.IsDockStateValid(DockState dockState)
{
return IsDockStateValid(dockState);
}
bool IDockDragSource.CanDockTo(DockPane pane)
{
if (!IsDockStateValid(pane.DockState))
return false;
if (pane.FloatWindow == this)
return false;
return true;
}
private int m_preDragExStyle;
Rectangle IDockDragSource.BeginDrag(Point ptMouse)
{
m_preDragExStyle = NativeMethods.GetWindowLong(this.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE);
NativeMethods.SetWindowLong(this.Handle,
(int)Win32.GetWindowLongIndex.GWL_EXSTYLE,
m_preDragExStyle | (int)(Win32.WindowExStyles.WS_EX_TRANSPARENT | Win32.WindowExStyles.WS_EX_LAYERED) );
return Bounds;
}
void IDockDragSource.EndDrag()
{
NativeMethods.SetWindowLong(this.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE, m_preDragExStyle);
Invalidate(true);
NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCPAINT, 1, 0);
}
public void FloatAt(Rectangle floatWindowBounds)
{
Bounds = floatWindowBounds;
}
public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex)
{
if (dockStyle == DockStyle.Fill)
{
for (int i = NestedPanes.Count - 1; i >= 0; i--)
{
DockPane paneFrom = NestedPanes[i];
for (int j = paneFrom.Contents.Count - 1; j >= 0; j--)
{
IDockContent c = paneFrom.Contents[j];
c.DockHandler.Pane = pane;
if (contentIndex != -1)
pane.SetContentIndex(c, contentIndex);
c.DockHandler.Activate();
}
}
}
else
{
DockAlignment alignment = DockAlignment.Left;
if (dockStyle == DockStyle.Left)
alignment = DockAlignment.Left;
else if (dockStyle == DockStyle.Right)
alignment = DockAlignment.Right;
else if (dockStyle == DockStyle.Top)
alignment = DockAlignment.Top;
else if (dockStyle == DockStyle.Bottom)
alignment = DockAlignment.Bottom;
MergeNestedPanes(VisibleNestedPanes, pane.NestedPanesContainer.NestedPanes, pane, alignment, 0.5);
}
}
public void DockTo(DockPanel panel, DockStyle dockStyle)
{
if (panel != DockPanel)
return;
NestedPaneCollection nestedPanesTo = null;
if (dockStyle == DockStyle.Top)
nestedPanesTo = DockPanel.DockWindows[DockState.Top].NestedPanes;
else if (dockStyle == DockStyle.Bottom)
nestedPanesTo = DockPanel.DockWindows[DockState.Bottom].NestedPanes;
else if (dockStyle == DockStyle.Left)
nestedPanesTo = DockPanel.DockWindows[DockState.Left].NestedPanes;
else if (dockStyle == DockStyle.Right)
nestedPanesTo = DockPanel.DockWindows[DockState.Right].NestedPanes;
else if (dockStyle == DockStyle.Fill)
nestedPanesTo = DockPanel.DockWindows[DockState.Document].NestedPanes;
DockPane prevPane = null;
for (int i = nestedPanesTo.Count - 1; i >= 0; i--)
if (nestedPanesTo[i] != VisibleNestedPanes[0])
prevPane = nestedPanesTo[i];
MergeNestedPanes(VisibleNestedPanes, nestedPanesTo, prevPane, DockAlignment.Left, 0.5);
}
private static void MergeNestedPanes(VisibleNestedPaneCollection nestedPanesFrom, NestedPaneCollection nestedPanesTo, DockPane prevPane, DockAlignment alignment, double proportion)
{
if (nestedPanesFrom.Count == 0)
return;
int count = nestedPanesFrom.Count;
DockPane[] panes = new DockPane[count];
DockPane[] prevPanes = new DockPane[count];
DockAlignment[] alignments = new DockAlignment[count];
double[] proportions = new double[count];
for (int i = 0; i < count; i++)
{
panes[i] = nestedPanesFrom[i];
prevPanes[i] = nestedPanesFrom[i].NestedDockingStatus.PreviousPane;
alignments[i] = nestedPanesFrom[i].NestedDockingStatus.Alignment;
proportions[i] = nestedPanesFrom[i].NestedDockingStatus.Proportion;
}
DockPane pane = panes[0].DockTo(nestedPanesTo.Container, prevPane, alignment, proportion);
panes[0].DockState = nestedPanesTo.DockState;
for (int i = 1; i < count; i++)
{
for (int j = i; j < count; j++)
{
if (prevPanes[j] == panes[i - 1])
prevPanes[j] = pane;
}
pane = panes[i].DockTo(nestedPanesTo.Container, prevPanes[i], alignments[i], proportions[i]);
panes[i].DockState = nestedPanesTo.DockState;
}
}
#endregion
}
}
| |
#region MIT.
//
// Gorgon.
// Copyright (C) 2013 Michael Winsor
//
// 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
// 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.
//
// Created: Saturday, January 19, 2013 7:32:49 PM
//
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Windows.Forms;
using Gorgon.Core;
using Gorgon.Graphics;
using Gorgon.Graphics.Core;
using Gorgon.Graphics.Fonts;
using Gorgon.Graphics.Imaging.Codecs;
using Gorgon.IO;
using Gorgon.IO.Extensions;
using Gorgon.Math;
using Gorgon.Renderers;
using Gorgon.Timing;
using Gorgon.UI;
using DX = SharpDX;
using FontStyle = Gorgon.Graphics.Fonts.FontStyle;
namespace Gorgon.Examples
{
/// <summary>
/// Main application form.
/// </summary>
/// <remarks>
/// This example is a port of the Gorgon 1.x folder file system example into Gorgon 3.x.
///
/// In this example we mount a folder as a virtual file system and pull in an image, some Gorgon 2.0 sprites, the
/// backing sprite image and some text for display.
/// </remarks>
public partial class Form
: System.Windows.Forms.Form
{
#region Variables.
// The file system.
private GorgonFileSystem _fileSystem;
// The graphics interface.
private GorgonGraphics _graphics;
// The swap chain that represents our screen.
private GorgonSwapChain _screen;
// The 2D renderer interface.
private Gorgon2D _renderer;
// The effect for blurring our sprite.
private Gorgon2DGaussBlurEffect _blurEffect;
// The render target for blurring the image.
private readonly GorgonRenderTarget2DView[] _blurredTarget = new GorgonRenderTarget2DView[2];
// The texture to display from the render target.
private readonly GorgonTexture2DView[] _blurredImage = new GorgonTexture2DView[2];
// The blur amount.
private float _blurAmount = 3.0f;
// Font for text display.
private GorgonFont _textFont;
// Font for help screen.
private GorgonFont _helpFont;
// Sprites.
private IList<GorgonSprite> _sprites;
// Help text.
private GorgonTextSprite _helpText;
// Poetry text.
private GorgonTextSprite _poetry;
// Text position.
private Vector2 _textPosition = Vector2.Zero;
// Blur delta.
private float _blurDelta = -16.0f;
// Flag to show help.
private bool _showHelp = true;
// Show rendering statistics.
private bool _showStats;
#endregion
#region Methods.
/// <summary>
/// Function to reset the blur targets to the original image.
/// </summary>
private void ResetBlur()
{
_sprites[2].Scale = new Vector2(1.0f, 1.0f);
// Adjust the texture size to avoid bleed when blurring.
// Bleed means that other portions of the texture get pulled in to the texture because of bi-linear filtering (and the blur operates in a similar manner, and therefore unwanted
// pixels get pulled in as well).
//
// See http://tape-worm.net/?page_id=277 for more info.
_sprites[2].Position = new Vector2(((_blurredImage[0].Width / 2.0f) - (_sprites[2].Size.Width / 2.0f)).FastFloor(),
((_blurredImage[0].Height / 2.0f) - (_sprites[2].Size.Height / 2.0f)).FastFloor());
for (int i = 0; i < _blurredTarget.Length; ++i)
{
_blurredTarget[i].Clear(GorgonColor.BlackTransparent);
_graphics.SetRenderTarget(_blurredTarget[i]);
_renderer.Begin();
_renderer.DrawSprite(_sprites[2]);
_renderer.End();
}
}
/// <summary>
/// Function to handle idle time processing.
/// </summary>
/// <returns><b>true</b> to continue processing, <b>false</b> to stop.</returns>
private bool Idle()
{
int width = ClientSize.Width;
int height = ClientSize.Height;
_screen.RenderTargetView.Clear(Color.FromArgb(250, 245, 220));
// Reset the text position.
if (_poetry.Position.Y < -_poetry.Size.Height)
{
_textPosition = new Vector2(0, height + _textFont.LineHeight);
}
// Scroll up.
_textPosition.Y -= (25.0f * GorgonTiming.Delta);
// Alter blur value.
_blurAmount += _blurDelta * GorgonTiming.Delta;
if (_blurAmount < 0.0f)
{
_blurAmount = 0.0f;
_blurDelta = -_blurDelta;
}
if (_blurAmount > 64)
{
_blurAmount = 64;
_blurDelta = -_blurDelta;
}
int index = 0;
ResetBlur();
if (_blurAmount > 0)
{
// Blur for the count we specify.
int blurCount = (int)_blurAmount;
for (int i = 0; i < blurCount; ++i)
{
int imageIndex = index = i % 2;
int targetIndex = index == 0 ? 1 : 0;
_blurEffect.Render(_blurredImage[imageIndex], _blurredTarget[targetIndex]);
}
}
// Switch back to our screen for rendering.
_graphics.SetRenderTarget(_screen.RenderTargetView);
// Draw the base.
_renderer.Begin();
// Draw text.
_poetry.Position = _textPosition;
_renderer.DrawTextSprite(_poetry);
_sprites[0].Position = new Vector2(width / 4, height / 4);
// Draw motherships.
_sprites[1].Position = new Vector2(width - (width / 4), height / 4);
_renderer.DrawSprite(_sprites[0]);
_renderer.DrawSprite(_sprites[1]);
// Draw our blurred image (we could have used a sprite here as well, but this works just as well).
_renderer.DrawFilledRectangle(new DX.RectangleF((width / 2) - (_blurredImage[0].Width / 2.0f),
(height / 2) - (_blurredImage[0].Height / 2.0f),
_blurredImage[0].Width,
_blurredImage[0].Height),
GorgonColor.White,
_blurredImage[index],
new DX.RectangleF(0, 0, 1, 1));
// Draw help text.
if (_showHelp)
{
_renderer.DrawTextSprite(_helpText);
}
// Show our rendering statistics.
if (_showStats)
{
var rectPosition = new DX.RectangleF(0, 0, width, (_helpFont.FontHeight * 2.0f) + 2.0f);
_renderer.DrawFilledRectangle(rectPosition, Color.FromArgb(192, Color.Black));
_renderer.DrawLine(rectPosition.X, rectPosition.Bottom, rectPosition.Width, rectPosition.Bottom, Color.White);
_renderer.DrawString($"FPS: {GorgonTiming.FPS:0.0}\nFrame Delta: {(GorgonTiming.Delta * 1000):0.0##} msec.",
Vector2.Zero,
_helpFont,
GorgonColor.White);
}
_renderer.End();
GorgonExample.ShowStatistics = _showStats;
GorgonExample.DrawStatsAndLogo(_renderer);
_screen.Present(1);
return true;
}
/// <summary>
/// Function to load a sprite from the file system.
/// </summary>
/// <param name="path">Path to the file to load.</param>
/// <returns>A byte array containing the data for a file from the file system.</returns>
private byte[] LoadFile(string path)
{
IGorgonVirtualFile file = _fileSystem.GetFile(path);
if (file is null)
{
throw new FileNotFoundException($"The file '{path}' was not found in the file system.");
}
using Stream stream = file.OpenStream();
byte[] result = new byte[stream.Length];
stream.Read(result, 0, result.Length);
return result;
}
/// <summary>
/// Function called to initialize the application.
/// </summary>
private void Initialize()
{
GorgonExample.ResourceBaseDirectory = new DirectoryInfo(ExampleConfig.Default.ResourceLocation);
// Resize and center the screen.
var screen = Screen.FromHandle(Handle);
ClientSize = new Size(ExampleConfig.Default.Resolution.Width, ExampleConfig.Default.Resolution.Height);
Location = new Point(screen.Bounds.Left + (screen.WorkingArea.Width / 2) - (ClientSize.Width / 2),
screen.Bounds.Top + (screen.WorkingArea.Height / 2) - (ClientSize.Height / 2));
// Initialize our graphics.
IReadOnlyList<IGorgonVideoAdapterInfo> videoAdapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);
if (videoAdapters.Count == 0)
{
throw new GorgonException(GorgonResult.CannotCreate,
"Gorgon requires at least a Direct3D 11.2 capable video device.\nThere is no suitable device installed on the system.");
}
// Find the best video device.
_graphics = new GorgonGraphics(videoAdapters.OrderByDescending(item => item.FeatureSet).First());
// Build our "screen".
_screen = new GorgonSwapChain(_graphics,
this,
new GorgonSwapChainInfo(ClientSize.Width, ClientSize.Height, BufferFormat.R8G8B8A8_UNorm));
if (!ExampleConfig.Default.IsWindowed)
{
// Go full screen by using borderless windowed mode.
_screen.EnterFullScreen();
}
// Build up our 2D renderer.
_renderer = new Gorgon2D(_graphics);
// Load in the logo texture from our resources.
GorgonExample.LoadResources(_graphics);
// Create fonts.
_textFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("GiGi", 24.0f, FontHeightMode.Points)
{
Name = "GiGi_24pt",
AntiAliasingMode = FontAntiAliasMode.AntiAlias,
TextureWidth = 512,
TextureHeight = 256
});
// Use the form font for this one.
_helpFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo(Font.FontFamily.Name,
Font.Size,
Font.Unit == GraphicsUnit.Pixel ? FontHeightMode.Pixels : FontHeightMode.Points)
{
Name = "Form Font",
AntiAliasingMode = FontAntiAliasMode.AntiAlias,
FontStyle = FontStyle.Bold
});
// Create our file system and mount the resources.
_fileSystem = new GorgonFileSystem(GorgonApplication.Log);
_fileSystem.Mount(GorgonExample.GetResourcePath(@"FileSystems\FolderSystem").FullName);
// In the previous versions of Gorgon, we used to load the image first, and then the sprites.
// But in this version, we have an extension that will load the sprite textures for us.
_sprites = new GorgonSprite[3];
// The sprites are in the v2 format.
IEnumerable<IGorgonSpriteCodec> v2Codec = new[] { new GorgonV2SpriteCodec(_renderer) };
IEnumerable<IGorgonImageCodec> pngCodec = new[] { new GorgonCodecPng() };
_sprites[0] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/base.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec);
_sprites[1] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/Mother.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec);
_sprites[2] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/Mother2c.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec);
// This is how you would get the sprites in v2 of Gorgon:
/*_spriteImage = _graphics.Textures.FromMemory<GorgonTexture2D>("0_HardVacuum", LoadFile("/Images/0_HardVacuum.png"), new GorgonCodecPNG());
// Get the sprites.
// The sprites in the file system are from version 1.0 of Gorgon.
// This version is backwards compatible and can load any version
// of the sprites produced by older versions of Gorgon.
_sprites = new GorgonSprite[3];
_sprites[0] = _renderer.Renderables.FromMemory<GorgonSprite>("Base", LoadFile("/Sprites/base.gorSprite"));
_sprites[1] = _renderer.Renderables.FromMemory<GorgonSprite>("Mother", LoadFile("/Sprites/Mother.gorSprite"));
_sprites[2] = _renderer.Renderables.FromMemory<GorgonSprite>("Mother2c", LoadFile("/Sprites/Mother2c.gorSprite"));
*/
// Get poetry.
_textPosition = new Vector2(0, ClientSize.Height + _textFont.LineHeight);
_poetry = new GorgonTextSprite(_textFont, Encoding.UTF8.GetString(LoadFile("/SomeText.txt")))
{
Position = _textPosition,
Color = Color.Black
};
// Set up help text.
_helpText = new GorgonTextSprite(_helpFont, "F1 - Show/hide this help text.\nS - Show frame statistics.\nESC - Exit.")
{
Color = Color.Blue,
Position = new Vector2(3, 3)
};
// Unlike the old example, we'll blend to render targets, ping-ponging back and forth, for a much better quality image and smoother transition.
_blurEffect = new Gorgon2DGaussBlurEffect(_renderer, 3)
{
BlurRenderTargetsSize = new DX.Size2((int)_sprites[2].Size.Width * 2, (int)_sprites[2].Size.Height * 2),
PreserveAlpha = false
};
_blurEffect.Precache();
_blurredTarget[0] = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo(_blurEffect.BlurRenderTargetsSize.Width,
_blurEffect.BlurRenderTargetsSize.Height,
BufferFormat.R8G8B8A8_UNorm)
{
Name = "Blurred RTV",
Binding = TextureBinding.ShaderResource,
Usage = ResourceUsage.Default
});
_blurredTarget[1] = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, _blurredTarget[0]);
_blurredImage[0] = _blurredTarget[0].GetShaderResourceView();
_blurredImage[1] = _blurredTarget[1].GetShaderResourceView();
GorgonApplication.IdleMethod = Idle;
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.KeyDown" /> event.
/// </summary>
/// <param name="e">A <see cref="KeyEventArgs" /> that contains the event data.</param>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.KeyCode == Keys.Escape)
{
GorgonApplication.Quit();
}
if (e.KeyCode == Keys.F1)
{
_showHelp = !_showHelp;
}
if (e.KeyCode == Keys.S)
{
_showStats = !_showStats;
}
}
/// <summary>Raises the <see cref="E:System.Windows.Forms.Form.FormClosing" /> event.</summary>
/// <param name="e">A <see cref="FormClosingEventArgs" /> that contains the event data. </param>
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
_blurredImage[1]?.Dispose();
_blurredTarget[1]?.Dispose();
_blurredImage[0]?.Dispose();
_blurredTarget[0]?.Dispose();
_blurEffect?.Dispose();
_helpFont?.Dispose();
_textFont?.Dispose();
_renderer?.Dispose();
_screen?.Dispose();
_graphics?.Dispose();
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Form.Load" /> event.
/// </summary>
/// <param name="e">An <see cref="EventArgs" /> that contains the event data.</param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
try
{
Cursor = Cursors.WaitCursor;
Visible = true;
Application.DoEvents();
// Initialize.
Initialize();
}
catch (Exception ex)
{
ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), GorgonApplication.Log);
GorgonApplication.Quit();
}
finally
{
Cursor = Cursors.Default;
}
}
#endregion
#region Constructor/Destructor.
/// <summary>
/// Constructor.
/// </summary>
public Form() => InitializeComponent();
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using SimpleContainer.Configuration;
using SimpleContainer.Infection;
using SimpleContainer.Interface;
using SimpleContainer.Tests.Helpers;
namespace SimpleContainer.Tests.Contracts
{
public abstract class ContractsBasicTest : SimpleContainerTestBase
{
public class RequireTest : ContractsBasicTest
{
public class ContainerClass1
{
public readonly OuterClass outerClass;
public ContainerClass1([TestContract("c1")] OuterClass outerClass)
{
this.outerClass = outerClass;
}
}
public class ContainerClass2
{
public readonly OuterClass outerClass;
public ContainerClass2([TestContract("c2")] OuterClass outerClass)
{
this.outerClass = outerClass;
}
}
public class OuterClass
{
public readonly InnerClass innerClass;
public OuterClass(InnerClass innerClass)
{
this.innerClass = innerClass;
}
}
public class InnerClass
{
public readonly IInterface @interface;
public InnerClass(IInterface @interface)
{
this.@interface = @interface;
}
}
public interface IInterface
{
}
public class Impl1 : IInterface
{
}
public class Impl2 : IInterface
{
}
[Test]
public void Test()
{
var container = Container(c =>
{
c.Contract("c1").Bind<IInterface, Impl1>();
c.Contract("c2").Bind<IInterface, Impl2>();
});
Assert.That(container.Get<ContainerClass1>().outerClass.innerClass.@interface, Is.InstanceOf<Impl1>());
Assert.That(container.Get<ContainerClass2>().outerClass.innerClass.@interface, Is.InstanceOf<Impl2>());
}
}
public class DoNotDuplicateServicesNotDependentOn : ContractsBasicTest
{
public class ServiceClient1
{
public readonly Service service;
public readonly SingletonService singletonService;
public ServiceClient1([TestContract("c1")] Service service, SingletonService singletonService)
{
this.service = service;
this.singletonService = singletonService;
}
}
public class ServiceClient2
{
public readonly Service service;
public SingletonService singletonService;
public ServiceClient2([TestContract("c2")] Service service, SingletonService singletonService)
{
this.service = service;
this.singletonService = singletonService;
}
}
public class SingletonService
{
}
public class Service
{
public readonly IInterface @interface;
public readonly SingletonService singletonService;
public Service(IInterface @interface, SingletonService singletonService)
{
this.@interface = @interface;
this.singletonService = singletonService;
}
}
public interface IInterface
{
}
public class Impl1 : IInterface
{
}
public class Impl2 : IInterface
{
}
[Test]
public void Test()
{
var container = Container(c =>
{
c.Contract("c1").Bind<IInterface, Impl1>();
c.Contract("c2").Bind<IInterface, Impl2>();
});
var singletonServiceInstance = container.Get<ServiceClient1>().service.singletonService;
Assert.That(container.Get<ServiceClient2>().service.singletonService, Is.SameAs(singletonServiceInstance));
Assert.That(container.Get<ServiceClient1>().singletonService, Is.SameAs(singletonServiceInstance));
Assert.That(container.Get<ServiceClient2>().singletonService, Is.SameAs(singletonServiceInstance));
}
}
public class SelfConfigurationDependency : ContractsBasicTest
{
public class Wrap
{
public readonly X first;
public readonly X second;
public Wrap([TestContract("first")] X first, [TestContract("second")] X second)
{
this.first = first;
this.second = second;
}
}
public class X
{
public readonly IIntf intf;
public X(IIntf intf)
{
this.intf = intf;
}
}
public interface IIntf
{
}
public class Y : IIntf
{
}
public class Z : IIntf
{
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("first").BindDependency<X, IIntf, Y>();
builder.Contract("second").BindDependency<X, IIntf, Z>();
});
var wrap = container.Get<Wrap>();
Assert.That(wrap.first.intf, Is.InstanceOf<Y>());
Assert.That(wrap.second.intf, Is.InstanceOf<Z>());
}
}
public class CanBeSpecifiedViaInfection : ContractsBasicTest
{
public class Wrap
{
public readonly IService serviceA;
public readonly IService serviceB;
public Wrap([TestContract("A")] IService serviceA, [TestContract("B")] IService serviceB)
{
this.serviceA = serviceA;
this.serviceB = serviceB;
}
}
public interface IService
{
}
public class ServiceA : IService
{
}
public class ServiceB : IService
{
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("A").Bind<IService, ServiceA>();
builder.Contract("B").Bind<IService, ServiceB>();
});
var wrap = container.Get<Wrap>();
Assert.That(wrap.serviceA, Is.InstanceOf<ServiceA>());
Assert.That(wrap.serviceB, Is.InstanceOf<ServiceB>());
}
}
public class IgnoreNotDeclared : ContractsBasicTest
{
public class A
{
public readonly B b;
public A(B b)
{
this.b = b;
}
}
[TestContract("not-declared")]
public class B
{
}
[Test]
public void Test()
{
var container = Container();
Assert.DoesNotThrow(() => container.Get<A>());
}
}
public class ClassIsAppliedAfterDependency : ContractsBasicTest
{
public class A
{
public readonly B b;
public A([TestContract("c1")] B b)
{
this.b = b;
}
}
[TestContract("c2")]
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("c1").BindDependency<B>("parameter", 42);
builder.Contract("c2").BindDependency<B>("parameter", 43);
});
Assert.That(container.Get<A>().b.parameter, Is.EqualTo(43));
}
}
public class CanAttachContractOnClass : ContractsBasicTest
{
public class Wrap
{
public readonly Service service;
public Wrap(Service service)
{
this.service = service;
}
}
public class TestContractAttribute : RequireContractAttribute
{
public TestContractAttribute()
: base("test-contract")
{
}
}
[TestContract]
public class Service
{
public readonly IInterface @interface;
public Service(IInterface @interface)
{
this.@interface = @interface;
}
}
public interface IInterface
{
}
public class Impl1 : IInterface
{
}
public class Impl2 : IInterface
{
}
[Test]
public void Test()
{
var container = Container(b => b.Contract<TestContractAttribute>().Bind<IInterface, Impl2>());
var wrap = container.Get<Wrap>();
Assert.That(wrap.service.@interface, Is.InstanceOf<Impl2>());
Assert.That(container.Resolve<Service>().GetConstructionLog(),
Is.EqualTo("Service[test-contract]\r\n\tIInterface[test-contract]\r\n\t\tImpl2"));
}
}
public class ContractAttachedOnClassIsUsedOnGet : ContractsBasicTest
{
[TestContract("a")]
public class A
{
public readonly ISomeInterface someInterface;
public A(ISomeInterface someInterface)
{
this.someInterface = someInterface;
}
}
public interface ISomeInterface
{
}
public class Impl1 : ISomeInterface
{
}
public class Impl2 : ISomeInterface
{
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("a").Bind<ISomeInterface, Impl2>());
Assert.That(container.Get<A>().someInterface, Is.InstanceOf<Impl2>());
}
}
public class SimpleNestedContracts : ContractsBasicTest
{
public class Wrap
{
public readonly IInterface1 s1;
public readonly IInterface1 s2;
public Wrap([TestContract("a1")] IInterface1 s1, [TestContract("a2")] IInterface1 s2)
{
this.s1 = s1;
this.s2 = s2;
}
}
public interface IInterface1
{
}
public class Impl1 : IInterface1
{
public readonly IInterface2 s1;
public readonly IInterface2 s2;
public Impl1([TestContract("b1")] IInterface2 s1, [TestContract("b2")] IInterface2 s2)
{
this.s1 = s1;
this.s2 = s2;
}
}
public class Impl2 : IInterface1
{
}
public interface IInterface2
{
}
public class Impl3 : IInterface2
{
}
public class Impl4 : IInterface2
{
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("a1").Bind<IInterface1, Impl1>();
builder.Contract("a2").Bind<IInterface1, Impl2>();
builder.Contract("b1").Bind<IInterface2, Impl3>();
builder.Contract("b2").Bind<IInterface2, Impl4>();
});
var instance = container.Get<Wrap>();
Assert.That(instance.s1, Is.InstanceOf<Impl1>());
Assert.That(instance.s2, Is.InstanceOf<Impl2>());
var impl = (Impl1) instance.s1;
Assert.That(impl.s1, Is.InstanceOf<Impl3>());
Assert.That(impl.s2, Is.InstanceOf<Impl4>());
}
}
public class ContractOnClassAndParameter : ContractsBasicTest
{
public class Wrap
{
public readonly A a;
public Wrap([TestContract("a")] A a)
{
this.a = a;
}
}
[TestContract("b")]
public class A
{
public readonly B b;
public A(B b)
{
this.b = b;
}
}
public class B
{
public readonly int dependency;
public readonly C c;
public B(int dependency, C c)
{
this.dependency = dependency;
this.c = c;
}
}
public class C
{
public readonly int dependency;
public C(int dependency)
{
this.dependency = dependency;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("a").BindDependency<B>("dependency", 1);
builder.Contract("b").BindDependency<C>("dependency", 2);
});
var wrap = container.Get<Wrap>();
Assert.That(wrap.a.b.dependency, Is.EqualTo(1));
Assert.That(wrap.a.b.c.dependency, Is.EqualTo(2));
}
}
public class ContractsFlowViaDependenciesWithRequireContract : ContractsBasicTest
{
public class H
{
public readonly A a1;
public readonly A a2;
public H([TestContract("x")] A a1, A a2)
{
this.a1 = a1;
this.a2 = a2;
}
}
public class A
{
public readonly B b;
public A([TestContract("y")] B b)
{
this.b = b;
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("y");
builder.BindDependency<B>("parameter", 1);
builder.Contract("x").BindDependency<B>("parameter", 2);
});
var h = container.Get<H>();
Assert.That(h.a1.b.parameter, Is.EqualTo(2));
Assert.That(h.a2.b.parameter, Is.EqualTo(1));
}
}
public class ContractsFlowViaInterfaces : ContractsBasicTest
{
public class A
{
public readonly Wrap s1;
public readonly Wrap s2;
public A([TestContract("a")] Wrap s1, Wrap s2)
{
this.s1 = s1;
this.s2 = s2;
}
}
public class Wrap
{
public readonly IInterface wrapped;
public Wrap(IInterface wrapped)
{
this.wrapped = wrapped;
}
}
public interface IInterface
{
int GetParameter();
}
public class Impl1 : IInterface
{
public readonly int parameter;
public Impl1(int parameter)
{
this.parameter = parameter;
}
public int GetParameter()
{
return parameter;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.BindDependency<Impl1>("parameter", 1);
builder.Contract("a").BindDependency<Impl1>("parameter", 2);
});
var a = container.Get<A>();
Assert.That(a.s1.wrapped.GetParameter(), Is.EqualTo(2));
Assert.That(a.s2.wrapped.GetParameter(), Is.EqualTo(1));
}
}
public class ContractUsedInEnumerableDependency : ContractsBasicTest
{
public class Wrap
{
public readonly A a;
public Wrap([TestContract("b")] A a)
{
this.a = a;
}
}
public class A
{
public readonly IEnumerable<B> enumerable;
public A(IEnumerable<B> enumerable)
{
this.enumerable = enumerable;
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("b").BindDependency<B>("parameter", 128));
Assert.That(container.Get<Wrap>().a.enumerable.Single().parameter, Is.EqualTo(128));
}
}
public class DumpUsedContractsBeforeFinalConstruction : ContractsBasicTest
{
[TestContract("a")]
public class A
{
public readonly int parameter;
public readonly B b;
public A(int parameter, B b)
{
this.parameter = parameter;
this.b = b;
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("a").BindDependency<A>("parameter", 78));
var error = Assert.Throws<SimpleContainerException>(() => container.Get<A>());
Assert.That(error.Message,
Is.StringContaining("!A[a]\r\n\tparameter -> 78\r\n\t!B\r\n\t\t!parameter <---------------"));
}
}
public class ServiceWithContractImplementsInterface : ContractsBasicTest
{
public interface IA
{
}
[TestContract("x")]
public class A : IA
{
public readonly int parameter;
public A(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("x").BindDependency<A>("parameter", 42));
var a = (A) container.Get<IA>();
Assert.That(a.parameter, Is.EqualTo(42));
}
}
public class CanInjectServiceName : ContractsBasicTest
{
public class A
{
public readonly B b;
public A([TestContract("my-test-contract")] B b)
{
this.b = b;
}
}
public class B
{
public readonly int parameter;
public readonly ServiceName myName1;
public readonly ServiceName myName2;
public B(ServiceName myName1, int parameter, ServiceName myName2)
{
this.myName1 = myName1;
this.parameter = parameter;
this.myName2 = myName2;
}
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("my-test-contract").BindDependencies<B>(new {parameter = 78}));
var instance = container.Get<A>().b;
Assert.That(instance.myName1.ToString(), Is.EqualTo("B[my-test-contract]"));
Assert.That(instance.myName2.ToString(), Is.EqualTo("B[my-test-contract]"));
}
}
public class CanOverrideServiceInSpecificContract : ContractsBasicTest
{
public class A
{
public readonly B b1;
public readonly B b2;
public A(B b1, [TestContract("c")] B b2)
{
this.b1 = b1;
this.b2 = b2;
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder b)
{
b.BindDependency<B>("parameter", 1);
b.Contract("c").BindDependency<B>("parameter", 2);
});
var instance = container.Get<A>();
Assert.That(instance.b1.parameter, Is.EqualTo(1));
Assert.That(instance.b2.parameter, Is.EqualTo(2));
using (var child = container.Clone(b => b.BindDependency<B>("parameter", 3)))
{
var childInstance = child.Get<A>();
Assert.That(childInstance.b1.parameter, Is.EqualTo(3));
Assert.That(childInstance.b2.parameter, Is.EqualTo(2));
}
}
}
public class ContractRedefinitionIsProhibited : ContractsBasicTest
{
public class A
{
public readonly B b;
public A([TestContract("x")] B b)
{
this.b = b;
}
}
[TestContract("x")]
public class B
{
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("x"));
var error = Assert.Throws<SimpleContainerException>(() => container.Get<A>());
Assert.That(error.Message,
Is.EqualTo("contract [x] already declared, stack\r\n\tA\r\n\tB[x->x]\r\n\r\n!A\r\n\t!B <---------------"));
}
}
public class SameInterfaceInContractNotACyclicDependency : ContractsBasicTest
{
public interface IB
{
}
public class ServiceB : IB
{
public C C;
public ServiceB([TestContract("test")] C c)
{
C = c;
}
}
public class InternalB : IB
{
}
public class C
{
public IB B;
public C(IB b)
{
B = b;
}
}
[Test]
public void Test()
{
var container = Container(x =>
{
x.Bind<IB, ServiceB>();
x.Contract("test").Bind<IB, InternalB>();
});
var serviceB = (ServiceB) container.Get<IB>();
Assert.That(serviceB.C.B, Is.SameAs(container.Get<InternalB>()));
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.