context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) 2007-2014 Joe White
//
// 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.
// Autogenerated file - do not edit
using System;
using System.Collections.Generic;
using System.Text;
using DGrok.DelphiNodes;
namespace DGrok.Framework
{
public partial class Visitor
{
public virtual void VisitArrayTypeNode(ArrayTypeNode node)
{
Visit(node.ArrayKeywordNode);
Visit(node.OpenBracketNode);
Visit(node.IndexListNode);
Visit(node.CloseBracketNode);
Visit(node.OfKeywordNode);
Visit(node.TypeNode);
}
public virtual void VisitAssemblerStatementNode(AssemblerStatementNode node)
{
Visit(node.AsmKeywordNode);
Visit(node.EndKeywordNode);
}
public virtual void VisitAttributeNode(AttributeNode node)
{
Visit(node.OpenBracketNode);
Visit(node.ScopeNode);
Visit(node.ColonNode);
Visit(node.ValueNode);
Visit(node.CloseBracketNode);
}
public virtual void VisitBinaryOperationNode(BinaryOperationNode node)
{
Visit(node.LeftNode);
Visit(node.OperatorNode);
Visit(node.RightNode);
}
public virtual void VisitBlockNode(BlockNode node)
{
Visit(node.BeginKeywordNode);
Visit(node.StatementListNode);
Visit(node.EndKeywordNode);
}
public virtual void VisitCaseSelectorNode(CaseSelectorNode node)
{
Visit(node.ValueListNode);
Visit(node.ColonNode);
Visit(node.StatementNode);
Visit(node.SemicolonNode);
}
public virtual void VisitCaseStatementNode(CaseStatementNode node)
{
Visit(node.CaseKeywordNode);
Visit(node.ExpressionNode);
Visit(node.OfKeywordNode);
Visit(node.SelectorListNode);
Visit(node.ElseKeywordNode);
Visit(node.ElseStatementListNode);
Visit(node.EndKeywordNode);
}
public virtual void VisitClassOfNode(ClassOfNode node)
{
Visit(node.ClassKeywordNode);
Visit(node.OfKeywordNode);
Visit(node.TypeNode);
}
public virtual void VisitClassTypeNode(ClassTypeNode node)
{
Visit(node.ClassKeywordNode);
Visit(node.DispositionNode);
Visit(node.OpenParenthesisNode);
Visit(node.InheritanceListNode);
Visit(node.CloseParenthesisNode);
Visit(node.ContentListNode);
Visit(node.EndKeywordNode);
}
public virtual void VisitConstantDeclNode(ConstantDeclNode node)
{
Visit(node.NameNode);
Visit(node.ColonNode);
Visit(node.TypeNode);
Visit(node.EqualSignNode);
Visit(node.ValueNode);
Visit(node.PortabilityDirectiveListNode);
Visit(node.SemicolonNode);
}
public virtual void VisitConstantListNode(ConstantListNode node)
{
Visit(node.OpenParenthesisNode);
Visit(node.ItemListNode);
Visit(node.CloseParenthesisNode);
}
public virtual void VisitConstSectionNode(ConstSectionNode node)
{
Visit(node.ConstKeywordNode);
Visit(node.ConstListNode);
}
public virtual void VisitDirectiveNode(DirectiveNode node)
{
Visit(node.SemicolonNode);
Visit(node.KeywordNode);
Visit(node.ValueNode);
Visit(node.DataNode);
}
public virtual void VisitEnumeratedTypeElementNode(EnumeratedTypeElementNode node)
{
Visit(node.NameNode);
Visit(node.EqualSignNode);
Visit(node.ValueNode);
}
public virtual void VisitEnumeratedTypeNode(EnumeratedTypeNode node)
{
Visit(node.OpenParenthesisNode);
Visit(node.ItemListNode);
Visit(node.CloseParenthesisNode);
}
public virtual void VisitExceptionItemNode(ExceptionItemNode node)
{
Visit(node.OnSemikeywordNode);
Visit(node.NameNode);
Visit(node.ColonNode);
Visit(node.TypeNode);
Visit(node.DoKeywordNode);
Visit(node.StatementNode);
Visit(node.SemicolonNode);
}
public virtual void VisitExportsItemNode(ExportsItemNode node)
{
Visit(node.NameNode);
Visit(node.SpecifierListNode);
}
public virtual void VisitExportsSpecifierNode(ExportsSpecifierNode node)
{
Visit(node.KeywordNode);
Visit(node.ValueNode);
}
public virtual void VisitExportsStatementNode(ExportsStatementNode node)
{
Visit(node.ExportsKeywordNode);
Visit(node.ItemListNode);
Visit(node.SemicolonNode);
}
public virtual void VisitFancyBlockNode(FancyBlockNode node)
{
Visit(node.DeclListNode);
Visit(node.BlockNode);
}
public virtual void VisitFieldDeclNode(FieldDeclNode node)
{
Visit(node.NameListNode);
Visit(node.ColonNode);
Visit(node.TypeNode);
Visit(node.PortabilityDirectiveListNode);
Visit(node.SemicolonNode);
}
public virtual void VisitFieldSectionNode(FieldSectionNode node)
{
Visit(node.ClassKeywordNode);
Visit(node.VarKeywordNode);
Visit(node.FieldListNode);
}
public virtual void VisitFileTypeNode(FileTypeNode node)
{
Visit(node.FileKeywordNode);
Visit(node.OfKeywordNode);
Visit(node.TypeNode);
}
public virtual void VisitForInStatementNode(ForInStatementNode node)
{
Visit(node.ForKeywordNode);
Visit(node.LoopVariableNode);
Visit(node.InKeywordNode);
Visit(node.ExpressionNode);
Visit(node.DoKeywordNode);
Visit(node.StatementNode);
}
public virtual void VisitForStatementNode(ForStatementNode node)
{
Visit(node.ForKeywordNode);
Visit(node.LoopVariableNode);
Visit(node.ColonEqualsNode);
Visit(node.StartingValueNode);
Visit(node.DirectionNode);
Visit(node.EndingValueNode);
Visit(node.DoKeywordNode);
Visit(node.StatementNode);
}
public virtual void VisitGotoStatementNode(GotoStatementNode node)
{
Visit(node.GotoKeywordNode);
Visit(node.LabelIdNode);
}
public virtual void VisitIfStatementNode(IfStatementNode node)
{
Visit(node.IfKeywordNode);
Visit(node.ConditionNode);
Visit(node.ThenKeywordNode);
Visit(node.ThenStatementNode);
Visit(node.ElseKeywordNode);
Visit(node.ElseStatementNode);
}
public virtual void VisitInitSectionNode(InitSectionNode node)
{
Visit(node.InitializationKeywordNode);
Visit(node.InitializationStatementListNode);
Visit(node.FinalizationKeywordNode);
Visit(node.FinalizationStatementListNode);
Visit(node.EndKeywordNode);
}
public virtual void VisitInterfaceTypeNode(InterfaceTypeNode node)
{
Visit(node.InterfaceKeywordNode);
Visit(node.OpenParenthesisNode);
Visit(node.BaseInterfaceNode);
Visit(node.CloseParenthesisNode);
Visit(node.OpenBracketNode);
Visit(node.GuidNode);
Visit(node.CloseBracketNode);
Visit(node.MethodAndPropertyListNode);
Visit(node.EndKeywordNode);
}
public virtual void VisitLabelDeclSectionNode(LabelDeclSectionNode node)
{
Visit(node.LabelKeywordNode);
Visit(node.LabelListNode);
Visit(node.SemicolonNode);
}
public virtual void VisitLabeledStatementNode(LabeledStatementNode node)
{
Visit(node.LabelIdNode);
Visit(node.ColonNode);
Visit(node.StatementNode);
}
public virtual void VisitMethodHeadingNode(MethodHeadingNode node)
{
Visit(node.ClassKeywordNode);
Visit(node.MethodTypeNode);
Visit(node.NameNode);
Visit(node.OpenParenthesisNode);
Visit(node.ParameterListNode);
Visit(node.CloseParenthesisNode);
Visit(node.ColonNode);
Visit(node.ReturnTypeNode);
Visit(node.DirectiveListNode);
Visit(node.SemicolonNode);
}
public virtual void VisitMethodImplementationNode(MethodImplementationNode node)
{
Visit(node.MethodHeadingNode);
Visit(node.FancyBlockNode);
Visit(node.SemicolonNode);
}
public virtual void VisitMethodResolutionNode(MethodResolutionNode node)
{
Visit(node.MethodTypeNode);
Visit(node.InterfaceMethodNode);
Visit(node.EqualSignNode);
Visit(node.ImplementationMethodNode);
Visit(node.SemicolonNode);
}
public virtual void VisitNumberFormatNode(NumberFormatNode node)
{
Visit(node.ValueNode);
Visit(node.SizeColonNode);
Visit(node.SizeNode);
Visit(node.PrecisionColonNode);
Visit(node.PrecisionNode);
}
public virtual void VisitOpenArrayNode(OpenArrayNode node)
{
Visit(node.ArrayKeywordNode);
Visit(node.OfKeywordNode);
Visit(node.TypeNode);
}
public virtual void VisitPackageNode(PackageNode node)
{
Visit(node.PackageKeywordNode);
Visit(node.NameNode);
Visit(node.SemicolonNode);
Visit(node.RequiresClauseNode);
Visit(node.ContainsClauseNode);
Visit(node.AttributeListNode);
Visit(node.EndKeywordNode);
Visit(node.DotNode);
}
public virtual void VisitPackedTypeNode(PackedTypeNode node)
{
Visit(node.PackedKeywordNode);
Visit(node.TypeNode);
}
public virtual void VisitParameterizedNode(ParameterizedNode node)
{
Visit(node.LeftNode);
Visit(node.OpenDelimiterNode);
Visit(node.ParameterListNode);
Visit(node.CloseDelimiterNode);
}
public virtual void VisitParameterNode(ParameterNode node)
{
Visit(node.ModifierNode);
Visit(node.NameListNode);
Visit(node.ColonNode);
Visit(node.TypeNode);
Visit(node.EqualSignNode);
Visit(node.DefaultValueNode);
}
public virtual void VisitParenthesizedExpressionNode(ParenthesizedExpressionNode node)
{
Visit(node.OpenParenthesisNode);
Visit(node.ExpressionNode);
Visit(node.CloseParenthesisNode);
}
public virtual void VisitPointerDereferenceNode(PointerDereferenceNode node)
{
Visit(node.OperandNode);
Visit(node.CaretNode);
}
public virtual void VisitPointerTypeNode(PointerTypeNode node)
{
Visit(node.CaretNode);
Visit(node.TypeNode);
}
public virtual void VisitProcedureTypeNode(ProcedureTypeNode node)
{
Visit(node.MethodTypeNode);
Visit(node.OpenParenthesisNode);
Visit(node.ParameterListNode);
Visit(node.CloseParenthesisNode);
Visit(node.ColonNode);
Visit(node.ReturnTypeNode);
Visit(node.FirstDirectiveListNode);
Visit(node.OfKeywordNode);
Visit(node.ObjectKeywordNode);
Visit(node.SecondDirectiveListNode);
}
public virtual void VisitProgramNode(ProgramNode node)
{
Visit(node.ProgramKeywordNode);
Visit(node.NameNode);
Visit(node.NoiseOpenParenthesisNode);
Visit(node.NoiseContentListNode);
Visit(node.NoiseCloseParenthesisNode);
Visit(node.SemicolonNode);
Visit(node.UsesClauseNode);
Visit(node.DeclarationListNode);
Visit(node.InitSectionNode);
Visit(node.DotNode);
}
public virtual void VisitPropertyNode(PropertyNode node)
{
Visit(node.ClassKeywordNode);
Visit(node.PropertyKeywordNode);
Visit(node.NameNode);
Visit(node.OpenBracketNode);
Visit(node.ParameterListNode);
Visit(node.CloseBracketNode);
Visit(node.ColonNode);
Visit(node.TypeNode);
Visit(node.DirectiveListNode);
Visit(node.SemicolonNode);
}
public virtual void VisitRaiseStatementNode(RaiseStatementNode node)
{
Visit(node.RaiseKeywordNode);
Visit(node.ExceptionNode);
Visit(node.AtSemikeywordNode);
Visit(node.AddressNode);
}
public virtual void VisitRecordFieldConstantNode(RecordFieldConstantNode node)
{
Visit(node.NameNode);
Visit(node.ColonNode);
Visit(node.ValueNode);
}
public virtual void VisitRecordTypeNode(RecordTypeNode node)
{
Visit(node.RecordKeywordNode);
Visit(node.ContentListNode);
Visit(node.VariantSectionNode);
Visit(node.EndKeywordNode);
}
public virtual void VisitRepeatStatementNode(RepeatStatementNode node)
{
Visit(node.RepeatKeywordNode);
Visit(node.StatementListNode);
Visit(node.UntilKeywordNode);
Visit(node.ConditionNode);
}
public virtual void VisitRequiresClauseNode(RequiresClauseNode node)
{
Visit(node.RequiresSemikeywordNode);
Visit(node.PackageListNode);
Visit(node.SemicolonNode);
}
public virtual void VisitSetLiteralNode(SetLiteralNode node)
{
Visit(node.OpenBracketNode);
Visit(node.ItemListNode);
Visit(node.CloseBracketNode);
}
public virtual void VisitSetOfNode(SetOfNode node)
{
Visit(node.SetKeywordNode);
Visit(node.OfKeywordNode);
Visit(node.TypeNode);
}
public virtual void VisitStringOfLengthNode(StringOfLengthNode node)
{
Visit(node.StringKeywordNode);
Visit(node.OpenBracketNode);
Visit(node.LengthNode);
Visit(node.CloseBracketNode);
}
public virtual void VisitTryExceptNode(TryExceptNode node)
{
Visit(node.TryKeywordNode);
Visit(node.TryStatementListNode);
Visit(node.ExceptKeywordNode);
Visit(node.ExceptionItemListNode);
Visit(node.ElseKeywordNode);
Visit(node.ElseStatementListNode);
Visit(node.EndKeywordNode);
}
public virtual void VisitTryFinallyNode(TryFinallyNode node)
{
Visit(node.TryKeywordNode);
Visit(node.TryStatementListNode);
Visit(node.FinallyKeywordNode);
Visit(node.FinallyStatementListNode);
Visit(node.EndKeywordNode);
}
public virtual void VisitTypeDeclNode(TypeDeclNode node)
{
Visit(node.NameNode);
Visit(node.EqualSignNode);
Visit(node.TypeKeywordNode);
Visit(node.TypeNode);
Visit(node.PortabilityDirectiveListNode);
Visit(node.SemicolonNode);
}
public virtual void VisitTypeForwardDeclarationNode(TypeForwardDeclarationNode node)
{
Visit(node.NameNode);
Visit(node.EqualSignNode);
Visit(node.TypeNode);
Visit(node.SemicolonNode);
}
public virtual void VisitTypeHelperNode(TypeHelperNode node)
{
Visit(node.TypeKeywordNode);
Visit(node.HelperSemikeywordNode);
Visit(node.OpenParenthesisNode);
Visit(node.BaseHelperTypeNode);
Visit(node.CloseParenthesisNode);
Visit(node.ForKeywordNode);
Visit(node.TypeNode);
Visit(node.ContentListNode);
Visit(node.EndKeywordNode);
}
public virtual void VisitTypeSectionNode(TypeSectionNode node)
{
Visit(node.TypeKeywordNode);
Visit(node.TypeListNode);
}
public virtual void VisitUnaryOperationNode(UnaryOperationNode node)
{
Visit(node.OperatorNode);
Visit(node.OperandNode);
}
public virtual void VisitUnitNode(UnitNode node)
{
Visit(node.UnitKeywordNode);
Visit(node.UnitNameNode);
Visit(node.PortabilityDirectiveListNode);
Visit(node.SemicolonNode);
Visit(node.InterfaceSectionNode);
Visit(node.ImplementationSectionNode);
Visit(node.InitSectionNode);
Visit(node.DotNode);
}
public virtual void VisitUnitSectionNode(UnitSectionNode node)
{
Visit(node.HeaderKeywordNode);
Visit(node.UsesClauseNode);
Visit(node.ContentListNode);
}
public virtual void VisitUsedUnitNode(UsedUnitNode node)
{
Visit(node.NameNode);
Visit(node.InKeywordNode);
Visit(node.FileNameNode);
}
public virtual void VisitUsesClauseNode(UsesClauseNode node)
{
Visit(node.UsesKeywordNode);
Visit(node.UnitListNode);
Visit(node.SemicolonNode);
}
public virtual void VisitVarDeclNode(VarDeclNode node)
{
Visit(node.NameListNode);
Visit(node.ColonNode);
Visit(node.TypeNode);
Visit(node.FirstPortabilityDirectiveListNode);
Visit(node.AbsoluteSemikeywordNode);
Visit(node.AbsoluteAddressNode);
Visit(node.EqualSignNode);
Visit(node.ValueNode);
Visit(node.SecondPortabilityDirectiveListNode);
Visit(node.SemicolonNode);
}
public virtual void VisitVariantGroupNode(VariantGroupNode node)
{
Visit(node.ValueListNode);
Visit(node.ColonNode);
Visit(node.OpenParenthesisNode);
Visit(node.FieldDeclListNode);
Visit(node.VariantSectionNode);
Visit(node.CloseParenthesisNode);
Visit(node.SemicolonNode);
}
public virtual void VisitVariantSectionNode(VariantSectionNode node)
{
Visit(node.CaseKeywordNode);
Visit(node.NameNode);
Visit(node.ColonNode);
Visit(node.TypeNode);
Visit(node.OfKeywordNode);
Visit(node.VariantGroupListNode);
}
public virtual void VisitVarSectionNode(VarSectionNode node)
{
Visit(node.VarKeywordNode);
Visit(node.VarListNode);
}
public virtual void VisitVisibilityNode(VisibilityNode node)
{
Visit(node.StrictSemikeywordNode);
Visit(node.VisibilityKeywordNode);
}
public virtual void VisitVisibilitySectionNode(VisibilitySectionNode node)
{
Visit(node.VisibilityNode);
Visit(node.ContentListNode);
}
public virtual void VisitWhileStatementNode(WhileStatementNode node)
{
Visit(node.WhileKeywordNode);
Visit(node.ConditionNode);
Visit(node.DoKeywordNode);
Visit(node.StatementNode);
}
public virtual void VisitWithStatementNode(WithStatementNode node)
{
Visit(node.WithKeywordNode);
Visit(node.ExpressionListNode);
Visit(node.DoKeywordNode);
Visit(node.StatementNode);
}
}
}
| |
// Copyright (c) 2010-2013 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 System.Runtime.InteropServices;
namespace SharpDX.Direct3D9
{
public partial class Texture
{
/// <summary>
/// Initializes a new instance of the <see cref="Texture"/> class.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <unmanaged>HRESULT IDirect3DDevice9::CreateTexture([In] unsigned int Width,[In] unsigned int Height,[In] unsigned int Levels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[Out, Fast] IDirect3DTexture9** ppTexture,[In] void** pSharedHandle)</unmanaged>
public Texture(Device device, int width, int height, int levelCount, Usage usage, Format format, Pool pool)
: base(IntPtr.Zero)
{
device.CreateTexture(width, height, levelCount, (int)usage, format, pool, this, IntPtr.Zero);
}
/// <summary>
/// Initializes a new instance of the <see cref="Texture"/> class.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="sharedHandle">The shared handle.</param>
/// <unmanaged>HRESULT IDirect3DDevice9::CreateTexture([In] unsigned int Width,[In] unsigned int Height,[In] unsigned int Levels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[Out, Fast] IDirect3DTexture9** ppTexture,[In] void** pSharedHandle)</unmanaged>
public Texture(Device device, int width, int height, int levelCount, Usage usage, Format format, Pool pool, ref IntPtr sharedHandle)
: base(IntPtr.Zero)
{
unsafe
{
fixed (void* pSharedHandle = &sharedHandle)
device.CreateTexture(width, height, levelCount, (int)usage, format, pool, this, new IntPtr(pSharedHandle));
}
}
/// <summary>
/// Checks texture-creation parameters.
/// </summary>
/// <param name="device">Device associated with the texture.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="mipLevelCount">Requested number of mipmap levels for the texture.</param>
/// <param name="usage">The requested usage for the texture.</param>
/// <param name="format">Requested format for the texture.</param>
/// <param name="pool">Memory class where the resource will be placed.</param>
/// <returns>
/// A value type containing the proposed values to pass to the texture creation functions.
/// </returns>
/// <unmanaged>HRESULT D3DXCheckTextureRequirements([In] IDirect3DDevice9* pDevice,[InOut] unsigned int* pWidth,[InOut] unsigned int* pHeight,[InOut] unsigned int* pNumMipLevels,[In] unsigned int Usage,[InOut] D3DFORMAT* pFormat,[In] D3DPOOL Pool)</unmanaged>
public static TextureRequirements CheckRequirements(Device device, int width, int height, int mipLevelCount, Usage usage, Format format, Pool pool)
{
var result = new TextureRequirements();
D3DX9.CheckTextureRequirements(device, ref result.Width, ref result.Height, ref result.MipLevelCount, (int)usage, ref result.Format, pool);
return result;
}
/// <summary>
/// Computes the normal map.
/// </summary>
/// <param name="texture">The texture.</param>
/// <param name="sourceTexture">The source texture.</param>
/// <param name="flags">The flags.</param>
/// <param name="channel">The channel.</param>
/// <param name="amplitude">The amplitude.</param>
/// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns>
/// <unmanaged>HRESULT D3DXComputeNormalMap([In] IDirect3DTexture9* pTexture,[In] IDirect3DTexture9* pSrcTexture,[Out, Buffer] const PALETTEENTRY* pSrcPalette,[In] unsigned int Flags,[In] unsigned int Channel,[In] float Amplitude)</unmanaged>
public static void ComputeNormalMap(Texture texture, Texture sourceTexture, NormalMapFlags flags, Channel channel, float amplitude)
{
D3DX9.ComputeNormalMap(texture, sourceTexture, null, (int)flags, (int)channel, amplitude);
}
/// <summary>
/// Computes the normal map.
/// </summary>
/// <param name="texture">The texture.</param>
/// <param name="sourceTexture">The source texture.</param>
/// <param name="palette">The palette.</param>
/// <param name="flags">The flags.</param>
/// <param name="channel">The channel.</param>
/// <param name="amplitude">The amplitude.</param>
/// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns>
/// <unmanaged>HRESULT D3DXComputeNormalMap([In] IDirect3DTexture9* pTexture,[In] IDirect3DTexture9* pSrcTexture,[Out, Buffer] const PALETTEENTRY* pSrcPalette,[In] unsigned int Flags,[In] unsigned int Channel,[In] float Amplitude)</unmanaged>
public static void ComputeNormalMap(Texture texture, Texture sourceTexture, PaletteEntry[] palette, NormalMapFlags flags, Channel channel, float amplitude)
{
D3DX9.ComputeNormalMap(texture, sourceTexture, palette, (int)flags, (int)channel, amplitude);
}
/// <summary>
/// Uses a user-provided function to fill each texel of each mip level of a given texture.
/// </summary>
/// <param name="callback">A function that is used to fill the texture.</param>
/// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns>
/// <unmanaged>HRESULT D3DXFillTexture([In] IDirect3DTexture9* pTexture,[In] __function__stdcall* pFunction,[In] void* pData)</unmanaged>
public void Fill(Fill2DCallback callback)
{
var handle = GCHandle.Alloc(callback);
try
{
D3DX9.FillTexture(this, FillCallbackHelper.Native2DCallbackPtr, GCHandle.ToIntPtr(handle));
}
finally
{
handle.Free();
}
}
/// <summary>
/// Uses a compiled high-level shader language (HLSL) function to fill each texel of each mipmap level of a texture.
/// </summary>
/// <param name="shader">A texture shader object that is used to fill the texture.</param>
/// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns>
/// <unmanaged>HRESULT D3DXFillTextureTX([In] IDirect3DTexture9* pTexture,[In] ID3DXTextureShader* pTextureShader)</unmanaged>
public void Fill(TextureShader shader)
{
D3DX9.FillTextureTX(this, shader);
}
/// <summary>
/// Locks a rectangle on a texture resource.
/// </summary>
/// <param name="level">The level.</param>
/// <param name="flags">The flags.</param>
/// <returns>
/// A <see cref="DataRectangle"/> describing the region locked.
/// </returns>
/// <unmanaged>HRESULT IDirect3DTexture9::LockRect([In] unsigned int Level,[Out] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged>
public DataRectangle LockRectangle(int level, SharpDX.Direct3D9.LockFlags flags)
{
LockedRectangle lockedRect;
LockRectangle(level, out lockedRect, IntPtr.Zero, flags);
return new DataRectangle(lockedRect.PBits, lockedRect.Pitch);
}
/// <summary>
/// Locks a rectangle on a texture resource.
/// </summary>
/// <param name="level">The level.</param>
/// <param name="flags">The flags.</param>
/// <param name="stream">The stream pointing to the locked region.</param>
/// <returns>
/// A <see cref="DataRectangle"/> describing the region locked.
/// </returns>
/// <unmanaged>HRESULT IDirect3DTexture9::LockRect([In] unsigned int Level,[Out] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged>
public DataRectangle LockRectangle(int level, SharpDX.Direct3D9.LockFlags flags, out DataStream stream)
{
LockedRectangle lockedRect;
LockRectangle(level, out lockedRect, IntPtr.Zero, flags);
stream = new DataStream(lockedRect.PBits, lockedRect.Pitch * GetLevelDescription(level).Height, true, (flags & LockFlags.ReadOnly) == 0);
return new DataRectangle(lockedRect.PBits, lockedRect.Pitch);
}
/// <summary>
/// Locks a rectangle on a texture resource.
/// </summary>
/// <param name="level">The level.</param>
/// <param name="rectangle">The rectangle.</param>
/// <param name="flags">The flags.</param>
/// <returns>
/// A <see cref="DataRectangle"/> describing the region locked.
/// </returns>
/// <unmanaged>HRESULT IDirect3DTexture9::LockRect([In] D3DCUBEMAP_FACES FaceType,[In] unsigned int Level,[In] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged>
public DataRectangle LockRectangle(int level, Rectangle rectangle, SharpDX.Direct3D9.LockFlags flags)
{
unsafe
{
LockedRectangle lockedRect;
LockRectangle(level, out lockedRect, new IntPtr(&rectangle), flags);
return new DataRectangle(lockedRect.PBits, lockedRect.Pitch);
}
}
/// <summary>
/// Locks a rectangle on a texture resource.
/// </summary>
/// <param name="level">The level.</param>
/// <param name="rectangle">The rectangle.</param>
/// <param name="flags">The flags.</param>
/// <param name="stream">The stream pointing to the locked region.</param>
/// <returns>
/// A <see cref="DataRectangle"/> describing the region locked.
/// </returns>
/// <unmanaged>HRESULT IDirect3DTexture9::LockRect([In] D3DCUBEMAP_FACES FaceType,[In] unsigned int Level,[In] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged>
public DataRectangle LockRectangle(int level, Rectangle rectangle, SharpDX.Direct3D9.LockFlags flags, out DataStream stream)
{
unsafe
{
LockedRectangle lockedRect;
LockRectangle(level, out lockedRect, new IntPtr(&rectangle), flags);
stream = new DataStream(lockedRect.PBits, lockedRect.Pitch * GetLevelDescription(level).Height, true, (flags & LockFlags.ReadOnly) == 0);
return new DataRectangle(lockedRect.PBits, lockedRect.Pitch);
}
}
/// <summary>
/// Adds a dirty region to a texture resource.
/// </summary>
/// <returns>
/// A <see cref="SharpDX.Result"/> object describing the result of the operation.
/// </returns>
/// <unmanaged>HRESULT IDirect3DTexture9::AddDirtyRect([In] const void* pDirtyRect)</unmanaged>
public void AddDirtyRectangle()
{
AddDirtyRectangle(IntPtr.Zero);
}
/// <summary>
/// Adds a dirty region to a texture resource.
/// </summary>
/// <param name="dirtyRectRef">The dirty rect ref.</param>
/// <returns>
/// A <see cref="SharpDX.Result"/> object describing the result of the operation.
/// </returns>
/// <unmanaged>HRESULT IDirect3DTexture9::AddDirtyRect([In] const void* pDirtyRect)</unmanaged>
public void AddDirtyRectangle(Rectangle dirtyRectRef)
{
unsafe
{
AddDirtyRectangle(new IntPtr(&dirtyRectRef));
}
}
/// <summary>
/// Creates a <see cref="Texture"/> from a file
/// </summary>
/// <param name="device">The device.</param>
/// <param name="filename">The filename.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static Texture FromFile(Device device, string filename)
{
Texture cubeTexture;
D3DX9.CreateTextureFromFileW(device, filename, out cubeTexture);
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="Texture"/> from a file
/// </summary>
/// <param name="device">The device.</param>
/// <param name="filename">The filename.</param>
/// <param name="usage">The usage.</param>
/// <param name="pool">The pool.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static Texture FromFile(Device device, string filename, Usage usage, Pool pool)
{
return FromFile(device, filename, -1, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a file
/// </summary>
/// <param name="device">The device.</param>
/// <param name="filename">The filename.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static Texture FromFile(Device device, string filename, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey)
{
return CreateFromFile(device, filename, width, height, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a file
/// </summary>
/// <param name="device">The device.</param>
/// <param name="filename">The filename.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static unsafe Texture FromFile(Device device, string filename, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation)
{
fixed (void* pImageInfo = &imageInformation)
return CreateFromFile(device, filename, width, height, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a file
/// </summary>
/// <param name="device">The device.</param>
/// <param name="filename">The filename.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static unsafe Texture FromFile(Device device, string filename, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette)
{
palette = new PaletteEntry[256];
fixed (void* pImageInfo = &imageInformation)
return CreateFromFile(device, filename, width, height, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a memory buffer.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemory([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static Texture FromMemory(Device device, byte[] buffer)
{
Texture cubeTexture;
unsafe
{
fixed (void* pData = buffer)
D3DX9.CreateTextureFromFileInMemory(device, (IntPtr)pData, buffer.Length, out cubeTexture);
}
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="Texture"/> from a memory buffer.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="usage">The usage.</param>
/// <param name="pool">The pool.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static Texture FromMemory(Device device, byte[] buffer, Usage usage, Pool pool)
{
return FromMemory(device, buffer, -1, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a memory buffer.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static Texture FromMemory(Device device, byte[] buffer, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey)
{
return CreateFromMemory(device, buffer, width, height, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a memory buffer.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static unsafe Texture FromMemory(Device device, byte[] buffer, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation)
{
fixed (void* pImageInfo = &imageInformation)
return CreateFromMemory(device, buffer, width, height, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a memory buffer.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static unsafe Texture FromMemory(Device device, byte[] buffer, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette)
{
palette = new PaletteEntry[256];
fixed (void* pImageInfo = &imageInformation)
return CreateFromMemory(device, buffer, width, height, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <returns>A <see cref="Texture"/></returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemory([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static Texture FromStream(Device device, Stream stream)
{
Texture cubeTexture;
if (stream is DataStream)
{
D3DX9.CreateTextureFromFileInMemory(device, ((DataStream)stream).PositionPointer, (int)(stream.Length - stream.Position), out cubeTexture);
}
else
{
unsafe
{
var data = Utilities.ReadStream(stream);
fixed (void* pData = data)
D3DX9.CreateTextureFromFileInMemory(device, (IntPtr)pData, data.Length, out cubeTexture);
}
}
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="Texture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="usage">The usage.</param>
/// <param name="pool">The pool.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static Texture FromStream(Device device, Stream stream, Usage usage, Pool pool)
{
return FromStream(device, stream, 0, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static Texture FromStream(Device device, Stream stream, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey)
{
return FromStream(device, stream, 0, width, height, levelCount, usage, format, pool, filter, mipFilter, colorKey);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="sizeBytes">The size bytes.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static Texture FromStream(Device device, Stream stream, int sizeBytes, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey)
{
return CreateFromStream(device, stream, sizeBytes, width, height, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="sizeBytes">The size bytes.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static unsafe Texture FromStream(Device device, Stream stream, int sizeBytes, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation)
{
fixed (void* pImageInfo = &imageInformation)
return CreateFromStream(device, stream, sizeBytes, width, height, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="sizeBytes">The size bytes.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
public static unsafe Texture FromStream(Device device, Stream stream, int sizeBytes, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette)
{
palette = new PaletteEntry[256];
fixed (void* pImageInfo = &imageInformation)
return CreateFromStream(device, stream, sizeBytes, width, height, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette);
}
/// <summary>
/// Creates a <see cref="Texture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
private static unsafe Texture CreateFromMemory(Device device, byte[] buffer, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette)
{
Texture cubeTexture;
fixed (void* pBuffer = buffer)
cubeTexture = CreateFromPointer(
device,
(IntPtr)pBuffer,
buffer.Length,
width,
height,
levelCount,
usage,
format,
pool,
filter,
mipFilter,
colorKey,
imageInformation,
palette
);
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="Texture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="sizeBytes">The size bytes.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>A <see cref="Texture"/></returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
private static unsafe Texture CreateFromStream(Device device, Stream stream, int sizeBytes, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette)
{
Texture cubeTexture;
sizeBytes = sizeBytes == 0 ? (int)(stream.Length - stream.Position): sizeBytes;
if (stream is DataStream)
{
cubeTexture = CreateFromPointer(
device,
((DataStream)stream).PositionPointer,
sizeBytes,
width,
height,
levelCount,
usage,
format,
pool,
filter,
mipFilter,
colorKey,
imageInformation,
palette
);
}
else
{
var data = Utilities.ReadStream(stream);
fixed (void* pData = data)
cubeTexture = CreateFromPointer(
device,
(IntPtr)pData,
data.Length,
width,
height,
levelCount,
usage,
format,
pool,
filter,
mipFilter,
colorKey,
imageInformation,
palette
);
}
stream.Position = sizeBytes;
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="Texture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="pointer">The pointer.</param>
/// <param name="sizeInBytes">The size in bytes.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
private static unsafe Texture CreateFromPointer(Device device, IntPtr pointer, int sizeInBytes, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette)
{
Texture cubeTexture;
D3DX9.CreateTextureFromFileInMemoryEx(
device,
pointer,
sizeInBytes,
width,
height,
levelCount,
(int)usage,
format,
pool,
(int)filter,
(int)mipFilter,
(Color)colorKey,
imageInformation,
palette,
out cubeTexture);
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="Texture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="fileName">Name of the file.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="Texture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DTexture9** ppTexture)</unmanaged>
private static Texture CreateFromFile(Device device, string fileName, int width, int height, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette)
{
Texture cubeTexture;
D3DX9.CreateTextureFromFileExW(
device,
fileName,
width,
height,
levelCount,
(int)usage,
format,
pool,
(int)filter,
(int)mipFilter,
(Color)colorKey,
imageInformation,
palette,
out cubeTexture);
return cubeTexture;
}
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2010 the Open Toolkit library.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
// flibit Added This!!!
#pragma warning disable 3021
namespace OpenTK
{
#region BlittableValueType<T>
/// <summary>
/// Checks whether the specified type parameter is a blittable value type.
/// </summary>
/// <remarks>
/// A blittable value type is a struct that only references other value types recursively,
/// which allows it to be passed to unmanaged code directly.
/// </remarks>
public static class BlittableValueType<T>
{
#region Fields
static readonly Type Type;
static readonly int stride;
#endregion
#region Constructors
static BlittableValueType()
{
Type = typeof(T);
if (Type.IsValueType && !Type.IsGenericType)
{
// Does this support generic types? On Mono 2.4.3 it does
// On .Net it doesn't.
// http://msdn.microsoft.com/en-us/library/5s4920fa.aspx
stride = Marshal.SizeOf(typeof(T));
}
}
#endregion
#region Public Members
/// <summary>
/// Gets the size of the type in bytes or 0 for non-blittable types.
/// </summary>
/// <remarks>
/// This property returns 0 for non-blittable types.
/// </remarks>
public static int Stride { get { return stride; } }
#region Check
/// <summary>
/// Checks whether the current typename T is blittable.
/// </summary>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check()
{
return Check(Type);
}
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">A System.Type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check(Type type)
{
if (!CheckStructLayoutAttribute(type))
Debug.Print("Warning: type {0} does not specify a StructLayoutAttribute with Pack=1. The memory layout of the struct may change between platforms.", type.Name);
return CheckType(type);
}
#endregion
#endregion
#region Private Members
// Checks whether the parameter is a primitive type or consists of primitive types recursively.
// Throws a NotSupportedException if it is not.
static bool CheckType(Type type)
{
//Debug.Print("Checking type {0} (size: {1} bytes).", type.Name, Marshal.SizeOf(type));
if (type.IsPrimitive)
return true;
if (!type.IsValueType)
return false;
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
Debug.Indent();
foreach (FieldInfo field in fields)
{
if (!CheckType(field.FieldType))
return false;
}
Debug.Unindent();
return Stride != 0;
}
// Checks whether the specified struct defines [StructLayout(LayoutKind.Sequential, Pack=1)]
// or [StructLayout(LayoutKind.Explicit)]
static bool CheckStructLayoutAttribute(Type type)
{
StructLayoutAttribute[] attr = (StructLayoutAttribute[])
type.GetCustomAttributes(typeof(StructLayoutAttribute), true);
if ((attr == null) ||
(attr != null && attr.Length > 0 && attr[0].Value != LayoutKind.Explicit && attr[0].Pack != 1))
return false;
return true;
}
#endregion
}
#endregion
#region BlittableValueType
/// <summary>
/// Checks whether the specified type parameter is a blittable value type.
/// </summary>
/// <remarks>
/// A blittable value type is a struct that only references other value types recursively,
/// which allows it to be passed to unmanaged code directly.
/// </remarks>
public static class BlittableValueType
{
#region Check
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">An instance of the type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check<T>(T type)
{
return BlittableValueType<T>.Check();
}
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">An instance of the type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check<T>(T[] type)
{
return BlittableValueType<T>.Check();
}
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">An instance of the type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check<T>(T[,] type)
{
return BlittableValueType<T>.Check();
}
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">An instance of the type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check<T>(T[, ,] type)
{
return BlittableValueType<T>.Check();
}
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">An instance of the type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
[CLSCompliant(false)]
public static bool Check<T>(T[][] type)
{
return BlittableValueType<T>.Check();
}
#endregion
#region StrideOf
/// <summary>
/// Returns the size of the specified value type in bytes or 0 if the type is not blittable.
/// </summary>
/// <typeparam name="T">The value type. Must be blittable.</typeparam>
/// <param name="type">An instance of the value type.</param>
/// <returns>An integer, specifying the size of the type in bytes.</returns>
/// <exception cref="System.ArgumentException">Occurs when type is not blittable.</exception>
public static int StrideOf<T>(T type)
{
if (!Check(type))
throw new ArgumentException("type");
return BlittableValueType<T>.Stride;
}
/// <summary>
/// Returns the size of a single array element in bytes or 0 if the element is not blittable.
/// </summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="type">An instance of the value type.</param>
/// <returns>An integer, specifying the size of the type in bytes.</returns>
/// <exception cref="System.ArgumentException">Occurs when type is not blittable.</exception>
public static int StrideOf<T>(T[] type)
{
if (!Check(type))
throw new ArgumentException("type");
return BlittableValueType<T>.Stride;
}
/// <summary>
/// Returns the size of a single array element in bytes or 0 if the element is not blittable.
/// </summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="type">An instance of the value type.</param>
/// <returns>An integer, specifying the size of the type in bytes.</returns>
/// <exception cref="System.ArgumentException">Occurs when type is not blittable.</exception>
public static int StrideOf<T>(T[,] type)
{
if (!Check(type))
throw new ArgumentException("type");
return BlittableValueType<T>.Stride;
}
/// <summary>
/// Returns the size of a single array element in bytes or 0 if the element is not blittable.
/// </summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="type">An instance of the value type.</param>
/// <returns>An integer, specifying the size of the type in bytes.</returns>
/// <exception cref="System.ArgumentException">Occurs when type is not blittable.</exception>
public static int StrideOf<T>(T[, ,] type)
{
if (!Check(type))
throw new ArgumentException("type");
return BlittableValueType<T>.Stride;
}
#endregion
}
#endregion
}
// flibit Added This!!!
#pragma warning restore 3021
| |
// 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.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Xml.Extensions;
namespace System.Xml.Serialization
{
internal class SourceInfo
{
//a[ia]
//((global::System.Xml.Serialization.XmlSerializerNamespaces)p[0])
private static Regex s_regex = new Regex("([(][(](?<t>[^)]+)[)])?(?<a>[^[]+)[[](?<ia>.+)[]][)]?");
//((global::Microsoft.CFx.Test.Common.TypeLibrary.IXSType_9)o), @"IXSType_9", @"", true, true);
private static Regex s_regex2 = new Regex("[(][(](?<cast>[^)]+)[)](?<arg>[^)]+)[)]");
private static readonly Lazy<MethodInfo> s_iListGetItemMethod = new Lazy<MethodInfo>(
() =>
{
return typeof(IList).GetMethod(
"get_Item",
new Type[] { typeof(int) }
);
});
public string Source;
public readonly string Arg;
public readonly MemberInfo MemberInfo;
public readonly Type Type;
public readonly CodeGenerator ILG;
public SourceInfo(string source, string arg, MemberInfo memberInfo, Type type, CodeGenerator ilg)
{
this.Source = source;
this.Arg = arg ?? source;
this.MemberInfo = memberInfo;
this.Type = type;
this.ILG = ilg;
}
public SourceInfo CastTo(TypeDesc td)
{
return new SourceInfo("((" + td.CSharpName + ")" + Source + ")", Arg, MemberInfo, td.Type, ILG);
}
public void LoadAddress(Type elementType)
{
InternalLoad(elementType, asAddress: true);
}
public void Load(Type elementType)
{
InternalLoad(elementType);
}
private void InternalLoad(Type elementType, bool asAddress = false)
{
Match match = s_regex.Match(Arg);
if (match.Success)
{
object varA = ILG.GetVariable(match.Groups["a"].Value);
Type varType = ILG.GetVariableType(varA);
object varIA = ILG.GetVariable(match.Groups["ia"].Value);
if (varType.IsArray)
{
ILG.Load(varA);
ILG.Load(varIA);
Type eType = varType.GetElementType();
if (CodeGenerator.IsNullableGenericType(eType))
{
ILG.Ldelema(eType);
ConvertNullableValue(eType, elementType);
}
else
{
if (eType.IsValueType)
{
ILG.Ldelema(eType);
if (!asAddress)
{
ILG.Ldobj(eType);
}
}
else
ILG.Ldelem(eType);
if (elementType != null)
ILG.ConvertValue(eType, elementType);
}
}
else
{
ILG.Load(varA);
ILG.Load(varIA);
MethodInfo get_Item = varType.GetMethod(
"get_Item",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(int) }
);
if (get_Item == null && typeof(IList).IsAssignableFrom(varType))
{
get_Item = s_iListGetItemMethod.Value;
}
Debug.Assert(get_Item != null);
ILG.Call(get_Item);
Type eType = get_Item.ReturnType;
if (CodeGenerator.IsNullableGenericType(eType))
{
LocalBuilder localTmp = ILG.GetTempLocal(eType);
ILG.Stloc(localTmp);
ILG.Ldloca(localTmp);
ConvertNullableValue(eType, elementType);
}
else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType)))
{
throw new CodeGeneratorConversionException(eType, elementType, asAddress, "IsNotAssignableFrom");
}
else
{
Convert(eType, elementType, asAddress);
}
}
}
else if (Source == "null")
{
ILG.Load(null);
}
else
{
object var;
Type varType;
if (Arg.StartsWith("o.@", StringComparison.Ordinal) || MemberInfo != null)
{
var = ILG.GetVariable(Arg.StartsWith("o.@", StringComparison.Ordinal) ? "o" : Arg);
varType = ILG.GetVariableType(var);
if (varType.IsValueType)
ILG.LoadAddress(var);
else
ILG.Load(var);
}
else
{
var = ILG.GetVariable(Arg);
varType = ILG.GetVariableType(var);
if (CodeGenerator.IsNullableGenericType(varType) &&
varType.GetGenericArguments()[0] == elementType)
{
ILG.LoadAddress(var);
ConvertNullableValue(varType, elementType);
}
else
{
if (asAddress)
ILG.LoadAddress(var);
else
ILG.Load(var);
}
}
if (MemberInfo != null)
{
Type memberType = (MemberInfo is FieldInfo) ?
((FieldInfo)MemberInfo).FieldType : ((PropertyInfo)MemberInfo).PropertyType;
if (CodeGenerator.IsNullableGenericType(memberType))
{
ILG.LoadMemberAddress(MemberInfo);
ConvertNullableValue(memberType, elementType);
}
else
{
ILG.LoadMember(MemberInfo);
Convert(memberType, elementType, asAddress);
}
}
else
{
match = s_regex2.Match(Source);
if (match.Success)
{
Debug.Assert(match.Groups["arg"].Value == Arg);
Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type));
if (asAddress)
ILG.ConvertAddress(varType, Type);
else
ILG.ConvertValue(varType, Type);
varType = Type;
}
Convert(varType, elementType, asAddress);
}
}
}
private void Convert(Type sourceType, Type targetType, bool asAddress)
{
if (targetType != null)
{
if (asAddress)
ILG.ConvertAddress(sourceType, targetType);
else
ILG.ConvertValue(sourceType, targetType);
}
}
private void ConvertNullableValue(Type nullableType, Type targetType)
{
System.Diagnostics.Debug.Assert(targetType == nullableType || targetType.IsAssignableFrom(nullableType.GetGenericArguments()[0]));
if (targetType != nullableType)
{
MethodInfo Nullable_get_Value = nullableType.GetMethod(
"get_Value",
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ILG.Call(Nullable_get_Value);
if (targetType != null)
{
ILG.ConvertValue(Nullable_get_Value.ReturnType, targetType);
}
}
}
public static implicit operator string (SourceInfo source)
{
return source.Source;
}
public static bool operator !=(SourceInfo a, SourceInfo b)
{
if ((object)a != null)
return !a.Equals(b);
return (object)b != null;
}
public static bool operator ==(SourceInfo a, SourceInfo b)
{
if ((object)a != null)
return a.Equals(b);
return (object)b == null;
}
public override bool Equals(object obj)
{
if (obj == null)
return Source == null;
SourceInfo info = obj as SourceInfo;
if (info != null)
return Source == info.Source;
return false;
}
public override int GetHashCode()
{
return (Source == null) ? 0 : Source.GetHashCode();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// 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.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
#if SRM
namespace System.Reflection.Metadata.Decoding
#else
namespace Roslyn.Reflection.Metadata.Decoding
#endif
{
/// <summary>
/// Decodes signature blobs.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
#if SRM && FUTURE
public
#endif
internal struct SignatureDecoder<TType>
{
private readonly ISignatureTypeProvider<TType> _provider;
private readonly MetadataReader _metadataReaderOpt;
private readonly SignatureDecoderOptions _options;
/// <summary>
/// Creates a new SignatureDecoder.
/// </summary>
/// <param name="provider">The provider used to obtain type symbols as the signature is decoded.</param>
/// <param name="metadataReader">
/// The metadata reader from which the signature was obtained. It may be null if the given provider allows it.
/// However, if <see cref="SignatureDecoderOptions.DifferentiateClassAndValueTypes"/> is specified, it should
/// be non-null to evaluate WinRT projections from class to value type or vice-versa correctly.
/// </param>
/// <param name="options">Set of optional decoder features to enable.</param>
public SignatureDecoder(
ISignatureTypeProvider<TType> provider,
MetadataReader metadataReader = null,
SignatureDecoderOptions options = SignatureDecoderOptions.None)
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
_metadataReaderOpt = metadataReader;
_provider = provider;
_options = options;
}
/// <summary>
/// Decodes a type embedded in a signature and advances the reader past the type.
/// </summary>
/// <param name="blobReader">The blob reader positioned at the leading SignatureTypeCode</param>
/// <param name="allowTypeSpecifications">Allow a <see cref="TypeSpecificationHandle"/> to follow a (CLASS | VALUETYPE) in the signature.
/// At present, the only context where that would be valid is in a LocalConstantSig as defined by the Portable PDB specification.
/// </param>
/// <returns>The decoded type.</returns>
/// <exception cref="System.BadImageFormatException">The reader was not positioned at a valid signature type.</exception>
public TType DecodeType(ref BlobReader blobReader, bool allowTypeSpecifications = false)
{
return DecodeType(ref blobReader, allowTypeSpecifications, blobReader.ReadCompressedInteger());
}
private TType DecodeType(ref BlobReader blobReader, bool allowTypeSpecifications, int typeCode)
{
TType elementType;
int index;
switch (typeCode)
{
case (int)SignatureTypeCode.Boolean:
case (int)SignatureTypeCode.Char:
case (int)SignatureTypeCode.SByte:
case (int)SignatureTypeCode.Byte:
case (int)SignatureTypeCode.Int16:
case (int)SignatureTypeCode.UInt16:
case (int)SignatureTypeCode.Int32:
case (int)SignatureTypeCode.UInt32:
case (int)SignatureTypeCode.Int64:
case (int)SignatureTypeCode.UInt64:
case (int)SignatureTypeCode.Single:
case (int)SignatureTypeCode.Double:
case (int)SignatureTypeCode.IntPtr:
case (int)SignatureTypeCode.UIntPtr:
case (int)SignatureTypeCode.Object:
case (int)SignatureTypeCode.String:
case (int)SignatureTypeCode.Void:
case (int)SignatureTypeCode.TypedReference:
return _provider.GetPrimitiveType((PrimitiveTypeCode)typeCode);
case (int)SignatureTypeCode.Pointer:
elementType = DecodeType(ref blobReader);
return _provider.GetPointerType(elementType);
case (int)SignatureTypeCode.ByReference:
elementType = DecodeType(ref blobReader);
return _provider.GetByReferenceType(elementType);
case (int)SignatureTypeCode.Pinned:
elementType = DecodeType(ref blobReader);
return _provider.GetPinnedType(elementType);
case (int)SignatureTypeCode.SZArray:
elementType = DecodeType(ref blobReader);
return _provider.GetSZArrayType(elementType);
case (int)SignatureTypeCode.FunctionPointer:
MethodSignature<TType> methodSignature = DecodeMethodSignature(ref blobReader);
return _provider.GetFunctionPointerType(methodSignature);
case (int)SignatureTypeCode.Array:
return DecodeArrayType(ref blobReader);
case (int)SignatureTypeCode.RequiredModifier:
return DecodeModifiedType(ref blobReader, isRequired: true);
case (int)SignatureTypeCode.OptionalModifier:
return DecodeModifiedType(ref blobReader, isRequired: false);
case (int)SignatureTypeCode.GenericTypeInstance:
return DecodeGenericTypeInstance(ref blobReader);
case (int)SignatureTypeCode.GenericTypeParameter:
index = blobReader.ReadCompressedInteger();
return _provider.GetGenericTypeParameter(index);
case (int)SignatureTypeCode.GenericMethodParameter:
index = blobReader.ReadCompressedInteger();
return _provider.GetGenericMethodParameter(index);
case (int)SignatureTypeHandleCode.Class:
case (int)SignatureTypeHandleCode.ValueType:
return DecodeTypeHandle(ref blobReader, (SignatureTypeHandleCode)typeCode, allowTypeSpecifications);
default:
#if SRM
throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureTypeCode, typeCode));
#else
throw new BadImageFormatException();
#endif
}
}
/// <summary>
/// Decodes a list of types, with at least one instance that is preceded by its count as a compressed integer.
/// </summary>
private ImmutableArray<TType> DecodeTypeSequence(ref BlobReader blobReader)
{
int count = blobReader.ReadCompressedInteger();
if (count == 0)
{
// This method is used for Local signatures and method specs, neither of which can have
// 0 elements. Parameter sequences can have 0 elements, but they are handled separately
// to deal with the sentinel/varargs case.
#if SRM
throw new BadImageFormatException(SR.SignatureTypeSequenceMustHaveAtLeastOneElement);
#else
throw new BadImageFormatException();
#endif
}
var types = ImmutableArray.CreateBuilder<TType>(count);
for (int i = 0; i < count; i++)
{
types.Add(DecodeType(ref blobReader));
}
return types.MoveToImmutable();
}
/// <summary>
/// Decodes a method (definition, reference, or standalone) or property signature blob.
/// </summary>
/// <param name="blobReader">BlobReader positioned at a method signature.</param>
/// <returns>The decoded method signature.</returns>
/// <exception cref="System.BadImageFormatException">The method signature is invalid.</exception>
public MethodSignature<TType> DecodeMethodSignature(ref BlobReader blobReader)
{
SignatureHeader header = blobReader.ReadSignatureHeader();
CheckMethodOrPropertyHeader(header);
int genericParameterCount = 0;
if (header.IsGeneric)
{
genericParameterCount = blobReader.ReadCompressedInteger();
}
int parameterCount = blobReader.ReadCompressedInteger();
TType returnType = DecodeType(ref blobReader);
ImmutableArray<TType> parameterTypes;
int requiredParameterCount;
if (parameterCount == 0)
{
requiredParameterCount = 0;
parameterTypes = ImmutableArray<TType>.Empty;
}
else
{
var parameterBuilder = ImmutableArray.CreateBuilder<TType>(parameterCount);
int parameterIndex;
for (parameterIndex = 0; parameterIndex < parameterCount; parameterIndex++)
{
int typeCode = blobReader.ReadCompressedInteger();
if (typeCode == (int)SignatureTypeCode.Sentinel)
{
break;
}
parameterBuilder.Add(DecodeType(ref blobReader, allowTypeSpecifications: false, typeCode: typeCode));
}
requiredParameterCount = parameterIndex;
for (; parameterIndex < parameterCount; parameterIndex++)
{
parameterBuilder.Add(DecodeType(ref blobReader));
}
parameterTypes = parameterBuilder.MoveToImmutable();
}
return new MethodSignature<TType>(header, returnType, requiredParameterCount, genericParameterCount, parameterTypes);
}
/// <summary>
/// Decodes a method specification signature blob and advances the reader past the signature.
/// </summary>
/// <param name="blobReader">A BlobReader positioned at a valid method specification signature.</param>
/// <returns>The types used to instantiate a generic method via the method specification.</returns>
public ImmutableArray<TType> DecodeMethodSpecificationSignature(ref BlobReader blobReader)
{
SignatureHeader header = blobReader.ReadSignatureHeader();
CheckHeader(header, SignatureKind.MethodSpecification);
return DecodeTypeSequence(ref blobReader);
}
/// <summary>
/// Decodes a local variable signature blob and advances the reader past the signature.
/// </summary>
/// <param name="blobReader">The blob reader positioned at a local variable signature.</param>
/// <returns>The local variable types.</returns>
/// <exception cref="System.BadImageFormatException">The local variable signature is invalid.</exception>
public ImmutableArray<TType> DecodeLocalSignature(ref BlobReader blobReader)
{
SignatureHeader header = blobReader.ReadSignatureHeader();
CheckHeader(header, SignatureKind.LocalVariables);
return DecodeTypeSequence(ref blobReader);
}
/// <summary>
/// Decodes a field signature blob and advances the reader past the signature.
/// </summary>
/// <param name="blobReader">The blob reader positioned at a field signature.</param>
/// <returns>The decoded field type.</returns>
public TType DecodeFieldSignature(ref BlobReader blobReader)
{
SignatureHeader header = blobReader.ReadSignatureHeader();
CheckHeader(header, SignatureKind.Field);
return DecodeType(ref blobReader);
}
private TType DecodeArrayType(ref BlobReader blobReader)
{
// PERF_TODO: Cache/reuse common case of small number of all-zero lower-bounds.
TType elementType = DecodeType(ref blobReader);
int rank = blobReader.ReadCompressedInteger();
var sizes = ImmutableArray<int>.Empty;
var lowerBounds = ImmutableArray<int>.Empty;
int sizesCount = blobReader.ReadCompressedInteger();
if (sizesCount > 0)
{
var builder = ImmutableArray.CreateBuilder<int>(sizesCount);
for (int i = 0; i < sizesCount; i++)
{
builder.Add(blobReader.ReadCompressedInteger());
}
sizes = builder.MoveToImmutable();
}
int lowerBoundsCount = blobReader.ReadCompressedInteger();
if (lowerBoundsCount > 0)
{
var builder = ImmutableArray.CreateBuilder<int>(lowerBoundsCount);
for (int i = 0; i < lowerBoundsCount; i++)
{
builder.Add(blobReader.ReadCompressedSignedInteger());
}
lowerBounds = builder.MoveToImmutable();
}
var arrayShape = new ArrayShape(rank, sizes, lowerBounds);
return _provider.GetArrayType(elementType, arrayShape);
}
private TType DecodeGenericTypeInstance(ref BlobReader blobReader)
{
TType genericType = DecodeType(ref blobReader);
ImmutableArray<TType> types = DecodeTypeSequence(ref blobReader);
return _provider.GetGenericInstance(genericType, types);
}
private TType DecodeModifiedType(ref BlobReader blobReader, bool isRequired)
{
TType modifier = DecodeTypeDefOrRefOrSpec(ref blobReader, SignatureTypeHandleCode.Unresolved);
TType unmodifiedType = DecodeType(ref blobReader);
return _provider.GetModifiedType(_metadataReaderOpt, isRequired, modifier, unmodifiedType);
}
private TType DecodeTypeDefOrRef(ref BlobReader blobReader, SignatureTypeHandleCode code)
{
return DecodeTypeHandle(ref blobReader, code, allowTypeSpecifications: false);
}
private TType DecodeTypeDefOrRefOrSpec(ref BlobReader blobReader, SignatureTypeHandleCode code)
{
return DecodeTypeHandle(ref blobReader, code, allowTypeSpecifications: true);
}
private TType DecodeTypeHandle(ref BlobReader blobReader, SignatureTypeHandleCode code, bool allowTypeSpecifications)
{
// Force no differentiation of class vs. value type unless the option is enabled.
// Avoids cost of WinRT projection.
if ((_options & SignatureDecoderOptions.DifferentiateClassAndValueTypes) == 0)
{
code = SignatureTypeHandleCode.Unresolved;
}
EntityHandle handle = blobReader.ReadTypeHandle();
if (!handle.IsNil)
{
switch (handle.Kind)
{
case HandleKind.TypeDefinition:
var typeDef = (TypeDefinitionHandle)handle;
return _provider.GetTypeFromDefinition(_metadataReaderOpt, typeDef, code);
case HandleKind.TypeReference:
var typeRef = (TypeReferenceHandle)handle;
if (code != SignatureTypeHandleCode.Unresolved)
{
ProjectClassOrValueType(typeRef, ref code);
}
return _provider.GetTypeFromReference(_metadataReaderOpt, typeRef, code);
case HandleKind.TypeSpecification:
if (!allowTypeSpecifications)
{
#if SRM
// To prevent cycles, the token following (CLASS | VALUETYPE) must not be a type spec.
// https://github.com/dotnet/coreclr/blob/8ff2389204d7c41b17eff0e9536267aea8d6496f/src/md/compiler/mdvalidator.cpp#L6154-L6160
throw new BadImageFormatException(SR.NotTypeDefOrRefHandle);
#else
throw new BadImageFormatException();
#endif
}
if (code != SignatureTypeHandleCode.Unresolved)
{
// TODO: We need more work here in differentiating case because instantiations can project class
// to value type as in IReference<T> -> Nullable<T>. Unblocking Roslyn work where the differentiation
// feature is not used. Note that the use-case of custom-mods will not hit this because there is no
// CLASS | VALUETYPE before the modifier token and so it always comes in unresolved.
code = SignatureTypeHandleCode.Unresolved; // never lie in the meantime.
}
var typeSpec = (TypeSpecificationHandle)handle;
return _provider.GetTypeFromSpecification(_metadataReaderOpt, typeSpec, SignatureTypeHandleCode.Unresolved);
default:
// indicates an error returned from ReadTypeHandle, otherwise unreachable.
Debug.Assert(handle.IsNil); // will fall through to throw in release.
break;
}
}
#if SRM
throw new BadImageFormatException(SR.NotTypeDefOrRefOrSpecHandle);
#else
throw new BadImageFormatException();
#endif
}
private void ProjectClassOrValueType(TypeReferenceHandle handle, ref SignatureTypeHandleCode code)
{
Debug.Assert(code != SignatureTypeHandleCode.Unresolved);
Debug.Assert((_options & SignatureDecoderOptions.DifferentiateClassAndValueTypes) != 0);
if (_metadataReaderOpt == null)
{
// If we're asked to differentiate value types without a reader, then
// return the designation unprojected as it occurs in the signature blob.
return;
}
#if SRM
TypeReference typeRef = _metadataReaderOpt.GetTypeReference(handle);
switch (typeRef.SignatureTreatment)
{
case TypeRefSignatureTreatment.ProjectedToClass:
code = SignatureTypeHandleCode.Class;
break;
case TypeRefSignatureTreatment.ProjectedToValueType:
code = SignatureTypeHandleCode.ValueType;
break;
}
#endif
}
private void CheckHeader(SignatureHeader header, SignatureKind expectedKind)
{
if (header.Kind != expectedKind)
{
#if SRM
throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureHeader, expectedKind, header.Kind, header.RawValue));
#else
throw new BadImageFormatException();
#endif
}
}
private void CheckMethodOrPropertyHeader(SignatureHeader header)
{
SignatureKind kind = header.Kind;
if (kind != SignatureKind.Method && kind != SignatureKind.Property)
{
#if SRM
throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureHeader2, SignatureKind.Property, SignatureKind.Method, header.Kind, header.RawValue));
#else
throw new BadImageFormatException();
#endif
}
}
}
}
| |
/************************************************************************************
Filename : OVRLipSyncContextMorphTarget.cs
Content : This bridges the viseme output to the morph targets
Created : August 7th, 2015
Copyright : Copyright Facebook Technologies, LLC and its affiliates.
All rights reserved.
Licensed under the Oculus Audio SDK License Version 3.3 (the "License");
you may not use the Oculus Audio SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/audio-3.3/
Unless required by applicable law or agreed to in writing, the Oculus Audio SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using System.Linq;
public class OVRLipSyncContextMorphTarget : MonoBehaviour
{
// PUBLIC
// Manually assign the skinned mesh renderer to this script
[Tooltip("Skinned Mesh Rendered target to be driven by Oculus Lipsync")]
public SkinnedMeshRenderer skinnedMeshRenderer = null;
// Set the blendshape index to go to (-1 means there is not one assigned)
[Tooltip("Blendshape index to trigger for each viseme.")]
public int [] visemeToBlendTargets = Enumerable.Range(0, OVRLipSync.VisemeCount).ToArray();
// enable/disable sending signals to viseme engine
[Tooltip("Enable using the test keys defined below to manually trigger each viseme.")]
public bool enableVisemeTestKeys = false;
[Tooltip("Test keys used to manually trigger an individual viseme - by " +
"default the QWERTY row of a US keyboard.")]
public KeyCode[] visemeTestKeys =
{
KeyCode.BackQuote,
KeyCode.Tab,
KeyCode.Q,
KeyCode.W,
KeyCode.E,
KeyCode.R,
KeyCode.T,
KeyCode.Y,
KeyCode.U,
KeyCode.I,
KeyCode.O,
KeyCode.P,
KeyCode.LeftBracket,
KeyCode.RightBracket,
KeyCode.Backslash,
};
[Tooltip("Test key used to manually trigger laughter and visualise the results")]
public KeyCode laughterKey = KeyCode.CapsLock;
[Tooltip("Blendshape index to trigger for laughter")]
public int laughterBlendTarget = OVRLipSync.VisemeCount;
[Range(0.0f, 1.0f)]
[Tooltip("Laughter probability threshold above which the laughter blendshape will be activated")]
public float laughterThreshold = 0.5f;
[Range(0.0f, 3.0f)]
[Tooltip("Laughter animation linear multiplier, the final output will be clamped to 1.0")]
public float laughterMultiplier = 1.5f;
// smoothing amount
[Range(1, 100)]
[Tooltip("Smoothing of 1 will yield only the current predicted viseme, 100 will yield an extremely smooth viseme response.")]
public int smoothAmount = 70;
// PRIVATE
// Look for a lip-sync Context (should be set at the same level as this component)
private OVRLipSyncContextBase lipsyncContext = null;
/// <summary>
/// Start this instance.
/// </summary>
void Start ()
{
// morph target needs to be set manually; possibly other components will need the same
if(skinnedMeshRenderer == null)
{
Debug.LogError("LipSyncContextMorphTarget.Start Error: " +
"Please set the target Skinned Mesh Renderer to be controlled!");
return;
}
// make sure there is a phoneme context assigned to this object
lipsyncContext = GetComponent<OVRLipSyncContextBase>();
if(lipsyncContext == null)
{
Debug.LogError("LipSyncContextMorphTarget.Start Error: " +
"No OVRLipSyncContext component on this object!");
}
else
{
// Send smoothing amount to context
lipsyncContext.Smoothing = smoothAmount;
}
}
/// <summary>
/// Update this instance.
/// </summary>
void Update ()
{
if((lipsyncContext != null) && (skinnedMeshRenderer != null))
{
// get the current viseme frame
OVRLipSync.Frame frame = lipsyncContext.GetCurrentPhonemeFrame();
if (frame != null)
{
SetVisemeToMorphTarget(frame);
SetLaughterToMorphTarget(frame);
}
// TEST visemes by capturing key inputs and sending a signal
CheckForKeys();
// Update smoothing value
if (smoothAmount != lipsyncContext.Smoothing)
{
lipsyncContext.Smoothing = smoothAmount;
}
}
}
/// <summary>
/// Sends the signals.
/// </summary>
void CheckForKeys()
{
if (enableVisemeTestKeys)
{
for (int i = 0; i < OVRLipSync.VisemeCount; ++i)
{
CheckVisemeKey(visemeTestKeys[i], i, 100);
}
}
CheckLaughterKey();
}
/// <summary>
/// Sets the viseme to morph target.
/// </summary>
void SetVisemeToMorphTarget(OVRLipSync.Frame frame)
{
for (int i = 0; i < visemeToBlendTargets.Length; i++)
{
if (visemeToBlendTargets[i] != -1)
{
// Viseme blend weights are in range of 0->1.0, we need to make range 100
skinnedMeshRenderer.SetBlendShapeWeight(
visemeToBlendTargets[i],
frame.Visemes[i] * 100.0f);
}
}
}
/// <summary>
/// Sets the laughter to morph target.
/// </summary>
void SetLaughterToMorphTarget(OVRLipSync.Frame frame)
{
if (laughterBlendTarget != -1)
{
// Laughter score will be raw classifier output in [0,1]
float laughterScore = frame.laughterScore;
// Threshold then re-map to [0,1]
laughterScore = laughterScore < laughterThreshold ? 0.0f : laughterScore - laughterThreshold;
laughterScore = Mathf.Min(laughterScore * laughterMultiplier, 1.0f);
laughterScore *= 1.0f / laughterThreshold;
skinnedMeshRenderer.SetBlendShapeWeight(
laughterBlendTarget,
laughterScore * 100.0f);
}
}
/// <summary>
/// Sends the viseme signal.
/// </summary>
/// <param name="key">Key.</param>
/// <param name="viseme">Viseme.</param>
/// <param name="arg1">Arg1.</param>
void CheckVisemeKey(KeyCode key, int viseme, int amount)
{
if (Input.GetKeyDown(key))
{
lipsyncContext.SetVisemeBlend(visemeToBlendTargets[viseme], amount);
}
if (Input.GetKeyUp(key))
{
lipsyncContext.SetVisemeBlend(visemeToBlendTargets[viseme], 0);
}
}
/// <summary>
/// Sends the laughter signal.
/// </summary>
void CheckLaughterKey()
{
if (Input.GetKeyDown(laughterKey))
{
lipsyncContext.SetLaughterBlend(100);
}
if (Input.GetKeyUp(laughterKey))
{
lipsyncContext.SetLaughterBlend(0);
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Search.Spans
{
/*
* 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 ArrayUtil = Lucene.Net.Util.ArrayUtil;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using IBits = Lucene.Net.Util.IBits;
using InPlaceMergeSorter = Lucene.Net.Util.InPlaceMergeSorter;
using Term = Lucene.Net.Index.Term;
using TermContext = Lucene.Net.Index.TermContext;
/// <summary>
/// A <see cref="Spans"/> that is formed from the ordered subspans of a <see cref="SpanNearQuery"/>
/// where the subspans do not overlap and have a maximum slop between them.
/// <para/>
/// The formed spans only contains minimum slop matches.
/// <para/>
/// The matching slop is computed from the distance(s) between
/// the non overlapping matching <see cref="Spans"/>.
/// <para/>
/// Successive matches are always formed from the successive <see cref="Spans"/>
/// of the <see cref="SpanNearQuery"/>.
/// <para/>
/// The formed spans may contain overlaps when the slop is at least 1.
/// For example, when querying using
/// <c>t1 t2 t3</c>
/// with slop at least 1, the fragment:
/// <c>t1 t2 t1 t3 t2 t3</c>
/// matches twice:
/// <c>t1 t2 .. t3 </c>
/// <c> t1 .. t2 t3</c>
///
/// <para/>
/// Expert:
/// Only public for subclassing. Most implementations should not need this class
/// </summary>
public class NearSpansOrdered : Spans
{
private readonly int allowedSlop;
private bool firstTime = true;
private bool more = false;
/// <summary>
/// The spans in the same order as the <see cref="SpanNearQuery"/> </summary>
private readonly Spans[] subSpans;
/// <summary>
/// Indicates that all subSpans have same <see cref="Doc"/> </summary>
private bool inSameDoc = false;
private int matchDoc = -1;
private int matchStart = -1;
private int matchEnd = -1;
private List<byte[]> matchPayload;
private readonly Spans[] subSpansByDoc;
// Even though the array is probably almost sorted, InPlaceMergeSorter will likely
// perform better since it has a lower overhead than TimSorter for small arrays
private readonly InPlaceMergeSorter sorter;
private class InPlaceMergeSorterAnonymousInnerClassHelper : InPlaceMergeSorter
{
private readonly NearSpansOrdered outerInstance;
public InPlaceMergeSorterAnonymousInnerClassHelper(NearSpansOrdered outerInstance)
{
this.outerInstance = outerInstance;
}
protected override void Swap(int i, int j)
{
ArrayUtil.Swap(outerInstance.subSpansByDoc, i, j);
}
protected override int Compare(int i, int j)
{
return outerInstance.subSpansByDoc[i].Doc - outerInstance.subSpansByDoc[j].Doc;
}
}
private SpanNearQuery query;
private bool collectPayloads = true;
public NearSpansOrdered(SpanNearQuery spanNearQuery, AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts)
: this(spanNearQuery, context, acceptDocs, termContexts, true)
{
}
public NearSpansOrdered(SpanNearQuery spanNearQuery, AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts, bool collectPayloads)
{
sorter = new InPlaceMergeSorterAnonymousInnerClassHelper(this);
if (spanNearQuery.GetClauses().Length < 2)
{
throw new ArgumentException("Less than 2 clauses: " + spanNearQuery);
}
this.collectPayloads = collectPayloads;
allowedSlop = spanNearQuery.Slop;
SpanQuery[] clauses = spanNearQuery.GetClauses();
subSpans = new Spans[clauses.Length];
matchPayload = new List<byte[]>();
subSpansByDoc = new Spans[clauses.Length];
for (int i = 0; i < clauses.Length; i++)
{
subSpans[i] = clauses[i].GetSpans(context, acceptDocs, termContexts);
subSpansByDoc[i] = subSpans[i]; // used in toSameDoc()
}
query = spanNearQuery; // kept for toString() only.
}
/// <summary>
/// Returns the document number of the current match. Initially invalid. </summary>
public override int Doc => matchDoc;
/// <summary>
/// Returns the start position of the current match. Initially invalid. </summary>
public override int Start => matchStart;
/// <summary>
/// Returns the end position of the current match. Initially invalid. </summary>
public override int End => matchEnd;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public virtual Spans[] SubSpans => subSpans;
// TODO: Remove warning after API has been finalized
// TODO: Would be nice to be able to lazy load payloads
public override ICollection<byte[]> GetPayload()
{
return matchPayload;
}
// TODO: Remove warning after API has been finalized
public override bool IsPayloadAvailable => matchPayload.Count == 0 == false;
public override long GetCost()
{
long minCost = long.MaxValue;
for (int i = 0; i < subSpans.Length; i++)
{
minCost = Math.Min(minCost, subSpans[i].GetCost());
}
return minCost;
}
/// <summary>
/// Move to the next match, returning true iff any such exists. </summary>
public override bool Next()
{
if (firstTime)
{
firstTime = false;
for (int i = 0; i < subSpans.Length; i++)
{
if (!subSpans[i].Next())
{
more = false;
return false;
}
}
more = true;
}
if (collectPayloads)
{
matchPayload.Clear();
}
return AdvanceAfterOrdered();
}
/// <summary>
/// Skips to the first match beyond the current, whose document number is
/// greater than or equal to <i>target</i>.
/// <para/>The behavior of this method is <b>undefined</b> when called with
/// <c> target <= current</c>, or after the iterator has exhausted.
/// Both cases may result in unpredicted behavior.
/// <para/>Returns <c>true</c> if there is such
/// a match.
/// <para/>Behaves as if written:
/// <code>
/// bool SkipTo(int target)
/// {
/// do
/// {
/// if (!Next())
/// return false;
/// } while (target > Doc);
/// return true;
/// }
/// </code>
/// Most implementations are considerably more efficient than that.
/// </summary>
public override bool SkipTo(int target)
{
if (firstTime)
{
firstTime = false;
for (int i = 0; i < subSpans.Length; i++)
{
if (!subSpans[i].SkipTo(target))
{
more = false;
return false;
}
}
more = true;
}
else if (more && (subSpans[0].Doc < target))
{
if (subSpans[0].SkipTo(target))
{
inSameDoc = false;
}
else
{
more = false;
return false;
}
}
if (collectPayloads)
{
matchPayload.Clear();
}
return AdvanceAfterOrdered();
}
/// <summary>
/// Advances the <see cref="SubSpans"/> to just after an ordered match with a minimum slop
/// that is smaller than the slop allowed by the <see cref="SpanNearQuery"/>. </summary>
/// <returns> <c>true</c> if there is such a match. </returns>
private bool AdvanceAfterOrdered()
{
while (more && (inSameDoc || ToSameDoc()))
{
if (StretchToOrder() && ShrinkToAfterShortestMatch())
{
return true;
}
}
return false; // no more matches
}
/// <summary>
/// Advance the <see cref="SubSpans"/> to the same document </summary>
private bool ToSameDoc()
{
sorter.Sort(0, subSpansByDoc.Length);
int firstIndex = 0;
int maxDoc = subSpansByDoc[subSpansByDoc.Length - 1].Doc;
while (subSpansByDoc[firstIndex].Doc != maxDoc)
{
if (!subSpansByDoc[firstIndex].SkipTo(maxDoc))
{
more = false;
inSameDoc = false;
return false;
}
maxDoc = subSpansByDoc[firstIndex].Doc;
if (++firstIndex == subSpansByDoc.Length)
{
firstIndex = 0;
}
}
for (int i = 0; i < subSpansByDoc.Length; i++)
{
Debug.Assert((subSpansByDoc[i].Doc == maxDoc), " NearSpansOrdered.toSameDoc() spans " + subSpansByDoc[0] + "\n at doc " + subSpansByDoc[i].Doc + ", but should be at " + maxDoc);
}
inSameDoc = true;
return true;
}
/// <summary>
/// Check whether two <see cref="Spans"/> in the same document are ordered. </summary>
/// <returns> <c>true</c> if <paramref name="spans1"/> starts before <paramref name="spans2"/>
/// or the spans start at the same position,
/// and <paramref name="spans1"/> ends before <paramref name="spans2"/>. </returns>
internal static bool DocSpansOrdered(Spans spans1, Spans spans2)
{
Debug.Assert(spans1.Doc == spans2.Doc, "doc1 " + spans1.Doc + " != doc2 " + spans2.Doc);
int start1 = spans1.Start;
int start2 = spans2.Start;
/* Do not call docSpansOrdered(int,int,int,int) to avoid invoking .end() : */
return (start1 == start2) ? (spans1.End < spans2.End) : (start1 < start2);
}
/// <summary>
/// Like <see cref="DocSpansOrdered(Spans, Spans)"/>, but use the spans
/// starts and ends as parameters.
/// </summary>
private static bool DocSpansOrdered(int start1, int end1, int start2, int end2)
{
return (start1 == start2) ? (end1 < end2) : (start1 < start2);
}
/// <summary>
/// Order the <see cref="SubSpans"/> within the same document by advancing all later spans
/// after the previous one.
/// </summary>
private bool StretchToOrder()
{
matchDoc = subSpans[0].Doc;
for (int i = 1; inSameDoc && (i < subSpans.Length); i++)
{
while (!DocSpansOrdered(subSpans[i - 1], subSpans[i]))
{
if (!subSpans[i].Next())
{
inSameDoc = false;
more = false;
break;
}
else if (matchDoc != subSpans[i].Doc)
{
inSameDoc = false;
break;
}
}
}
return inSameDoc;
}
/// <summary>
/// The <see cref="SubSpans"/> are ordered in the same doc, so there is a possible match.
/// Compute the slop while making the match as short as possible by advancing
/// all <see cref="SubSpans"/> except the last one in reverse order.
/// </summary>
private bool ShrinkToAfterShortestMatch()
{
matchStart = subSpans[subSpans.Length - 1].Start;
matchEnd = subSpans[subSpans.Length - 1].End;
var possibleMatchPayloads = new JCG.HashSet<byte[]>();
if (subSpans[subSpans.Length - 1].IsPayloadAvailable)
{
possibleMatchPayloads.UnionWith(subSpans[subSpans.Length - 1].GetPayload());
}
IList<byte[]> possiblePayload = null;
int matchSlop = 0;
int lastStart = matchStart;
int lastEnd = matchEnd;
for (int i = subSpans.Length - 2; i >= 0; i--)
{
Spans prevSpans = subSpans[i];
if (collectPayloads && prevSpans.IsPayloadAvailable)
{
possiblePayload = new List<byte[]>(prevSpans.GetPayload()); // LUCENENET specific - using copy constructor instead of AddRange()
}
int prevStart = prevSpans.Start;
int prevEnd = prevSpans.End;
while (true) // Advance prevSpans until after (lastStart, lastEnd)
{
if (!prevSpans.Next())
{
inSameDoc = false;
more = false;
break; // Check remaining subSpans for final match.
}
else if (matchDoc != prevSpans.Doc)
{
inSameDoc = false; // The last subSpans is not advanced here.
break; // Check remaining subSpans for last match in this document.
}
else
{
int ppStart = prevSpans.Start;
int ppEnd = prevSpans.End; // Cannot avoid invoking .end()
if (!DocSpansOrdered(ppStart, ppEnd, lastStart, lastEnd))
{
break; // Check remaining subSpans.
} // prevSpans still before (lastStart, lastEnd)
else
{
prevStart = ppStart;
prevEnd = ppEnd;
if (collectPayloads && prevSpans.IsPayloadAvailable)
{
possiblePayload = new List<byte[]>(prevSpans.GetPayload()); // LUCENENET specific - using copy constructor instead of AddRange()
}
}
}
}
if (collectPayloads && possiblePayload != null)
{
possibleMatchPayloads.UnionWith(possiblePayload);
}
Debug.Assert(prevStart <= matchStart);
if (matchStart > prevEnd) // Only non overlapping spans add to slop.
{
matchSlop += (matchStart - prevEnd);
}
/* Do not break on (matchSlop > allowedSlop) here to make sure
* that subSpans[0] is advanced after the match, if any.
*/
matchStart = prevStart;
lastStart = prevStart;
lastEnd = prevEnd;
}
bool match = matchSlop <= allowedSlop;
if (collectPayloads && match && possibleMatchPayloads.Count > 0)
{
matchPayload.AddRange(possibleMatchPayloads);
}
return match; // ordered and allowed slop
}
public override string ToString()
{
return this.GetType().Name + "(" + query.ToString() + ")@" + (firstTime ? "START" : (more ? (Doc + ":" + Start + "-" + End) : "END"));
}
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections;
using System.Collections.Generic;
namespace Shielded
{
/// <summary>
/// A shielded red-black tree, for keeping sorted data. Each node is a
/// Shielded struct, so parallel operations are possible. Multiple items
/// may be added under the same key. 'Nc' stands for 'no count', which
/// enables it to be a bit faster.
/// </summary>
public class ShieldedTreeNc<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
private enum Color : byte
{
Red = 0,
Black
}
private struct Node
{
public Color Color;
public TKey Key;
public TValue Value;
public Shielded<Node> Left;
public Shielded<Node> Right;
public Shielded<Node> Parent;
}
private void ClearLinks(Shielded<Node> node)
{
node.Modify((ref Node n) => n.Left = n.Right = n.Parent = null);
}
private readonly Shielded<Shielded<Node>> _head;
private readonly IComparer<TKey> _comparer;
private readonly object _owner;
/// <summary>
/// Initializes a new tree, which will use a given comparer, or using the .NET default
/// comparer if none is specified.
/// </summary>
public ShieldedTreeNc(IComparer<TKey> comparer = null, object owner = null)
{
_owner = owner ?? this;
_head = new Shielded<Shielded<Node>>(this);
_comparer = comparer != null ? comparer : Comparer<TKey>.Default;
}
private Shielded<Node> FindInternal(TKey key)
{
return Shield.InTransaction(() => {
var curr = _head.Value;
int comparison;
while (curr != null &&
(comparison = _comparer.Compare(curr.Value.Key, key)) != 0)
{
if (comparison > 0)
curr = curr.Value.Left;
else
curr = curr.Value.Right;
}
return curr;
});
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<KeyValuePair<TKey, TValue>>)this).GetEnumerator();
}
/// <summary>
/// Gets an enumerator for all the key-value pairs in the tree.
/// </summary>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
Shield.AssertInTransaction();
Stack<Shielded<Node>> centerStack = new Stack<Shielded<Node>>();
var curr = _head.Value;
while (curr != null)
{
while (curr.Value.Left != null)
{
centerStack.Push(curr);
curr = curr.Value.Left;
}
yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value);
while (curr.Value.Right == null && centerStack.Count > 0)
{
curr = centerStack.Pop();
yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value);
}
curr = curr.Value.Right;
}
}
/// <summary>
/// Gets an enuerable which enumerates the tree in descending key order. (Does not
/// involve any copying, just as efficient as <see cref="GetEnumerator"/>.)
/// </summary>
public IEnumerable<KeyValuePair<TKey, TValue>> Descending
{
get
{
Shield.AssertInTransaction();
Stack<Shielded<Node>> centerStack = new Stack<Shielded<Node>>();
var curr = _head.Value;
while (curr != null)
{
while (curr.Value.Right != null)
{
centerStack.Push(curr);
curr = curr.Value.Right;
}
yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value);
while (curr.Value.Left == null && centerStack.Count > 0)
{
curr = centerStack.Pop();
yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value);
}
curr = curr.Value.Left;
}
}
}
/// <summary>
/// Enumerate all key-value pairs, whose keys are in the given range. The range
/// is inclusive, both from and to are included in the result (if the tree contains
/// those keys). The items are returned sorted. If from is greater than to, the
/// enumerable will not return anything. For backwards enumeration you must explicitly
/// use <see cref="RangeDescending"/>.
/// </summary>
public IEnumerable<KeyValuePair<TKey, TValue>> Range(TKey from, TKey to)
{
foreach (var n in RangeInternal(from, to))
yield return new KeyValuePair<TKey, TValue>(n.Value.Key, n.Value.Value);
}
/// <summary>
/// Enumerates only over the nodes in the range. Borders included.
/// </summary>
private IEnumerable<Shielded<Node>> RangeInternal(TKey from, TKey to)
{
if (_comparer.Compare(from, to) > 0)
yield break;
Shield.AssertInTransaction();
Stack<Shielded<Node>> centerStack = new Stack<Shielded<Node>>();
var curr = _head.Value;
while (curr != null)
{
while (curr.Value.Left != null &&
_comparer.Compare(curr.Value.Key, from) >= 0)
{
centerStack.Push(curr);
curr = curr.Value.Left;
}
if (_comparer.Compare(curr.Value.Key, to) > 0)
yield break;
if (_comparer.Compare(curr.Value.Key, from) >= 0)
yield return curr;
while (curr.Value.Right == null &&
centerStack.Count > 0)
{
curr = centerStack.Pop();
if (_comparer.Compare(curr.Value.Key, to) <= 0)
yield return curr;
else
yield break;
}
curr = curr.Value.Right;
}
}
/// <summary>
/// Enumerate all key-value pairs, whose keys are in the given range, but in descending
/// key order. The range is inclusive, both from and to are included in the result (if
/// the tree contains those keys). If from is smaller than to, the enumerable will not
/// return anything. For forward enumeration you must explicitly use <see cref="Range"/>.
/// </summary>
public IEnumerable<KeyValuePair<TKey, TValue>> RangeDescending(TKey from, TKey to)
{
if (_comparer.Compare(from, to) < 0)
yield break;
Shield.AssertInTransaction();
Stack<Shielded<Node>> centerStack = new Stack<Shielded<Node>>();
var curr = _head.Value;
while (curr != null)
{
while (curr.Value.Right != null &&
_comparer.Compare(curr.Value.Key, from) <= 0)
{
centerStack.Push(curr);
curr = curr.Value.Right;
}
if (_comparer.Compare(curr.Value.Key, to) < 0)
yield break;
if (_comparer.Compare(curr.Value.Key, from) <= 0)
yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value);
while (curr.Value.Left == null &&
centerStack.Count > 0)
{
curr = centerStack.Pop();
if (_comparer.Compare(curr.Value.Key, to) >= 0)
yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value);
else
yield break;
}
curr = curr.Value.Left;
}
}
private void InsertInternal(TKey key, TValue item)
{
Shield.AssertInTransaction();
Shielded<Node> parent = null;
var targetLoc = _head.Value;
int comparison = 0;
while (targetLoc != null)
{
parent = targetLoc;
if ((comparison = _comparer.Compare(targetLoc.Value.Key, key)) > 0)
targetLoc = targetLoc.Value.Left;
else
targetLoc = targetLoc.Value.Right;
}
var shN = new Shielded<Node>(new Node()
{
//Color = Color.Red, // the default anyway.
Parent = parent,
Key = key,
Value = item
}, _owner);
if (parent != null)
{
if (comparison > 0)
parent.Modify((ref Node p) => p.Left = shN);
else
parent.Modify((ref Node p) => p.Right = shN);
}
else
_head.Value = shN;
InsertProcedure(shN);
OnInsert();
}
/// <summary>
/// Called after inserting a new node.
/// </summary>
protected virtual void OnInsert() { }
#region Wikipedia, insertion
private Shielded<Node> Grandparent(Shielded<Node> n)
{
if (n != null && n.Value.Parent != null)
return n.Value.Parent.Value.Parent;
else
return null;
}
private Shielded<Node> Uncle(Shielded<Node> n)
{
Shielded<Node> g = Grandparent(n);
if (g == null)
return null;
if (n.Value.Parent == g.Value.Left)
return g.Value.Right;
else
return g.Value.Left;
}
private void RotateLeft(Shielded<Node> p)
{
Shielded<Node> right = null;
Shielded<Node> parent = null;
p.Modify((ref Node pInner) =>
{
right = pInner.Right;
parent = pInner.Parent;
pInner.Right = right.Value.Left;
pInner.Parent = right;
});
right.Modify((ref Node r) =>
{
if (r.Left != null)
r.Left.Modify((ref Node n) => n.Parent = p);
r.Left = p;
r.Parent = parent;
});
if (parent != null)
parent.Modify((ref Node n) =>
{
if (n.Left == p)
n.Left = right;
else
n.Right = right;
});
else
_head.Value = right;
}
private void RotateRight(Shielded<Node> p)
{
Shielded<Node> left = null;
Shielded<Node> parent = null;
p.Modify((ref Node pInner) =>
{
left = pInner.Left;
parent = pInner.Parent;
pInner.Left = left.Value.Right;
pInner.Parent = left;
});
left.Modify((ref Node l) =>
{
if (l.Right != null)
l.Right.Modify((ref Node n) => n.Parent = p);
l.Right = p;
l.Parent = parent;
});
if (parent != null)
parent.Modify((ref Node n) =>
{
if (n.Left == p)
n.Left = left;
else
n.Right = left;
});
else
_head.Value = left;
}
private void InsertProcedure(Shielded<Node> n)
{
while (true)
{
if (n.Value.Parent == null)
n.Modify((ref Node nInn) => nInn.Color = Color.Black);
else if (n.Value.Parent.Value.Color == Color.Black)
return;
else
{
Shielded<Node> u = Uncle(n);
Shielded<Node> g = Grandparent(n);
if (u != null && u.Value.Color == Color.Red)
{
n.Value.Parent.Modify((ref Node p) => p.Color = Color.Black);
u.Modify((ref Node uInn) => uInn.Color = Color.Black);
g.Modify((ref Node gInn) => gInn.Color = Color.Red);
n = g;
continue;
}
else
{
if (n == n.Value.Parent.Value.Right && n.Value.Parent == g.Value.Left)
{
RotateLeft(n.Value.Parent);
n = n.Value.Left;
}
else if (n == n.Value.Parent.Value.Left && n.Value.Parent == g.Value.Right)
{
RotateRight(n.Value.Parent);
n = n.Value.Right;
}
n.Value.Parent.Modify((ref Node p) => p.Color = Color.Black);
g.Modify((ref Node gInn) => gInn.Color = Color.Red);
if (n == n.Value.Parent.Value.Left)
RotateRight(g);
else
RotateLeft(g);
}
}
break;
}
}
#endregion
/// <summary>
/// Removes an item and returns it. Useful if you could have multiple items under the same key.
/// </summary>
public bool RemoveAndReturn(TKey key, out TValue val)
{
var node = RangeInternal(key, key).FirstOrDefault();
if (node != null)
{
val = node.Value.Value;
RemoveInternal(node);
return true;
}
else
{
val = default(TValue);
return false;
}
}
private void RemoveInternal(Shielded<Node> node)
{
Shield.AssertInTransaction();
// find the first follower in the right subtree (arbitrary choice..)
Shielded<Node> follower;
if (node.Value.Right == null)
follower = node;
else
{
follower = node.Value.Right;
while (follower.Value.Left != null)
follower = follower.Value.Left;
// loosing the node value right now!
node.Modify((ref Node n) =>
{
var f = follower.Value;
n.Key = f.Key;
n.Value = f.Value;
});
}
DeleteOneChild(follower);
OnRemove();
}
/// <summary>
/// Called after a node is removed from the tree.
/// </summary>
protected virtual void OnRemove() { }
#region Wikipedia, removal
Shielded<Node> Sibling(Shielded<Node> n)
{
var parent = n.Value.Parent.Value;
if (n == parent.Left)
return parent.Right;
else
return parent.Left;
}
void ReplaceNode(Shielded<Node> target, Shielded<Node> source)
{
var targetParent = target.Value.Parent;
if (source != null)
source.Modify((ref Node s) => s.Parent = targetParent);
if (targetParent == null)
_head.Value = source;
else
targetParent.Modify((ref Node p) =>
{
if (p.Left == target)
p.Left = source;
else
p.Right = source;
});
ClearLinks(target);
}
void DeleteOneChild(Shielded<Node> node)
{
// node has at most one child!
Shielded<Node> child = node.Value.Right == null ? node.Value.Left : node.Value.Right;
bool deleted = false;
if (child != null)
{
ReplaceNode(node, child);
deleted = true;
}
if (node.Value.Color == Color.Black)
{
if (child != null && child.Value.Color == Color.Red)
child.Modify((ref Node c) => c.Color = Color.Black);
else
{
// since we don't represent null leaves as nodes, we must start
// the process with the not yet removed parent in this case.
if (!deleted)
child = node;
while (true)
{
// delete case 1
if (child.Value.Parent != null)
{
// delete case 2
Shielded<Node> s = Sibling(child);
if (s.Value.Color == Color.Red)
{
child.Value.Parent.Modify((ref Node p) => p.Color = Color.Red);
s.Modify((ref Node sInn) => sInn.Color = Color.Black);
if (child == child.Value.Parent.Value.Left)
RotateLeft(child.Value.Parent);
else
RotateRight(child.Value.Parent);
s = Sibling(child);
}
// delete case 3
if ((child.Value.Parent.Value.Color == Color.Black) &&
(s.Value.Color == Color.Black) &&
(s.Value.Left == null || s.Value.Left.Value.Color == Color.Black) &&
(s.Value.Right == null || s.Value.Right.Value.Color == Color.Black))
{
s.Modify((ref Node sInn) => sInn.Color = Color.Red);
child = child.Value.Parent;
continue; // back to 1
}
else
{
// delete case 4
if ((child.Value.Parent.Value.Color == Color.Red) &&
(s.Value.Color == Color.Black) &&
(s.Value.Left == null || s.Value.Left.Value.Color == Color.Black) &&
(s.Value.Right == null || s.Value.Right.Value.Color == Color.Black))
{
s.Modify((ref Node sInn) => sInn.Color = Color.Red);
child.Value.Parent.Modify((ref Node p) => p.Color = Color.Black);
}
else
{
// delete case 5
if (s.Value.Color == Color.Black)
{
if ((child == child.Value.Parent.Value.Left) &&
(s.Value.Right == null || s.Value.Right.Value.Color == Color.Black) &&
(s.Value.Left != null && s.Value.Left.Value.Color == Color.Red))
{
s.Modify((ref Node sInn) =>
{
sInn.Color = Color.Red;
sInn.Left.Modify((ref Node l) => l.Color = Color.Black);
});
RotateRight(s);
s = Sibling(child);
}
else if ((child == child.Value.Parent.Value.Right) &&
(s.Value.Left == null || s.Value.Left.Value.Color == Color.Black) &&
(s.Value.Right != null && s.Value.Right.Value.Color == Color.Red))
{
s.Modify((ref Node sInn) =>
{
sInn.Color = Color.Red;
sInn.Right.Modify((ref Node r) => r.Color = Color.Black);
});
RotateLeft(s);
s = Sibling(child);
}
}
// delete case 6
child.Value.Parent.Modify((ref Node p) =>
{
var c = p.Color;
s.Modify((ref Node sInn) => sInn.Color = c);
p.Color = Color.Black;
});
if (child == child.Value.Parent.Value.Left)
{
s.Value.Right.Modify((ref Node r) => r.Color = Color.Black);
RotateLeft(child.Value.Parent);
}
else
{
s.Value.Left.Modify((ref Node l) => l.Color = Color.Black);
RotateRight(child.Value.Parent);
}
}
}
}
break;
}
}
}
if (!deleted)
{
// original node is still in the tree, and it still has no children.
if (node.Value.Parent != null)
node.Value.Parent.Modify((ref Node p) => {
if (p.Left == node)
p.Left = null;
else
p.Right = null;
});
else
_head.Value = null;
ClearLinks(node);
}
}
#endregion
/// <summary>
/// Clear this instance. Efficient, O(1).
/// </summary>
public virtual void Clear()
{
// ridiculously simple :)
_head.Value = null;
}
/// <summary>
/// Checks both the key and value, which may be useful due to the tree supporting multiple
/// entries with the same key.
/// </summary>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
var valueComp = EqualityComparer<TValue>.Default;
return Shield.InTransaction(() =>
RangeInternal(item.Key, item.Key).Any(n =>
valueComp.Equals(n.Value.Value, item.Value)));
}
/// <summary>
/// Copy the tree contents into an array.
/// </summary>
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Shield.InTransaction(() => {
foreach (var kvp in this)
array[arrayIndex++] = kvp;
});
}
/// <summary>
/// Remove the given key-value pair from the tree. Checks both the key and
/// value, which may be useful due to the tree supporting multiple entries
/// with the same key.
/// </summary>
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return Remove(item.Key, item.Value);
}
/// <summary>
/// Remove the given key-value pair from the tree. Checks both the key and
/// value, which may be useful due to the tree supporting multiple entries
/// with the same key.
/// </summary>
public bool Remove(TKey key, TValue value)
{
var target = RangeInternal(key, key).FirstOrDefault(n =>
EqualityComparer<TValue>.Default.Equals(n.Value.Value, value));
if (target == null)
return false;
RemoveInternal(target);
return true;
}
/// <summary>
/// Add the given key and value to the tree. Same key can be added multiple times
/// into the tree!
/// </summary>
public void Add(TKey key, TValue value)
{
InsertInternal(key, value);
}
/// <summary>
/// Check if the key is present in the tree.
/// </summary>
public bool ContainsKey(TKey key)
{
return FindInternal(key) != null;
}
/// <summary>
/// Remove an item with the specified key. If you want to know what got removed, use
/// RemoveAndReturn.
/// </summary>
public bool Remove(TKey key)
{
TValue val;
return RemoveAndReturn(key, out val);
}
/// <summary>
/// Try to get any one of the values stored under the given key. There may be multiple items
/// under the same key!
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
bool res = false;
value = Shield.InTransaction(() => {
var n = FindInternal(key);
res = n != null;
return res ? n.Value.Value : default(TValue);
});
return res;
}
/// <summary>
/// Gets or sets the item with the specified key.
/// If there are many with the same key, acts on the first one it finds!
/// </summary>
public TValue this[TKey key]
{
get
{
return Shield.InTransaction(() => {
var n = FindInternal(key);
if (n == null)
throw new KeyNotFoundException();
return n.Value.Value;
});
}
set
{
Shield.AssertInTransaction();
// replaces the first occurrence...
var n = FindInternal(key);
if (n == null)
Add(key, value);
else
n.Modify((ref Node nInner) => nInner.Value = value);
}
}
/// <summary>
/// Get a collection of the keys in the tree. Works out of transaction.
/// The result is a copy, it does not get updated with later changes.
/// Count will be equal to the tree count, i.e. if there are multiple
/// entries with the same key, that key will be in this collection
/// multiple times.
/// </summary>
public ICollection<TKey> Keys
{
get
{
return Shield.InTransaction(
() => ((IEnumerable<KeyValuePair<TKey, TValue>>)this)
.Select(kvp => kvp.Key)
.ToList());
}
}
/// <summary>
/// Get a collection of the values in the tree. Works out of transaction.
/// The result is a copy, it does not get updated with later changes.
/// </summary>
public ICollection<TValue> Values
{
get
{
return Shield.InTransaction(
() => ((IEnumerable<KeyValuePair<TKey, TValue>>)this)
.Select(kvp => kvp.Value)
.ToList());
}
}
/// <summary>
/// Returns true if tree is empty. More efficient than any enumerator if not.
/// </summary>
public bool IsEmpty
{
get
{
return _head.Value == null;
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type PlannerPlanDetailsRequest.
/// </summary>
public partial class PlannerPlanDetailsRequest : BaseRequest, IPlannerPlanDetailsRequest
{
/// <summary>
/// Constructs a new PlannerPlanDetailsRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public PlannerPlanDetailsRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified PlannerPlanDetails using POST.
/// </summary>
/// <param name="plannerPlanDetailsToCreate">The PlannerPlanDetails to create.</param>
/// <returns>The created PlannerPlanDetails.</returns>
public System.Threading.Tasks.Task<PlannerPlanDetails> CreateAsync(PlannerPlanDetails plannerPlanDetailsToCreate)
{
return this.CreateAsync(plannerPlanDetailsToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified PlannerPlanDetails using POST.
/// </summary>
/// <param name="plannerPlanDetailsToCreate">The PlannerPlanDetails to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created PlannerPlanDetails.</returns>
public async System.Threading.Tasks.Task<PlannerPlanDetails> CreateAsync(PlannerPlanDetails plannerPlanDetailsToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<PlannerPlanDetails>(plannerPlanDetailsToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified PlannerPlanDetails.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified PlannerPlanDetails.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<PlannerPlanDetails>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified PlannerPlanDetails.
/// </summary>
/// <returns>The PlannerPlanDetails.</returns>
public System.Threading.Tasks.Task<PlannerPlanDetails> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified PlannerPlanDetails.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The PlannerPlanDetails.</returns>
public async System.Threading.Tasks.Task<PlannerPlanDetails> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<PlannerPlanDetails>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified PlannerPlanDetails using PATCH.
/// </summary>
/// <param name="plannerPlanDetailsToUpdate">The PlannerPlanDetails to update.</param>
/// <returns>The updated PlannerPlanDetails.</returns>
public System.Threading.Tasks.Task<PlannerPlanDetails> UpdateAsync(PlannerPlanDetails plannerPlanDetailsToUpdate)
{
return this.UpdateAsync(plannerPlanDetailsToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified PlannerPlanDetails using PATCH.
/// </summary>
/// <param name="plannerPlanDetailsToUpdate">The PlannerPlanDetails to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated PlannerPlanDetails.</returns>
public async System.Threading.Tasks.Task<PlannerPlanDetails> UpdateAsync(PlannerPlanDetails plannerPlanDetailsToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<PlannerPlanDetails>(plannerPlanDetailsToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanDetailsRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanDetailsRequest Expand(Expression<Func<PlannerPlanDetails, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanDetailsRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IPlannerPlanDetailsRequest Select(Expression<Func<PlannerPlanDetails, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="plannerPlanDetailsToInitialize">The <see cref="PlannerPlanDetails"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(PlannerPlanDetails plannerPlanDetailsToInitialize)
{
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Text;
using System.Threading;
using KERB_LOGON_SUBMIT_TYPE = Interop.SspiCli.KERB_LOGON_SUBMIT_TYPE;
using KERB_S4U_LOGON = Interop.SspiCli.KERB_S4U_LOGON;
using KerbS4uLogonFlags = Interop.SspiCli.KerbS4uLogonFlags;
using LUID = Interop.LUID;
using LSA_STRING = Interop.SspiCli.LSA_STRING;
using QUOTA_LIMITS = Interop.SspiCli.QUOTA_LIMITS;
using SECURITY_LOGON_TYPE = Interop.SspiCli.SECURITY_LOGON_TYPE;
using TOKEN_SOURCE = Interop.SspiCli.TOKEN_SOURCE;
namespace System.Security.Principal
{
public class WindowsIdentity : ClaimsIdentity, IDisposable
{
private string _name = null;
private SecurityIdentifier _owner = null;
private SecurityIdentifier _user = null;
private IdentityReferenceCollection _groups = null;
private SafeAccessTokenHandle _safeTokenHandle = SafeAccessTokenHandle.InvalidHandle;
private string _authType = null;
private int _isAuthenticated = -1;
private volatile TokenImpersonationLevel _impersonationLevel;
private volatile bool _impersonationLevelInitialized;
public new const string DefaultIssuer = @"AD AUTHORITY";
private string _issuerName = DefaultIssuer;
private object _claimsIntiailizedLock = new object();
private volatile bool _claimsInitialized;
private List<Claim> _deviceClaims;
private List<Claim> _userClaims;
//
// Constructors.
//
private WindowsIdentity()
: base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid)
{ }
/// <summary>
/// Initializes a new instance of the WindowsIdentity class for the user represented by the specified User Principal Name (UPN).
/// </summary>
/// <remarks>
/// Unlike the desktop version, we connect to Lsa only as an untrusted caller. We do not attempt to explot Tcb privilege or adjust the current
/// thread privilege to include Tcb.
/// </remarks>
public WindowsIdentity(string sUserPrincipalName)
: base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid)
{
// Desktop compat: See comments below for why we don't validate sUserPrincipalName.
using (SafeLsaHandle lsaHandle = ConnectToLsa())
{
int packageId = LookupAuthenticationPackage(lsaHandle, Interop.SspiCli.AuthenticationPackageNames.MICROSOFT_KERBEROS_NAME_A);
// 8 byte or less name that indicates the source of the access token. This choice of name is visible to callers through the native GetTokenInformation() api
// so we'll use the same name the CLR used even though we're not actually the "CLR."
byte[] sourceName = { (byte)'C', (byte)'L', (byte)'R', (byte)0 };
TOKEN_SOURCE sourceContext;
if (!Interop.SecurityBase.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier))
throw new SecurityException(Interop.mincore.GetMessage(Marshal.GetLastWin32Error()));
sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH];
Array.Copy(sourceName, sourceContext.SourceName, sourceName.Length);
// Desktop compat: Desktop never null-checks sUserPrincipalName. Actual behavior is that the null makes it down to Encoding.Unicode.GetBytes() which then throws
// the ArgumentNullException (provided that the prior LSA calls didn't fail first.) To make this compat decision explicit, we'll null check ourselves
// and simulate the exception from Encoding.Unicode.GetBytes().
if (sUserPrincipalName == null)
throw new ArgumentNullException("s");
byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName);
if (upnBytes.Length > ushort.MaxValue)
{
// Desktop compat: LSA only allocates 16 bits to hold the UPN size. We should throw an exception here but unfortunately, the desktop did an unchecked cast to ushort,
// effectively truncating upnBytes to the first (N % 64K) bytes. We'll simulate the same behavior here (albeit in a way that makes it look less accidental.)
Array.Resize(ref upnBytes, upnBytes.Length & ushort.MaxValue);
}
unsafe
{
//
// Build the KERB_S4U_LOGON structure. Note that the LSA expects this entire
// structure to be contained within the same block of memory, so we need to allocate
// enough room for both the structure itself and the UPN string in a single buffer
// and do the marshalling into this buffer by hand.
//
int authenticationInfoLength = checked(sizeof(KERB_S4U_LOGON) + upnBytes.Length);
using (SafeLocalAllocHandle authenticationInfo = Interop.mincore_obsolete.LocalAlloc(0, new UIntPtr(checked((uint)authenticationInfoLength))))
{
if (authenticationInfo.IsInvalid || authenticationInfo == null)
throw new OutOfMemoryException();
KERB_S4U_LOGON* pKerbS4uLogin = (KERB_S4U_LOGON*)(authenticationInfo.DangerousGetHandle());
pKerbS4uLogin->MessageType = KERB_LOGON_SUBMIT_TYPE.KerbS4ULogon;
pKerbS4uLogin->Flags = KerbS4uLogonFlags.None;
pKerbS4uLogin->ClientUpn.Length = pKerbS4uLogin->ClientUpn.MaximumLength = checked((ushort)upnBytes.Length);
IntPtr pUpnOffset = (IntPtr)(pKerbS4uLogin + 1);
pKerbS4uLogin->ClientUpn.Buffer = pUpnOffset;
Marshal.Copy(upnBytes, 0, pKerbS4uLogin->ClientUpn.Buffer, upnBytes.Length);
pKerbS4uLogin->ClientRealm.Length = pKerbS4uLogin->ClientRealm.MaximumLength = 0;
pKerbS4uLogin->ClientRealm.Buffer = IntPtr.Zero;
ushort sourceNameLength = checked((ushort)(sourceName.Length));
using (SafeLocalAllocHandle sourceNameBuffer = Interop.mincore_obsolete.LocalAlloc(0, new UIntPtr(sourceNameLength)))
{
if (sourceNameBuffer.IsInvalid || sourceNameBuffer == null)
throw new OutOfMemoryException();
Marshal.Copy(sourceName, 0, sourceNameBuffer.DangerousGetHandle(), sourceName.Length);
LSA_STRING lsaOriginName = new LSA_STRING(sourceNameBuffer.DangerousGetHandle(), sourceNameLength);
SafeLsaReturnBufferHandle profileBuffer;
int profileBufferLength;
LUID logonId;
SafeAccessTokenHandle accessTokenHandle;
QUOTA_LIMITS quota;
int subStatus;
int ntStatus = Interop.SspiCli.LsaLogonUser(
lsaHandle,
ref lsaOriginName,
SECURITY_LOGON_TYPE.Network,
packageId,
authenticationInfo.DangerousGetHandle(),
authenticationInfoLength,
IntPtr.Zero,
ref sourceContext,
out profileBuffer,
out profileBufferLength,
out logonId,
out accessTokenHandle,
out quota,
out subStatus);
if (ntStatus == unchecked((int)Interop.StatusOptions.STATUS_ACCOUNT_RESTRICTION) && subStatus < 0)
ntStatus = subStatus;
if (ntStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(ntStatus);
if (subStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(subStatus);
if (profileBuffer != null)
profileBuffer.Dispose();
_safeTokenHandle = accessTokenHandle;
}
}
}
}
}
private static SafeLsaHandle ConnectToLsa()
{
SafeLsaHandle lsaHandle;
int ntStatus = Interop.SspiCli.LsaConnectUntrusted(out lsaHandle);
if (ntStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(ntStatus);
return lsaHandle;
}
private static int LookupAuthenticationPackage(SafeLsaHandle lsaHandle, string packageName)
{
unsafe
{
int packageId;
byte[] asciiPackageName = Encoding.ASCII.GetBytes(packageName);
fixed (byte* pAsciiPackageName = asciiPackageName)
{
LSA_STRING lsaPackageName = new LSA_STRING((IntPtr)pAsciiPackageName, checked((ushort)(asciiPackageName.Length)));
int ntStatus = Interop.SspiCli.LsaLookupAuthenticationPackage(lsaHandle, ref lsaPackageName, out packageId);
if (ntStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(ntStatus);
}
return packageId;
}
}
public WindowsIdentity(IntPtr userToken) : this(userToken, null, -1) { }
public WindowsIdentity(IntPtr userToken, string type) : this(userToken, type, -1) { }
private WindowsIdentity(IntPtr userToken, string authType, int isAuthenticated)
: base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid)
{
CreateFromToken(userToken);
_authType = authType;
_isAuthenticated = isAuthenticated;
}
private void CreateFromToken(IntPtr userToken)
{
if (userToken == IntPtr.Zero)
throw new ArgumentException(SR.Argument_TokenZero);
Contract.EndContractBlock();
// Find out if the specified token is a valid.
uint dwLength = (uint)Marshal.SizeOf<uint>();
bool result = Interop.mincore.GetTokenInformation(userToken, (uint)TokenInformationClass.TokenType,
SafeLocalAllocHandle.InvalidHandle, 0, out dwLength);
if (Marshal.GetLastWin32Error() == Interop.mincore.Errors.ERROR_INVALID_HANDLE)
throw new ArgumentException(SR.Argument_InvalidImpersonationToken);
if (!Interop.mincore.DuplicateHandle(Interop.mincore.GetCurrentProcess(),
userToken,
Interop.mincore.GetCurrentProcess(),
ref _safeTokenHandle,
0,
true,
Interop.DuplicateHandleOptions.DUPLICATE_SAME_ACCESS))
throw new SecurityException(Interop.mincore.GetMessage(Marshal.GetLastWin32Error()));
}
//
// Factory methods.
//
public static WindowsIdentity GetCurrent()
{
return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, false);
}
public static WindowsIdentity GetCurrent(bool ifImpersonating)
{
return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, ifImpersonating);
}
public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess)
{
return GetCurrentInternal(desiredAccess, false);
}
// GetAnonymous() is used heavily in ASP.NET requests as a dummy identity to indicate
// the request is anonymous. It does not represent a real process or thread token so
// it cannot impersonate or do anything useful. Note this identity does not represent the
// usual concept of an anonymous token, and the name is simply misleading but we cannot change it now.
public static WindowsIdentity GetAnonymous()
{
return new WindowsIdentity();
}
//
// Properties.
//
// this is defined 'override sealed' for back compat. Il generated is 'virtual final' and this needs to be the same.
public override sealed string AuthenticationType
{
get
{
// If this is an anonymous identity, return an empty string
if (_safeTokenHandle.IsInvalid)
return String.Empty;
if (_authType == null)
{
Interop.LUID authId = GetLogonAuthId(_safeTokenHandle);
if (authId.LowPart == Interop.LuidOptions.ANONYMOUS_LOGON_LUID)
return String.Empty; // no authentication, just return an empty string
SafeLsaReturnBufferHandle pLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle;
try
{
int status = Interop.mincore.LsaGetLogonSessionData(ref authId, ref pLogonSessionData);
if (status < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(status);
pLogonSessionData.Initialize((uint)Marshal.SizeOf<Interop.SECURITY_LOGON_SESSION_DATA>());
Interop.SECURITY_LOGON_SESSION_DATA logonSessionData = pLogonSessionData.Read<Interop.SECURITY_LOGON_SESSION_DATA>(0);
return Marshal.PtrToStringUni(logonSessionData.AuthenticationPackage.Buffer);
}
finally
{
if (!pLogonSessionData.IsInvalid)
pLogonSessionData.Dispose();
}
}
return _authType;
}
}
public TokenImpersonationLevel ImpersonationLevel
{
get
{
// In case of a race condition here here, both threads will set m_impersonationLevel to the same value,
// which is ok.
if (!_impersonationLevelInitialized)
{
TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None;
// If this is an anonymous identity
if (_safeTokenHandle.IsInvalid)
{
impersonationLevel = TokenImpersonationLevel.Anonymous;
}
else
{
TokenType tokenType = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType);
if (tokenType == TokenType.TokenPrimary)
{
impersonationLevel = TokenImpersonationLevel.None; // primary token;
}
else
{
/// This is an impersonation token, get the impersonation level
int level = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel);
impersonationLevel = (TokenImpersonationLevel)level + 1;
}
}
_impersonationLevel = impersonationLevel;
_impersonationLevelInitialized = true;
}
return _impersonationLevel;
}
}
public override bool IsAuthenticated
{
get
{
if (_isAuthenticated == -1)
{
// This approach will not work correctly for domain guests (will return false
// instead of true). This is a corner-case that is not very interesting.
_isAuthenticated = CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID })) ? 1 : 0;
}
return _isAuthenticated == 1;
}
}
private bool CheckNtTokenForSid(SecurityIdentifier sid)
{
Contract.EndContractBlock();
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return false;
// CheckTokenMembership expects an impersonation token
SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle;
TokenImpersonationLevel til = ImpersonationLevel;
bool isMember = false;
try
{
if (til == TokenImpersonationLevel.None)
{
if (!Interop.mincore.DuplicateTokenEx(_safeTokenHandle,
(uint)TokenAccessLevels.Query,
IntPtr.Zero,
(uint)TokenImpersonationLevel.Identification,
(uint)TokenType.TokenImpersonation,
ref token))
throw new SecurityException(Interop.mincore.GetMessage(Marshal.GetLastWin32Error()));
}
// CheckTokenMembership will check if the SID is both present and enabled in the access token.
if (!Interop.mincore.CheckTokenMembership((til != TokenImpersonationLevel.None ? _safeTokenHandle : token),
sid.BinaryForm,
ref isMember))
throw new SecurityException(Interop.mincore.GetMessage(Marshal.GetLastWin32Error()));
}
finally
{
if (token != SafeAccessTokenHandle.InvalidHandle)
{
token.Dispose();
}
}
return isMember;
}
//
// IsGuest, IsSystem and IsAnonymous are maintained for compatibility reasons. It is always
// possible to extract this same information from the User SID property and the new
// (and more general) methods defined in the SID class (IsWellKnown, etc...).
//
public virtual bool IsGuest
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return false;
return CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest }));
}
}
public virtual bool IsSystem
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return false;
SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID });
return (this.User == sid);
}
}
public virtual bool IsAnonymous
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return true;
SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID });
return (this.User == sid);
}
}
public override string Name
{
get
{
return GetName();
}
}
internal String GetName()
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return String.Empty;
if (_name == null)
{
// revert thread impersonation for the duration of the call to get the name.
RunImpersonated(SafeAccessTokenHandle.InvalidHandle, delegate
{
NTAccount ntAccount = this.User.Translate(typeof(NTAccount)) as NTAccount;
_name = ntAccount.ToString();
});
}
return _name;
}
public SecurityIdentifier Owner
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return null;
if (_owner == null)
{
using (SafeLocalAllocHandle tokenOwner = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenOwner))
{
_owner = new SecurityIdentifier(tokenOwner.Read<IntPtr>(0), true);
}
}
return _owner;
}
}
public SecurityIdentifier User
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return null;
if (_user == null)
{
using (SafeLocalAllocHandle tokenUser = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser))
{
_user = new SecurityIdentifier(tokenUser.Read<IntPtr>(0), true);
}
}
return _user;
}
}
public IdentityReferenceCollection Groups
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return null;
if (_groups == null)
{
IdentityReferenceCollection groups = new IdentityReferenceCollection();
using (SafeLocalAllocHandle pGroups = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups))
{
uint groupCount = pGroups.Read<uint>(0);
Interop.TOKEN_GROUPS tokenGroups = pGroups.Read<Interop.TOKEN_GROUPS>(0);
Interop.SID_AND_ATTRIBUTES[] groupDetails = new Interop.SID_AND_ATTRIBUTES[tokenGroups.GroupCount];
pGroups.ReadArray((uint)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups").ToInt32(),
groupDetails,
0,
groupDetails.Length);
foreach (Interop.SID_AND_ATTRIBUTES group in groupDetails)
{
// Ignore disabled, logon ID, and deny-only groups.
uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED)
{
groups.Add(new SecurityIdentifier(group.Sid, true));
}
}
}
Interlocked.CompareExchange(ref _groups, groups, null);
}
return _groups;
}
}
public SafeAccessTokenHandle AccessToken
{
get
{
return _safeTokenHandle;
}
}
//
// Public methods.
//
public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
{
if (action == null)
throw new ArgumentNullException("action");
RunImpersonatedInternal(safeAccessTokenHandle, action);
}
public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func)
{
if (func == null)
throw new ArgumentNullException("func");
T result = default(T);
RunImpersonatedInternal(safeAccessTokenHandle, () => result = func());
return result;
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_safeTokenHandle != null && !_safeTokenHandle.IsClosed)
_safeTokenHandle.Dispose();
}
_name = null;
_owner = null;
_user = null;
}
public void Dispose()
{
Dispose(true);
}
//
// internal.
//
private static AsyncLocal<SafeAccessTokenHandle> s_currentImpersonatedToken = new AsyncLocal<SafeAccessTokenHandle>(CurrentImpersonatedTokenChanged);
private static void RunImpersonatedInternal(SafeAccessTokenHandle token, Action action)
{
bool isImpersonating;
int hr;
SafeAccessTokenHandle previousToken = GetCurrentToken(TokenAccessLevels.MaximumAllowed, false, out isImpersonating, out hr);
if (previousToken == null || previousToken.IsInvalid)
throw new SecurityException(Interop.mincore.GetMessage(hr));
s_currentImpersonatedToken.Value = isImpersonating ? previousToken : null;
ExecutionContext currentContext = ExecutionContext.Capture();
// Run everything else inside of ExecutionContext.Run, so that any EC changes will be undone
// on the way out.
ExecutionContext.Run(
currentContext,
delegate
{
if (!Interop.mincore.RevertToSelf())
Environment.FailFast(Interop.mincore.GetMessage(Marshal.GetLastWin32Error()));
s_currentImpersonatedToken.Value = null;
if (!token.IsInvalid && !Interop.mincore.ImpersonateLoggedOnUser(token))
throw new SecurityException(SR.Argument_ImpersonateUser);
s_currentImpersonatedToken.Value = token;
action();
},
null);
}
private static void CurrentImpersonatedTokenChanged(AsyncLocalValueChangedArgs<SafeAccessTokenHandle> args)
{
if (!args.ThreadContextChanged)
return; // we handle explicit Value property changes elsewhere.
if (!Interop.mincore.RevertToSelf())
Environment.FailFast(Interop.mincore.GetMessage(Marshal.GetLastWin32Error()));
if (args.CurrentValue != null && !args.CurrentValue.IsInvalid)
{
if (!Interop.mincore.ImpersonateLoggedOnUser(args.CurrentValue))
Environment.FailFast(Interop.mincore.GetMessage(Marshal.GetLastWin32Error()));
}
}
internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess, bool threadOnly)
{
int hr = 0;
bool isImpersonating;
SafeAccessTokenHandle safeTokenHandle = GetCurrentToken(desiredAccess, threadOnly, out isImpersonating, out hr);
if (safeTokenHandle == null || safeTokenHandle.IsInvalid)
{
// either we wanted only ThreadToken - return null
if (threadOnly && !isImpersonating)
return null;
// or there was an error
throw new SecurityException(Interop.mincore.GetMessage(hr));
}
WindowsIdentity wi = new WindowsIdentity();
wi._safeTokenHandle.Dispose();
wi._safeTokenHandle = safeTokenHandle;
return wi;
}
//
// private.
//
private static int GetHRForWin32Error(int dwLastError)
{
if ((dwLastError & 0x80000000) == 0x80000000)
return dwLastError;
else
return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
}
private static Exception GetExceptionFromNtStatus(int status)
{
if ((uint)status == Interop.StatusOptions.STATUS_ACCESS_DENIED)
return new UnauthorizedAccessException();
if ((uint)status == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES || (uint)status == Interop.StatusOptions.STATUS_NO_MEMORY)
return new OutOfMemoryException();
int win32ErrorCode = Interop.mincore.RtlNtStatusToDosError(status);
return new SecurityException(Interop.mincore.GetMessage(win32ErrorCode));
}
private static SafeAccessTokenHandle GetCurrentToken(TokenAccessLevels desiredAccess, bool threadOnly, out bool isImpersonating, out int hr)
{
isImpersonating = true;
SafeAccessTokenHandle safeTokenHandle;
hr = 0;
bool success = Interop.mincore.OpenThreadToken(desiredAccess, WinSecurityContext.Both, out safeTokenHandle);
if (!success)
hr = Marshal.GetHRForLastWin32Error();
if (!success && hr == GetHRForWin32Error(Interop.mincore.Errors.ERROR_NO_TOKEN))
{
// No impersonation
isImpersonating = false;
if (!threadOnly)
safeTokenHandle = GetCurrentProcessToken(desiredAccess, out hr);
}
return safeTokenHandle;
}
private static SafeAccessTokenHandle GetCurrentProcessToken(TokenAccessLevels desiredAccess, out int hr)
{
hr = 0;
SafeAccessTokenHandle safeTokenHandle;
if (!Interop.mincore.OpenProcessToken(Interop.mincore.GetCurrentProcess(), desiredAccess, out safeTokenHandle))
hr = GetHRForWin32Error(Marshal.GetLastWin32Error());
return safeTokenHandle;
}
/// <summary>
/// Get a property from the current token
/// </summary>
private T GetTokenInformation<T>(TokenInformationClass tokenInformationClass) where T : struct
{
Debug.Assert(!_safeTokenHandle.IsInvalid && !_safeTokenHandle.IsClosed, "!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed");
using (SafeLocalAllocHandle information = GetTokenInformation(_safeTokenHandle, tokenInformationClass))
{
Debug.Assert(information.ByteLength >= (ulong)Marshal.SizeOf<T>(),
"information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T))");
return information.Read<T>(0);
}
}
//
// QueryImpersonation used to test if the current thread is impersonated.
// This method doesn't return the thread token (WindowsIdentity).
// Note GetCurrentInternal can be used to perform the same test, but
// QueryImpersonation is optimized for performance
//
internal static ImpersonationQueryResult QueryImpersonation()
{
SafeAccessTokenHandle safeTokenHandle = null;
bool success = Interop.mincore.OpenThreadToken(TokenAccessLevels.Query, WinSecurityContext.Thread, out safeTokenHandle);
if (safeTokenHandle != null)
{
Debug.Assert(success, "[WindowsIdentity..QueryImpersonation] - success");
safeTokenHandle.Dispose();
return ImpersonationQueryResult.Impersonated;
}
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
{
// thread is impersonated because the thread was there (and we failed to open it).
return ImpersonationQueryResult.Impersonated;
}
if (lastError == Interop.mincore.Errors.ERROR_NO_TOKEN)
{
// definitely not impersonating
return ImpersonationQueryResult.NotImpersonated;
}
// Unexpected failure.
return ImpersonationQueryResult.Failed;
}
private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle)
{
using (SafeLocalAllocHandle pStatistics = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics))
{
Interop.TOKEN_STATISTICS statistics = pStatistics.Read<Interop.TOKEN_STATISTICS>(0);
return statistics.AuthenticationId;
}
}
private static SafeLocalAllocHandle GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass)
{
SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
uint dwLength = (uint)Marshal.SizeOf<uint>();
bool result = Interop.mincore.GetTokenInformation(tokenHandle,
(uint)tokenInformationClass,
safeLocalAllocHandle,
0,
out dwLength);
int dwErrorCode = Marshal.GetLastWin32Error();
switch (dwErrorCode)
{
case Interop.mincore.Errors.ERROR_BAD_LENGTH:
// special case for TokenSessionId. Falling through
case Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER:
// ptrLength is an [In] param to LocalAlloc
UIntPtr ptrLength = new UIntPtr(dwLength);
safeLocalAllocHandle.Dispose();
safeLocalAllocHandle = Interop.mincore_obsolete.LocalAlloc(0, ptrLength);
if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid)
throw new OutOfMemoryException();
safeLocalAllocHandle.Initialize(dwLength);
result = Interop.mincore.GetTokenInformation(tokenHandle,
(uint)tokenInformationClass,
safeLocalAllocHandle,
dwLength,
out dwLength);
if (!result)
throw new SecurityException(Interop.mincore.GetMessage(Marshal.GetLastWin32Error()));
break;
case Interop.mincore.Errors.ERROR_INVALID_HANDLE:
throw new ArgumentException(SR.Argument_InvalidImpersonationToken);
default:
throw new SecurityException(Interop.mincore.GetMessage(dwErrorCode));
}
return safeLocalAllocHandle;
}
protected WindowsIdentity(WindowsIdentity identity)
: base(identity, null, identity._authType, null, null)
{
if (identity == null)
throw new ArgumentNullException("identity");
Contract.EndContractBlock();
bool mustDecrement = false;
try
{
if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle != SafeAccessTokenHandle.InvalidHandle && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero)
{
identity._safeTokenHandle.DangerousAddRef(ref mustDecrement);
if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero)
CreateFromToken(identity._safeTokenHandle.DangerousGetHandle());
_authType = identity._authType;
_isAuthenticated = identity._isAuthenticated;
}
}
finally
{
if (mustDecrement)
identity._safeTokenHandle.DangerousRelease();
}
}
internal IntPtr GetTokenInternal()
{
return _safeTokenHandle.DangerousGetHandle();
}
internal WindowsIdentity(ClaimsIdentity claimsIdentity, IntPtr userToken)
: base(claimsIdentity)
{
if (userToken != IntPtr.Zero && userToken.ToInt64() > 0)
{
CreateFromToken(userToken);
}
}
/// <summary>
/// Returns a new instance of the base, used when serializing the WindowsIdentity.
/// </summary>
internal ClaimsIdentity CloneAsBase()
{
return base.Clone();
}
/// <summary>
/// Returns a new instance of <see cref="WindowsIdentity"/> with values copied from this object.
/// </summary>
public override ClaimsIdentity Clone()
{
return new WindowsIdentity(this);
}
/// <summary>
/// Gets the 'User Claims' from the NTToken that represents this identity
/// </summary>
public virtual IEnumerable<Claim> UserClaims
{
get
{
InitializeClaims();
return _userClaims.ToArray();
}
}
/// <summary>
/// Gets the 'Device Claims' from the NTToken that represents the device the identity is using
/// </summary>
public virtual IEnumerable<Claim> DeviceClaims
{
get
{
InitializeClaims();
return _deviceClaims.ToArray();
}
}
/// <summary>
/// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="WindowsIdentity"/>.
/// Includes UserClaims and DeviceClaims.
/// </summary>
public override IEnumerable<Claim> Claims
{
get
{
if (!_claimsInitialized)
{
InitializeClaims();
}
foreach (Claim claim in base.Claims)
yield return claim;
foreach (Claim claim in _userClaims)
yield return claim;
foreach (Claim claim in _deviceClaims)
yield return claim;
}
}
/// <summary>
/// Intenal method to initialize the claim collection.
/// Lazy init is used so claims are not initialzed until needed
/// </summary>
private void InitializeClaims()
{
if (!_claimsInitialized)
{
lock (_claimsIntiailizedLock)
{
if (!_claimsInitialized)
{
_userClaims = new List<Claim>();
_deviceClaims = new List<Claim>();
if (!String.IsNullOrEmpty(Name))
{
//
// Add the name claim only if the WindowsIdentity.Name is populated
// WindowsIdentity.Name will be null when it is the fake anonymous user
// with a token value of IntPtr.Zero
//
_userClaims.Add(new Claim(NameClaimType, Name, ClaimValueTypes.String, _issuerName, _issuerName, this));
}
// primary sid
AddPrimarySidClaim(_userClaims);
// group sids
AddGroupSidClaims(_userClaims);
_claimsInitialized = true;
}
}
}
}
/// <summary>
/// Creates a collection of SID claims that represent the users groups.
/// </summary>
private void AddGroupSidClaims(List<Claim> instanceClaims)
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return;
SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle;
SafeLocalAllocHandle safeAllocHandlePrimaryGroup = SafeLocalAllocHandle.InvalidHandle;
try
{
// Retrieve the primary group sid
safeAllocHandlePrimaryGroup = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenPrimaryGroup);
Interop.TOKEN_PRIMARY_GROUP primaryGroup = (Interop.TOKEN_PRIMARY_GROUP)Marshal.PtrToStructure<Interop.TOKEN_PRIMARY_GROUP>(safeAllocHandlePrimaryGroup.DangerousGetHandle());
SecurityIdentifier primaryGroupSid = new SecurityIdentifier(primaryGroup.PrimaryGroup, true);
// only add one primary group sid
bool foundPrimaryGroupSid = false;
// Retrieve all group sids, primary group sid is one of them
safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups);
int count = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle());
IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups"));
Claim claim;
for (int i = 0; i < count; ++i)
{
Interop.SID_AND_ATTRIBUTES group = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(pSidAndAttributes);
uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true);
if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED)
{
if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value))
{
claim = new Claim(ClaimTypes.PrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
foundPrimaryGroupSid = true;
}
//Primary group sid generates both regular groupsid claim and primary groupsid claim
claim = new Claim(ClaimTypes.GroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
else if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY)
{
if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value))
{
claim = new Claim(ClaimTypes.DenyOnlyPrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
foundPrimaryGroupSid = true;
}
//Primary group sid generates both regular groupsid claim and primary groupsid claim
claim = new Claim(ClaimTypes.DenyOnlySid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Marshal.SizeOf<Interop.SID_AND_ATTRIBUTES>());
}
}
finally
{
safeAllocHandle.Dispose();
safeAllocHandlePrimaryGroup.Dispose();
}
}
/// <summary>
/// Creates a Windows SID Claim and adds to collection of claims.
/// </summary>
private void AddPrimarySidClaim(List<Claim> instanceClaims)
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return;
SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle;
try
{
safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser);
Interop.SID_AND_ATTRIBUTES user = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(safeAllocHandle.DangerousGetHandle());
uint mask = Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
SecurityIdentifier sid = new SecurityIdentifier(user.Sid, true);
Claim claim;
if (user.Attributes == 0)
{
claim = new Claim(ClaimTypes.PrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
else if ((user.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY)
{
claim = new Claim(ClaimTypes.DenyOnlyPrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
}
finally
{
safeAllocHandle.Dispose();
}
}
}
internal enum WinSecurityContext
{
Thread = 1, // OpenAsSelf = false
Process = 2, // OpenAsSelf = true
Both = 3 // OpenAsSelf = true, then OpenAsSelf = false
}
internal enum ImpersonationQueryResult
{
Impersonated = 0, // current thread is impersonated
NotImpersonated = 1, // current thread is not impersonated
Failed = 2 // failed to query
}
internal enum TokenType : int
{
TokenPrimary = 1,
TokenImpersonation
}
internal enum TokenInformationClass : int
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
TokenIsAppContainer,
TokenCapabilities,
TokenAppContainerSid,
TokenAppContainerNumber,
TokenUserClaimAttributes,
TokenDeviceClaimAttributes,
TokenRestrictedUserClaimAttributes,
TokenRestrictedDeviceClaimAttributes,
TokenDeviceGroups,
TokenRestrictedDeviceGroups,
MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum
}
}
| |
using System;
using Microsoft.SPOT;
/*
* Copyright 2011-2014 Stefan Thoolen (http://www.netmftoolbox.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Toolbox.NETMF.NET
{
/// <summary>
/// .NETMF SMTP Client
/// </summary>
public class SMTP_Client
{
/// <summary>
/// Small container for mail contacts
/// </summary>
public class MailContact
{
/// <summary>The full name of the person</summary>
public string Name { get; set; }
/// <summary>The mail address of the person</summary>
public string MailAddress { get; set; }
/// <summary>Returns the name and mail address as a string</summary>
/// <returns>Returns the name and mail address as a string</returns>
public override string ToString()
{
if (this.Name == "") return "<" + this.MailAddress + ">";
return "\"" + this.Name + "\" <" + this.MailAddress + ">";
}
/// <summary>Creates a new mail contact</summary>
/// <param name="MailAddress">The mail address of the person</param>
/// <param name="Name">The full name of the person</param>
public MailContact(string MailAddress, string Name = "") { this.MailAddress = MailAddress; this.Name = Name; }
}
/// <summary>
/// Container for mail messages
/// </summary>
public class MailMessage
{
/// <summary>The subject of the mail</summary>
public string Subject { get; set; }
/// <summary>The body of the mail</summary>
public string Body { get; set; }
/// <summary>Content type of the mail (default: text/plain)</summary>
public string ContentType { get; set; }
/// <summary>Character set of the mail (default: us-ascii)</summary>
public string CharacterSet { get; set; }
/// <summary>Defines the priority of the mail (1 to 5, default: 3)</summary>
public int Priority {
get
{
return this._Priority;
}
set
{
if (value < 1 || value > 5) throw new IndexOutOfRangeException();
this._Priority = value;
}
}
/// <summary>Contains the priority</summary>
private int _Priority;
/// <summary>Returns the mailbody</summary>
/// <returns>Returns the mailbody</returns>
public override string ToString() { return this.Body; }
/// <summary>Creates a new mail message</summary>
/// <param name="Subject">The subject of the mail</param>
/// <param name="Body">The body of the mail</param>
public MailMessage(string Subject, string Body = "")
{
this.Subject = Subject;
this.Body = Body;
this.Priority = 3;
this.ContentType = "text/plain";
this.CharacterSet = "us-ascii";
}
}
/// <summary>
/// Supported authentication types
/// </summary>
public enum AuthenticationTypes
{
/// <summary>No authentication is used</summary>
None = 0,
/// <summary>Login authentication is used</summary>
Login = 1
// I want to support Plain authentication as well, but a bug got in the way: http://netmf.codeplex.com/workitem/1321
//Plain = 2
}
/// <summary>Reference to the SMTP authentication type</summary>
private AuthenticationTypes _SMTP_Auth;
/// <summary>Reference to the SMTP authentication username</summary>
private string _SMTP_User;
/// <summary>Reference to the SMTP authentication password</summary>
private string _SMTP_Pass;
/// <summary>Local host name, used for identifying the mail client</summary>
private string _LocalHostname;
/// <summary>Reference to the socket</summary>
private SimpleSocket _Socket;
/// <summary>
/// Initializes a mail sender
/// </summary>
/// <param name="Socket">The socket to use (default TCP port for SMTP is 25)</param>
/// <param name="AuthenticationType">The form of SMTP Authentication (default: no authentication)</param>
/// <param name="Username">Username for the SMTP server (when using authentication)</param>
/// <param name="Password">Password for the SMTP server (when using authentication)</param>
public SMTP_Client(SimpleSocket Socket, AuthenticationTypes AuthenticationType = AuthenticationTypes.None, string Username = "", string Password = "")
{
// Copies all parameters to the global scope
this._Socket = Socket;
this._SMTP_User = Username;
this._SMTP_Pass = Password;
this._SMTP_Auth = AuthenticationType;
// By default we fill the hostname with the name of the hardware itself. We need this to identify ourself
string Hostname = Tools.HardwareProvider.ToString();
int LastDot = Hostname.LastIndexOf('.');
if (LastDot > 0)
this._LocalHostname = Hostname.Substring(0, LastDot);
else
this._LocalHostname = Hostname;
}
/// <summary>
/// Sends a message
/// </summary>
/// <param name="Message">The message to send</param>
/// <param name="From">The sender (From: header)</param>
/// <param name="To">A list of recipients (To: header)</param>
/// <param name="CC">A list of recipients (CC: header)</param>
/// <param name="BCC">A list of recipients (in no header at all)</param>
public void Send(MailMessage Message, MailContact From, MailContact[] To, MailContact[] CC = null, MailContact[] BCC = null)
{
// CC and BCC can be defined null
if (CC == null) CC = new MailContact[0];
if (BCC == null) BCC = new MailContact[0];
// This array will be filled with all recipients
string[] Recipients = new string[To.Length + CC.Length + BCC.Length];
int RecipientIndex = 0;
// Subject
string MailHeaders = "Subject: " + Message.Subject + "\r\n";
// From
MailHeaders += "From: " + From.ToString() + "\r\n";
// Reply-to
MailHeaders += "Reply-to: <" + From.MailAddress + ">\r\n";
// To
MailHeaders += "To: ";
for (int Counter = 0; Counter < To.Length; ++Counter)
{
MailHeaders += To[Counter].ToString() + ";";
Recipients[RecipientIndex] = To[Counter].MailAddress;
++RecipientIndex;
}
MailHeaders = MailHeaders.Substring(0, MailHeaders.Length - 1) + "\r\n";
// BCC
if (CC.Length != 0)
{
// CC
MailHeaders += "CC: ";
for (int Counter = 0; Counter < CC.Length; ++Counter)
{
MailHeaders += CC[Counter].ToString() + ";";
Recipients[RecipientIndex] = CC[Counter].MailAddress;
++RecipientIndex;
}
MailHeaders = MailHeaders.Substring(0, MailHeaders.Length - 1) + "\r\n";
}
// BCC
if (BCC.Length != 0)
{
for (int Counter = 0; Counter < BCC.Length; ++Counter)
{
Recipients[RecipientIndex] = BCC[Counter].MailAddress;
++RecipientIndex;
}
}
// Date; below 2011, the date is probably not set and sending it will only give the message a higher spam score in spam filters
if (DateTime.Now.Year > 2010)
MailHeaders += "Date: " + this._RFC2822_Date() + "\r\n";
// Message-ID
MailHeaders += "Message-ID: <" + DateTime.Now.Ticks.ToString() + "@" + this._LocalHostname + ">\r\n";
// Priority
if (Message.Priority != 3)
{
MailHeaders += "X-Priority: " + Message.Priority.ToString() + "\r\n";
}
// Content Type
MailHeaders += "Content-Type: " + Message.ContentType + "; charset=" + Message.CharacterSet + "\r\n";
// Mailer
MailHeaders += "X-Mailer: NETMFToolbox/0.1\r\n";
// Actually sends the mail
this._Send(From.MailAddress, Recipients, MailHeaders + "\r\n" + Message.Body);
}
/// <summary>
/// Sends a message
/// </summary>
/// <param name="Message">The message to send</param>
/// <param name="From">The sender (From: header)</param>
/// <param name="To">The recipient (To: header)</param>
public void Send(MailMessage Message, MailContact From, MailContact To)
{
this.Send(Message, From, new MailContact[] { To }, null, null);
}
/// <summary>
/// Actually sends a message
/// </summary>
/// <param name="From">The mail address of the sender</param>
/// <param name="Recipients">The mail addresses of all recipients (To, CC and BCC)</param>
/// <param name="Data">The data, including headers</param>
private void _Send(string From, string[] Recipients, string Data)
{
// Used for the answers of the SMTP server
string Text = "";
// Creates the socket
// Defines that we use line endings with the linefeed character
this._Socket.LineEnding = "\n";
// Connects to the socket
this._Socket.Connect();
string Error = "";
do
{ // We will use break, also when an error occures, so we always close the connection nicely
// Reads and validates the first line of data
Text = this._Socket.Receive(true);
if (Text.Substring(0, 3) != "220") { Error = Text; break; }
// Say "hello!"
this._Socket.Send("HELO " + this._LocalHostname + "\r\n");
// Validates the response. Some servers send multiple 220 replies. We require a 250 reply. All other replies are invalid.
while (Text.Substring(0, 3) == "220")
Text = this._Socket.Receive(true);
if (Text.Substring(0, 3) != "250") { Error = Text; break; }
// Login Authentication Support
if (this._SMTP_Auth == AuthenticationTypes.Login)
{
// Authenticates with the LOGIN authentication type
this._Socket.Send("AUTH LOGIN\r\n");
Text = this._Socket.Receive(true);
if (Text.Substring(0, 3) != "334") { Error = Text; break; }
// Sends the username, base64 encoded
this._Socket.Send(Tools.Base64Encode(this._SMTP_User) + "\r\n");
Text = this._Socket.Receive(true);
if (Text.Substring(0, 3) != "334") { Error = Text; break; }
// Sends the password, base64 encoded
this._Socket.Send(Tools.Base64Encode(this._SMTP_Pass) + "\r\n");
Text = this._Socket.Receive(true);
if (Text.Substring(0, 3) != "235") { Error = Text; break; }
}
// Specifies the sender and validates the response
this._Socket.Send("MAIL FROM:<" + From + ">\r\n");
Text = this._Socket.Receive(true);
if (Text.Substring(0, 3) != "250") { Error = Text; break; }
// Specifies the receiver and validates the response
for (int Counter = 0; Counter < Recipients.Length; ++Counter)
{
this._Socket.Send("RCPT TO:<" + Recipients[Counter] + ">\r\n");
Text = this._Socket.Receive(true);
if (Text.Substring(0, 3) != "250") { Error = Text; break; }
}
// Initializes data transfer
this._Socket.Send("DATA\r\n");
Text = this._Socket.Receive(true);
if (Text.Substring(0, 3) != "354") { Error = Text; break; }
// Sends the actual data
this._Socket.Send(Data + "\r\n.\r\n");
Text = this._Socket.Receive(true);
if (Text.Substring(0, 3) != "250") { Error = Text; break; }
} while (false);
// Closes the connection
this._Socket.Send("QUIT\r\n");
this._Socket.Close();
if (Error != "")
{
throw new SystemException(Error);
}
}
/// <summary>
/// Returns the date formatted for mail headers
/// </summary>
/// <returns>The date formatted for mail headers</returns>
private string _RFC2822_Date()
{
// All days in a week
string[] Days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
// All months in a year
string[] Months = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
// Current date/time
DateTime dt = DateTime.Now;
// Timezone
string tz = Tools.ZeroFill(DateTime.UtcNow.CompareTo(dt) * 100, 4);
if (tz.Substring(0, 1) != "-") tz = "+" + tz;
// Start building the output
string Output = "";
Output += Days[(int)dt.DayOfWeek] + ", ";
Output += dt.Day + " ";
Output += Months[(int)dt.Month] + " ";
Output += dt.Year + " ";
Output += Tools.ZeroFill(dt.Hour, 2) + ":";
Output += Tools.ZeroFill(dt.Minute, 2) + ":";
Output += Tools.ZeroFill(dt.Second, 2) + " ";
Output += tz;
return Output;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="AreaDescriptionPicker.cs" company="Google">
//
// Copyright 2016 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Tango;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
/// List controller of the scrolling list.
///
/// This list controller present a toggle group of Tango space Area Descriptions. The list class also has interface
/// to start the game and connect to Tango Service.
/// </summary>
public class AreaDescriptionPicker : MonoBehaviour, ITangoLifecycle
{
/// <summary>
/// The prefab of a standard button in the scrolling list.
/// </summary>
public GameObject m_listElement;
/// <summary>
/// The container panel of the Tango space Area Description scrolling list.
/// </summary>
public RectTransform m_listContentParent;
/// <summary>
/// Toggle group for the Area Description list.
///
/// You can only toggle one Area Description at a time. After we get the list of Area Description from Tango,
/// they are all added to this toggle group.
/// </summary>
public ToggleGroup m_toggleGroup;
/// <summary>
/// Enable learning mode toggle.
///
/// Learning Mode allows the loaded Area Description to be extended with more knowledge about the area..
/// </summary>
public Toggle m_enableLearningToggle;
/// <summary>
/// The reference of the TangoPoseController object.
///
/// TangoPoseController listens to pose updates and applies the correct pose to itself and its built-in camera.
/// </summary>
public TangoPoseController m_poseController;
/// <summary>
/// Control panel game object.
///
/// The panel will be enabled when the game starts.
/// </summary>
public GameObject m_gameControlPanel;
/// <summary>
/// The GUI controller.
///
/// GUI controller will be enabled when the game starts.
/// </summary>
public AreaLearningInGameController m_guiController;
/// <summary>
/// A reference to TangoApplication instance.
/// </summary>
private TangoApplication m_tangoApplication;
/// <summary>
/// The UUID of the selected Area Description.
/// </summary>
private string m_curAreaDescriptionUUID;
/// <summary>
/// Start the game.
///
/// This will start the service connection, and start pose estimation from Tango Service.
/// </summary>
/// <param name="isNewAreaDescription">If set to <c>true</c> game with start to learn a new Area
/// Description.</param>
public void StartGame(bool isNewAreaDescription)
{
// The game has to be started with an Area Description.
if (!isNewAreaDescription)
{
if (string.IsNullOrEmpty(m_curAreaDescriptionUUID))
{
AndroidHelper.ShowAndroidToastMessage("Please choose an Area Description.");
return;
}
}
else
{
m_curAreaDescriptionUUID = null;
}
// Dismiss Area Description list, footer and header UI panel.
gameObject.SetActive(false);
if (isNewAreaDescription)
{
// Completely new area description.
m_guiController.m_curAreaDescription = null;
m_tangoApplication.m_areaDescriptionLearningMode = true;
}
else
{
// Load up an existing Area Description.
AreaDescription areaDescription = AreaDescription.ForUUID(m_curAreaDescriptionUUID);
m_guiController.m_curAreaDescription = areaDescription;
m_tangoApplication.m_areaDescriptionLearningMode = m_enableLearningToggle.isOn;
}
m_tangoApplication.Startup(m_guiController.m_curAreaDescription);
// Enable GUI controller to allow user tap and interactive with the environment.
m_poseController.gameObject.SetActive(true);
m_guiController.enabled = true;
m_gameControlPanel.SetActive(true);
}
/// <summary>
/// Internal callback when a permissions event happens.
/// </summary>
/// <param name="permissionsGranted">If set to <c>true</c> permissions granted.</param>
public void OnTangoPermissions(bool permissionsGranted)
{
if (permissionsGranted)
{
_PopulateList();
}
else
{
AndroidHelper.ShowAndroidToastMessage("Motion Tracking and Area Learning Permissions Needed");
// This is a fix for a lifecycle issue where calling
// Application.Quit() here, and restarting the application
// immediately results in a deadlocked app.
AndroidHelper.AndroidQuit();
}
}
/// <summary>
/// This is called when successfully connected to the Tango service.
/// </summary>
public void OnTangoServiceConnected()
{
}
/// <summary>
/// This is called when disconnected from the Tango service.
/// </summary>
public void OnTangoServiceDisconnected()
{
}
/// <summary>
/// Unity Start function.
///
/// This function is responsible for connecting callbacks, set up TangoApplication and initialize the data list.
/// </summary>
public void Start()
{
m_tangoApplication = FindObjectOfType<TangoApplication>();
if (m_tangoApplication != null)
{
m_tangoApplication.Register(this);
if (AndroidHelper.IsTangoCorePresent())
{
m_tangoApplication.RequestPermissions();
}
}
else
{
Debug.Log("No Tango Manager found in scene.");
}
}
/// <summary>
/// Unity Update function.
///
/// Application will be closed when click the back button.
/// </summary>
public void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
// This is a fix for a lifecycle issue where calling
// Application.Quit() here, and restarting the application
// immediately results in a deadlocked app.
AndroidHelper.AndroidQuit();
}
}
/// <summary>
/// Refresh the scrolling list's content for both list.
///
/// This function will query from the Tango API for the Tango space Area Description. Also, when it populates
/// the scrolling list content, it will connect the delegate for each button in the list. The delegate is
/// responsible for the actual import/export through the Tango API.
/// </summary>
private void _PopulateList()
{
foreach (Transform t in m_listContentParent.transform)
{
Destroy(t.gameObject);
}
// Update Tango space Area Description list.
AreaDescription[] areaDescriptionList = AreaDescription.GetList();
if (areaDescriptionList == null)
{
return;
}
foreach (AreaDescription areaDescription in areaDescriptionList)
{
GameObject newElement = Instantiate(m_listElement) as GameObject;
AreaDescriptionListElement listElement = newElement.GetComponent<AreaDescriptionListElement>();
listElement.m_toggle.group = m_toggleGroup;
listElement.m_areaDescriptionName.text = areaDescription.GetMetadata().m_name;
listElement.m_areaDescriptionUUID.text = areaDescription.m_uuid;
// Ensure the lambda makes a copy of areaDescription.
AreaDescription lambdaParam = areaDescription;
listElement.m_toggle.onValueChanged.AddListener((value) => _OnToggleChanged(lambdaParam, value));
newElement.transform.SetParent(m_listContentParent.transform, false);
}
}
/// <summary>
/// Callback function when toggle button is selected.
/// </summary>
/// <param name="item">Caller item object.</param>
/// <param name="value">Selected value of the toggle button.</param>
private void _OnToggleChanged(AreaDescription item, bool value)
{
if (value)
{
m_curAreaDescriptionUUID = item.m_uuid;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Net.Sockets
{
internal static partial class SocketPal
{
// The API that uses this information is not supported on *nix, and will throw
// PlatformNotSupportedException instead.
public const int ProtocolInformationSize = 0;
public const bool SupportsMultipleConnectAttempts = false;
private readonly static bool SupportsDualModeIPv4PacketInfo = GetPlatformSupportsDualModeIPv4PacketInfo();
private static bool GetPlatformSupportsDualModeIPv4PacketInfo()
{
return Interop.Sys.PlatformSupportsDualModeIPv4PacketInfo();
}
public static SocketError GetSocketErrorForErrorCode(Interop.Error errorCode)
{
return SocketErrorPal.GetSocketErrorForNativeError(errorCode);
}
public static void CheckDualModeReceiveSupport(Socket socket)
{
if (!SupportsDualModeIPv4PacketInfo && socket.AddressFamily == AddressFamily.InterNetworkV6 && socket.DualMode)
{
throw new PlatformNotSupportedException(SR.net_sockets_dualmode_receivefrom_notsupported);
}
}
private static unsafe IPPacketInformation GetIPPacketInformation(Interop.Sys.MessageHeader* messageHeader, bool isIPv4, bool isIPv6)
{
if (!isIPv4 && !isIPv6)
{
return default(IPPacketInformation);
}
Interop.Sys.IPPacketInformation nativePacketInfo;
if (!Interop.Sys.TryGetIPPacketInformation(messageHeader, isIPv4, &nativePacketInfo))
{
return default(IPPacketInformation);
}
return new IPPacketInformation(nativePacketInfo.Address.GetIPAddress(), nativePacketInfo.InterfaceIndex);
}
public static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket)
{
return SafeCloseSocket.CreateSocket(addressFamily, socketType, protocolType, out socket);
}
private static unsafe int Receive(SafeCloseSocket socket, SocketFlags flags, byte[] buffer, int offset, int count, byte[] socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
{
Debug.Assert(socketAddress != null || socketAddressLen == 0, $"Unexpected values: socketAddress={socketAddress}, socketAddressLen={socketAddressLen}");
long received;
int sockAddrLen = 0;
if (socketAddress != null)
{
sockAddrLen = socketAddressLen;
}
fixed (byte* sockAddr = socketAddress)
fixed (byte* b = buffer)
{
var iov = new Interop.Sys.IOVector {
Base = &b[offset],
Count = (UIntPtr)count
};
var messageHeader = new Interop.Sys.MessageHeader {
SocketAddress = sockAddr,
SocketAddressLen = sockAddrLen,
IOVectors = &iov,
IOVectorCount = 1
};
errno = Interop.Sys.ReceiveMessage(socket, &messageHeader, flags, &received);
receivedFlags = messageHeader.Flags;
sockAddrLen = messageHeader.SocketAddressLen;
}
if (errno != Interop.Error.SUCCESS)
{
return -1;
}
socketAddressLen = sockAddrLen;
return checked((int)received);
}
private static unsafe int Send(SafeCloseSocket socket, SocketFlags flags, byte[] buffer, ref int offset, ref int count, byte[] socketAddress, int socketAddressLen, out Interop.Error errno)
{
int sent;
int sockAddrLen = 0;
if (socketAddress != null)
{
sockAddrLen = socketAddressLen;
}
fixed (byte* sockAddr = socketAddress)
fixed (byte* b = buffer)
{
var iov = new Interop.Sys.IOVector {
Base = &b[offset],
Count = (UIntPtr)count
};
var messageHeader = new Interop.Sys.MessageHeader {
SocketAddress = sockAddr,
SocketAddressLen = sockAddrLen,
IOVectors = &iov,
IOVectorCount = 1
};
long bytesSent;
errno = Interop.Sys.SendMessage(socket, &messageHeader, flags, &bytesSent);
sent = checked((int)bytesSent);
}
if (errno != Interop.Error.SUCCESS)
{
return -1;
}
offset += sent;
count -= sent;
return sent;
}
private static unsafe int Send(SafeCloseSocket socket, SocketFlags flags, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, byte[] socketAddress, int socketAddressLen, out Interop.Error errno)
{
// Pin buffers and set up iovecs.
int startIndex = bufferIndex, startOffset = offset;
int sockAddrLen = 0;
if (socketAddress != null)
{
sockAddrLen = socketAddressLen;
}
int maxBuffers = buffers.Count - startIndex;
var handles = new GCHandle[maxBuffers];
var iovecs = new Interop.Sys.IOVector[maxBuffers];
int sent;
int toSend = 0, iovCount = maxBuffers;
try
{
for (int i = 0; i < maxBuffers; i++, startOffset = 0)
{
ArraySegment<byte> buffer = buffers[startIndex + i];
Debug.Assert(buffer.Offset + startOffset < buffer.Array.Length, $"Unexpected values: Offset={buffer.Offset}, startOffset={startOffset}, Length={buffer.Array.Length}");
handles[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
iovecs[i].Base = &((byte*)handles[i].AddrOfPinnedObject())[buffer.Offset + startOffset];
toSend += (buffer.Count - startOffset);
iovecs[i].Count = (UIntPtr)(buffer.Count - startOffset);
}
// Make the call
fixed (byte* sockAddr = socketAddress)
fixed (Interop.Sys.IOVector* iov = iovecs)
{
var messageHeader = new Interop.Sys.MessageHeader {
SocketAddress = sockAddr,
SocketAddressLen = sockAddrLen,
IOVectors = iov,
IOVectorCount = iovCount
};
long bytesSent;
errno = Interop.Sys.SendMessage(socket, &messageHeader, flags, &bytesSent);
sent = checked((int)bytesSent);
}
}
finally
{
// Free GC handles.
for (int i = 0; i < iovCount; i++)
{
if (handles[i].IsAllocated)
{
handles[i].Free();
}
}
}
if (errno != Interop.Error.SUCCESS)
{
return -1;
}
// Update position.
int endIndex = bufferIndex, endOffset = offset, unconsumed = sent;
for (; endIndex < buffers.Count && unconsumed > 0; endIndex++, endOffset = 0)
{
int space = buffers[endIndex].Count - endOffset;
if (space > unconsumed)
{
endOffset += unconsumed;
break;
}
unconsumed -= space;
}
bufferIndex = endIndex;
offset = endOffset;
return sent;
}
private static unsafe int Receive(SafeCloseSocket socket, SocketFlags flags, IList<ArraySegment<byte>> buffers, byte[] socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
{
int available;
errno = Interop.Sys.GetBytesAvailable(socket, &available);
if (errno != Interop.Error.SUCCESS)
{
receivedFlags = 0;
return -1;
}
if (available == 0)
{
// Always request at least one byte.
available = 1;
}
// Pin buffers and set up iovecs.
int maxBuffers = buffers.Count;
var handles = new GCHandle[maxBuffers];
var iovecs = new Interop.Sys.IOVector[maxBuffers];
int sockAddrLen = 0;
if (socketAddress != null)
{
sockAddrLen = socketAddressLen;
}
long received = 0;
int toReceive = 0, iovCount = maxBuffers;
try
{
for (int i = 0; i < maxBuffers; i++)
{
ArraySegment<byte> buffer = buffers[i];
handles[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
iovecs[i].Base = &((byte*)handles[i].AddrOfPinnedObject())[buffer.Offset];
int space = buffer.Count;
toReceive += space;
if (toReceive >= available)
{
iovecs[i].Count = (UIntPtr)(space - (toReceive - available));
toReceive = available;
iovCount = i + 1;
break;
}
iovecs[i].Count = (UIntPtr)space;
}
// Make the call.
fixed (byte* sockAddr = socketAddress)
fixed (Interop.Sys.IOVector* iov = iovecs)
{
var messageHeader = new Interop.Sys.MessageHeader {
SocketAddress = sockAddr,
SocketAddressLen = sockAddrLen,
IOVectors = iov,
IOVectorCount = iovCount
};
errno = Interop.Sys.ReceiveMessage(socket, &messageHeader, flags, &received);
receivedFlags = messageHeader.Flags;
sockAddrLen = messageHeader.SocketAddressLen;
}
}
finally
{
// Free GC handles.
for (int i = 0; i < iovCount; i++)
{
if (handles[i].IsAllocated)
{
handles[i].Free();
}
}
}
if (errno != Interop.Error.SUCCESS)
{
return -1;
}
socketAddressLen = sockAddrLen;
return checked((int)received);
}
private static unsafe int ReceiveMessageFrom(SafeCloseSocket socket, SocketFlags flags, byte[] buffer, int offset, int count, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out Interop.Error errno)
{
Debug.Assert(socketAddress != null, "Expected non-null socketAddress");
int cmsgBufferLen = Interop.Sys.GetControlMessageBufferSize(isIPv4, isIPv6);
var cmsgBuffer = stackalloc byte[cmsgBufferLen];
int sockAddrLen = socketAddressLen;
Interop.Sys.MessageHeader messageHeader;
long received;
fixed (byte* rawSocketAddress = socketAddress)
fixed (byte* b = buffer)
{
var sockAddr = (byte*)rawSocketAddress;
var iov = new Interop.Sys.IOVector {
Base = &b[offset],
Count = (UIntPtr)count
};
messageHeader = new Interop.Sys.MessageHeader {
SocketAddress = sockAddr,
SocketAddressLen = sockAddrLen,
IOVectors = &iov,
IOVectorCount = 1,
ControlBuffer = cmsgBuffer,
ControlBufferLen = cmsgBufferLen
};
errno = Interop.Sys.ReceiveMessage(socket, &messageHeader, flags, &received);
receivedFlags = messageHeader.Flags;
sockAddrLen = messageHeader.SocketAddressLen;
}
ipPacketInformation = GetIPPacketInformation(&messageHeader, isIPv4, isIPv6);
if (errno != Interop.Error.SUCCESS)
{
return -1;
}
socketAddressLen = sockAddrLen;
return checked((int)received);
}
public static unsafe bool TryCompleteAccept(SafeCloseSocket socket, byte[] socketAddress, ref int socketAddressLen, out IntPtr acceptedFd, out SocketError errorCode)
{
IntPtr fd;
Interop.Error errno;
int sockAddrLen = socketAddressLen;
fixed (byte* rawSocketAddress = socketAddress)
{
try
{
errno = Interop.Sys.Accept(socket, rawSocketAddress, &sockAddrLen, &fd);
}
catch (ObjectDisposedException)
{
// The socket was closed, or is closing.
errorCode = SocketError.OperationAborted;
acceptedFd = (IntPtr)(-1);
return true;
}
}
if (errno == Interop.Error.SUCCESS)
{
Debug.Assert(fd != (IntPtr)(-1), "Expected fd != -1");
socketAddressLen = sockAddrLen;
errorCode = SocketError.Success;
acceptedFd = fd;
return true;
}
acceptedFd = (IntPtr)(-1);
if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
{
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
errorCode = SocketError.Success;
return false;
}
public static unsafe bool TryStartConnect(SafeCloseSocket socket, byte[] socketAddress, int socketAddressLen, out SocketError errorCode)
{
Debug.Assert(socketAddress != null, "Expected non-null socketAddress");
Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}");
Interop.Error err;
fixed (byte* rawSocketAddress = socketAddress)
{
err = Interop.Sys.Connect(socket, rawSocketAddress, socketAddressLen);
}
if (err == Interop.Error.SUCCESS)
{
errorCode = SocketError.Success;
return true;
}
if (err != Interop.Error.EINPROGRESS)
{
errorCode = GetSocketErrorForErrorCode(err);
return true;
}
errorCode = SocketError.Success;
return false;
}
public static unsafe bool TryCompleteConnect(SafeCloseSocket socket, int socketAddressLen, out SocketError errorCode)
{
Interop.Error socketError;
Interop.Error err;
try
{
err = Interop.Sys.GetSocketErrorOption(socket, &socketError);
}
catch (ObjectDisposedException)
{
// The socket was closed, or is closing.
errorCode = SocketError.OperationAborted;
return true;
}
if (err != Interop.Error.SUCCESS)
{
Debug.Assert(err == Interop.Error.EBADF, $"Unexpected err: {err}");
errorCode = SocketError.SocketError;
return true;
}
if (socketError == Interop.Error.SUCCESS)
{
errorCode = SocketError.Success;
return true;
}
else if (socketError == Interop.Error.EINPROGRESS)
{
errorCode = SocketError.Success;
return false;
}
errorCode = GetSocketErrorForErrorCode(socketError);
return true;
}
public static bool TryCompleteReceiveFrom(SafeCloseSocket socket, byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode)
{
return TryCompleteReceiveFrom(socket, buffer, null, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode);
}
public static bool TryCompleteReceiveFrom(SafeCloseSocket socket, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode)
{
return TryCompleteReceiveFrom(socket, null, buffers, 0, 0, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode);
}
public static unsafe bool TryCompleteReceiveFrom(SafeCloseSocket socket, byte[] buffer, IList<ArraySegment<byte>> buffers, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode)
{
try
{
Interop.Error errno;
int received;
if (buffer != null)
{
received = Receive(socket, flags, buffer, offset, count, socketAddress, ref socketAddressLen, out receivedFlags, out errno);
}
else
{
received = Receive(socket, flags, buffers, socketAddress, ref socketAddressLen, out receivedFlags, out errno);
}
if (received != -1)
{
bytesReceived = received;
errorCode = SocketError.Success;
return true;
}
bytesReceived = 0;
if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
{
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
errorCode = SocketError.Success;
return false;
}
catch (ObjectDisposedException)
{
// The socket was closed, or is closing.
bytesReceived = 0;
receivedFlags = 0;
errorCode = SocketError.OperationAborted;
return true;
}
}
public static unsafe bool TryCompleteReceiveMessageFrom(SafeCloseSocket socket, byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out SocketError errorCode)
{
try
{
Interop.Error errno;
int received = ReceiveMessageFrom(socket, flags, buffer, offset, count, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out receivedFlags, out ipPacketInformation, out errno);
if (received != -1)
{
bytesReceived = received;
errorCode = SocketError.Success;
return true;
}
bytesReceived = 0;
if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
{
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
errorCode = SocketError.Success;
return false;
}
catch (ObjectDisposedException)
{
// The socket was closed, or is closing.
bytesReceived = 0;
receivedFlags = 0;
ipPacketInformation = default(IPPacketInformation);
errorCode = SocketError.OperationAborted;
return true;
}
}
public static bool TryCompleteSendTo(SafeCloseSocket socket, byte[] buffer, ref int offset, ref int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
int bufferIndex = 0;
return TryCompleteSendTo(socket, buffer, null, ref bufferIndex, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode);
}
public static bool TryCompleteSendTo(SafeCloseSocket socket, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
int count = 0;
return TryCompleteSendTo(socket, null, buffers, ref bufferIndex, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode);
}
public static bool TryCompleteSendTo(SafeCloseSocket socket, byte[] buffer, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, ref int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
for (;;)
{
int sent;
Interop.Error errno;
try
{
if (buffer != null)
{
sent = Send(socket, flags, buffer, ref offset, ref count, socketAddress, socketAddressLen, out errno);
}
else
{
sent = Send(socket, flags, buffers, ref bufferIndex, ref offset, socketAddress, socketAddressLen, out errno);
}
}
catch (ObjectDisposedException)
{
// The socket was closed, or is closing.
errorCode = SocketError.OperationAborted;
return true;
}
if (sent == -1)
{
if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
{
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
errorCode = SocketError.Success;
return false;
}
bytesSent += sent;
bool isComplete = sent == 0 ||
(buffer != null && count == 0) ||
(buffers != null && bufferIndex == buffers.Count);
if (isComplete)
{
errorCode = SocketError.Success;
return true;
}
}
}
public static SocketError SetBlocking(SafeCloseSocket handle, bool shouldBlock, out bool willBlock)
{
handle.IsNonBlocking = !shouldBlock;
willBlock = shouldBlock;
return SocketError.Success;
}
public static unsafe SocketError GetSockName(SafeCloseSocket handle, byte[] buffer, ref int nameLen)
{
Interop.Error err;
int addrLen = nameLen;
fixed (byte* rawBuffer = buffer)
{
err = Interop.Sys.GetSockName(handle, rawBuffer, &addrLen);
}
nameLen = addrLen;
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError GetAvailable(SafeCloseSocket handle, out int available)
{
int value = 0;
Interop.Error err = Interop.Sys.GetBytesAvailable(handle, &value);
available = value;
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError GetPeerName(SafeCloseSocket handle, byte[] buffer, ref int nameLen)
{
Interop.Error err;
int addrLen = nameLen;
fixed (byte* rawBuffer = buffer)
{
err = Interop.Sys.GetPeerName(handle, rawBuffer, &addrLen);
}
nameLen = addrLen;
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError Bind(SafeCloseSocket handle, byte[] buffer, int nameLen)
{
Interop.Error err;
fixed (byte* rawBuffer = buffer)
{
err = Interop.Sys.Bind(handle, rawBuffer, nameLen);
}
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static SocketError Listen(SafeCloseSocket handle, int backlog)
{
Interop.Error err = Interop.Sys.Listen(handle, backlog);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static SocketError Accept(SafeCloseSocket handle, byte[] buffer, ref int nameLen, out SafeCloseSocket socket)
{
return SafeCloseSocket.Accept(handle, buffer, ref nameLen, out socket);
}
public static SocketError Connect(SafeCloseSocket handle, byte[] socketAddress, int socketAddressLen)
{
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.Connect(socketAddress, socketAddressLen, -1);
}
handle.AsyncContext.CheckForPriorConnectFailure();
SocketError errorCode;
bool completed = TryStartConnect(handle, socketAddress, socketAddressLen, out errorCode);
if (completed)
{
handle.AsyncContext.RegisterConnectResult(errorCode);
return errorCode;
}
else
{
return SocketError.WouldBlock;
}
}
public static SocketError Disconnect(Socket socket, SafeCloseSocket handle, bool reuseSocket)
{
throw new PlatformNotSupportedException();
}
public static SocketError Send(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
var bufferList = buffers;
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.Send(bufferList, socketFlags, handle.SendTimeout, out bytesTransferred);
}
bytesTransferred = 0;
int bufferIndex = 0;
int offset = 0;
SocketError errorCode;
bool completed = TryCompleteSendTo(handle, bufferList, ref bufferIndex, ref offset, socketFlags, null, 0, ref bytesTransferred, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError Send(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, out int bytesTransferred)
{
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.Send(buffer, offset, count, socketFlags, handle.SendTimeout, out bytesTransferred);
}
bytesTransferred = 0;
SocketError errorCode;
bool completed = TryCompleteSendTo(handle, buffer, ref offset, ref count, socketFlags, null, 0, ref bytesTransferred, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError SendTo(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, byte[] socketAddress, int socketAddressLen, out int bytesTransferred)
{
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.SendTo(buffer, offset, count, socketFlags, socketAddress, socketAddressLen, handle.SendTimeout, out bytesTransferred);
}
bytesTransferred = 0;
SocketError errorCode;
bool completed = TryCompleteSendTo(handle, buffer, ref offset, ref count, socketFlags, socketAddress, socketAddressLen, ref bytesTransferred, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError Receive(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, ref SocketFlags socketFlags, out int bytesTransferred)
{
SocketError errorCode;
if (!handle.IsNonBlocking)
{
errorCode = handle.AsyncContext.Receive(buffers, ref socketFlags, handle.ReceiveTimeout, out bytesTransferred);
}
else
{
int socketAddressLen = 0;
if (!TryCompleteReceiveFrom(handle, buffers, socketFlags, null, ref socketAddressLen, out bytesTransferred, out socketFlags, out errorCode))
{
errorCode = SocketError.WouldBlock;
}
}
return errorCode;
}
public static SocketError Receive(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, out int bytesTransferred)
{
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.Receive(buffer, offset, count, ref socketFlags, handle.ReceiveTimeout, out bytesTransferred);
}
int socketAddressLen = 0;
SocketError errorCode;
bool completed = TryCompleteReceiveFrom(handle, buffer, offset, count, socketFlags, null, ref socketAddressLen, out bytesTransferred, out socketFlags, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError ReceiveMessageFrom(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
{
byte[] socketAddressBuffer = socketAddress.Buffer;
int socketAddressLen = socketAddress.Size;
bool isIPv4, isIPv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, socketAddress, out isIPv4, out isIPv6);
SocketError errorCode;
if (!handle.IsNonBlocking)
{
errorCode = handle.AsyncContext.ReceiveMessageFrom(buffer, offset, count, ref socketFlags, socketAddressBuffer, ref socketAddressLen, isIPv4, isIPv6, handle.ReceiveTimeout, out ipPacketInformation, out bytesTransferred);
}
else
{
if (!TryCompleteReceiveMessageFrom(handle, buffer, offset, count, socketFlags, socketAddressBuffer, ref socketAddressLen, isIPv4, isIPv6, out bytesTransferred, out socketFlags, out ipPacketInformation, out errorCode))
{
errorCode = SocketError.WouldBlock;
}
}
socketAddress.InternalSize = socketAddressLen;
receiveAddress = socketAddress;
return errorCode;
}
public static SocketError ReceiveFrom(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, byte[] socketAddress, ref int socketAddressLen, out int bytesTransferred)
{
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.ReceiveFrom(buffer, offset, count, ref socketFlags, socketAddress, ref socketAddressLen, handle.ReceiveTimeout, out bytesTransferred);
}
SocketError errorCode;
bool completed = TryCompleteReceiveFrom(handle, buffer, offset, count, socketFlags, socketAddress, ref socketAddressLen, out bytesTransferred, out socketFlags, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError WindowsIoctl(SafeCloseSocket handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
{
throw new PlatformNotSupportedException();
}
public static unsafe SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
Interop.Error err;
if (optionLevel == SocketOptionLevel.Socket)
{
if (optionName == SocketOptionName.ReceiveTimeout)
{
handle.ReceiveTimeout = optionValue == 0 ? -1 : optionValue;
err = Interop.Sys.SetReceiveTimeout(handle, optionValue);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
else if (optionName == SocketOptionName.SendTimeout)
{
handle.SendTimeout = optionValue == 0 ? -1 : optionValue;
err = Interop.Sys.SetSendTimeout(handle, optionValue);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
}
else if (optionLevel == SocketOptionLevel.IP)
{
if (optionName == SocketOptionName.MulticastInterface)
{
// if the value of the IP_MULTICAST_IF is an address in the 0.x.x.x block
// the value is interpreted as an interface index
int interfaceIndex = IPAddress.NetworkToHostOrder(optionValue);
if ((interfaceIndex & 0xff000000) == 0)
{
var opt = new Interop.Sys.IPv4MulticastOption {
MulticastAddress = 0,
LocalAddress = 0,
InterfaceIndex = interfaceIndex
};
err = Interop.Sys.SetIPv4MulticastOption(handle, Interop.Sys.MulticastOption.MULTICAST_IF, &opt);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
}
}
err = Interop.Sys.SetSockOpt(handle, optionLevel, optionName, (byte*)&optionValue, sizeof(int));
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
Interop.Error err;
if (optionValue == null || optionValue.Length == 0)
{
err = Interop.Sys.SetSockOpt(handle, optionLevel, optionName, null, 0);
}
else
{
fixed (byte* pinnedValue = optionValue)
{
err = Interop.Sys.SetSockOpt(handle, optionLevel, optionName, pinnedValue, optionValue.Length);
}
}
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError SetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, MulticastOption optionValue)
{
Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership, $"Unexpected optionName: {optionName}");
Interop.Sys.MulticastOption optName = optionName == SocketOptionName.AddMembership ?
Interop.Sys.MulticastOption.MULTICAST_ADD :
Interop.Sys.MulticastOption.MULTICAST_DROP;
IPAddress localAddress = optionValue.LocalAddress ?? IPAddress.Any;
var opt = new Interop.Sys.IPv4MulticastOption {
MulticastAddress = unchecked((uint)optionValue.Group.GetAddress()),
LocalAddress = unchecked((uint)localAddress.GetAddress()),
InterfaceIndex = optionValue.InterfaceIndex
};
Interop.Error err = Interop.Sys.SetIPv4MulticastOption(handle, optName, &opt);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError SetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, IPv6MulticastOption optionValue)
{
Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership, $"Unexpected optionName={optionName}");
Interop.Sys.MulticastOption optName = optionName == SocketOptionName.AddMembership ?
Interop.Sys.MulticastOption.MULTICAST_ADD :
Interop.Sys.MulticastOption.MULTICAST_DROP;
var opt = new Interop.Sys.IPv6MulticastOption {
Address = optionValue.Group.GetNativeIPAddress(),
InterfaceIndex = (int)optionValue.InterfaceIndex
};
Interop.Error err = Interop.Sys.SetIPv6MulticastOption(handle, optName, &opt);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError SetLingerOption(SafeCloseSocket handle, LingerOption optionValue)
{
var opt = new Interop.Sys.LingerOption {
OnOff = optionValue.Enabled ? 1 : 0,
Seconds = optionValue.LingerTime
};
Interop.Error err = Interop.Sys.SetLingerOption(handle, &opt);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static void SetReceivingDualModeIPv4PacketInformation(Socket socket)
{
// NOTE: some platforms (e.g. OS X) do not support receiving IPv4 packet information for packets received
// on dual-mode sockets. On these platforms, this call is a no-op.
if (SupportsDualModeIPv4PacketInfo)
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
}
}
public static unsafe SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue)
{
if (optionLevel == SocketOptionLevel.Socket)
{
if (optionName == SocketOptionName.ReceiveTimeout)
{
optionValue = handle.ReceiveTimeout == -1 ? 0 : handle.ReceiveTimeout;
return SocketError.Success;
}
else if (optionName == SocketOptionName.SendTimeout)
{
optionValue = handle.SendTimeout == -1 ? 0 : handle.SendTimeout;
return SocketError.Success;
}
}
int value = 0;
int optLen = sizeof(int);
Interop.Error err = Interop.Sys.GetSockOpt(handle, optionLevel, optionName, (byte*)&value, &optLen);
optionValue = value;
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength)
{
int optLen = optionLength;
Interop.Error err;
if (optionValue == null || optionValue.Length == 0)
{
optLen = 0;
err = Interop.Sys.GetSockOpt(handle, optionLevel, optionName, null, &optLen);
}
else
{
fixed (byte* pinnedValue = optionValue)
{
err = Interop.Sys.GetSockOpt(handle, optionLevel, optionName, pinnedValue, &optLen);
}
}
if (err == Interop.Error.SUCCESS)
{
optionLength = optLen;
return SocketError.Success;
}
return GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError GetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out MulticastOption optionValue)
{
Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership, $"Unexpected optionName={optionName}");
Interop.Sys.MulticastOption optName = optionName == SocketOptionName.AddMembership ?
Interop.Sys.MulticastOption.MULTICAST_ADD :
Interop.Sys.MulticastOption.MULTICAST_DROP;
Interop.Sys.IPv4MulticastOption opt;
Interop.Error err = Interop.Sys.GetIPv4MulticastOption(handle, optName, &opt);
if (err != Interop.Error.SUCCESS)
{
optionValue = default(MulticastOption);
return GetSocketErrorForErrorCode(err);
}
var multicastAddress = new IPAddress((long)opt.MulticastAddress);
var localAddress = new IPAddress((long)opt.LocalAddress);
optionValue = new MulticastOption(multicastAddress, localAddress) {
InterfaceIndex = opt.InterfaceIndex
};
return SocketError.Success;
}
public static unsafe SocketError GetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
{
Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership, $"Unexpected optionName={optionName}");
Interop.Sys.MulticastOption optName = optionName == SocketOptionName.AddMembership ?
Interop.Sys.MulticastOption.MULTICAST_ADD :
Interop.Sys.MulticastOption.MULTICAST_DROP;
Interop.Sys.IPv6MulticastOption opt;
Interop.Error err = Interop.Sys.GetIPv6MulticastOption(handle, optName, &opt);
if (err != Interop.Error.SUCCESS)
{
optionValue = default(IPv6MulticastOption);
return GetSocketErrorForErrorCode(err);
}
optionValue = new IPv6MulticastOption(opt.Address.GetIPAddress(), opt.InterfaceIndex);
return SocketError.Success;
}
public static unsafe SocketError GetLingerOption(SafeCloseSocket handle, out LingerOption optionValue)
{
var opt = new Interop.Sys.LingerOption();
Interop.Error err = Interop.Sys.GetLingerOption(handle, &opt);
if (err != Interop.Error.SUCCESS)
{
optionValue = default(LingerOption);
return GetSocketErrorForErrorCode(err);
}
optionValue = new LingerOption(opt.OnOff != 0, opt.Seconds);
return SocketError.Success;
}
public static unsafe SocketError Poll(SafeCloseSocket handle, int microseconds, SelectMode mode, out bool status)
{
Interop.Sys.PollEvents inEvent = Interop.Sys.PollEvents.POLLNONE;
switch (mode)
{
case SelectMode.SelectRead: inEvent = Interop.Sys.PollEvents.POLLIN; break;
case SelectMode.SelectWrite: inEvent = Interop.Sys.PollEvents.POLLOUT; break;
case SelectMode.SelectError: inEvent = Interop.Sys.PollEvents.POLLPRI; break;
}
int milliseconds = microseconds == -1 ? -1 : microseconds / 1000;
Interop.Sys.PollEvents outEvents;
Interop.Error err = Interop.Sys.Poll(handle, inEvent, milliseconds, out outEvents);
if (err != Interop.Error.SUCCESS)
{
status = false;
return GetSocketErrorForErrorCode(err);
}
switch (mode)
{
case SelectMode.SelectRead: status = (outEvents & (Interop.Sys.PollEvents.POLLIN | Interop.Sys.PollEvents.POLLHUP)) != 0; break;
case SelectMode.SelectWrite: status = (outEvents & Interop.Sys.PollEvents.POLLOUT) != 0; break;
case SelectMode.SelectError: status = (outEvents & (Interop.Sys.PollEvents.POLLERR | Interop.Sys.PollEvents.POLLPRI)) != 0; break;
default: status = false; break;
}
return SocketError.Success;
}
public static unsafe SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
{
int checkReadInitialCount = checkRead != null ? checkRead.Count : 0;
int checkWriteInitialCount = checkWrite != null ? checkWrite.Count : 0;
int checkErrorInitialCount = checkError != null ? checkError.Count : 0;
int count = checked(checkReadInitialCount + checkWriteInitialCount + checkErrorInitialCount);
Debug.Assert(count > 0, $"Expected at least one entry.");
// Rather than using the select syscall, we use poll. While this has a mismatch in API from Select and
// requires some translation, it avoids the significant limitation of select only working with file descriptors
// less than FD_SETSIZE, and thus failing arbitrarily depending on the file descriptor value assigned
// by the system. Since poll then expects an array of entries, we try to allocate the array on the stack,
// only falling back to allocating it on the heap if it's deemed too big.
const int StackThreshold = 80; // arbitrary limit to avoid too much space on stack
if (count < StackThreshold)
{
Interop.Sys.PollEvent* eventsOnStack = stackalloc Interop.Sys.PollEvent[count];
return SelectViaPoll(
checkRead, checkReadInitialCount,
checkWrite, checkWriteInitialCount,
checkError, checkErrorInitialCount,
eventsOnStack, count, microseconds);
}
else
{
var eventsOnHeap = new Interop.Sys.PollEvent[count];
fixed (Interop.Sys.PollEvent* eventsOnHeapPtr = eventsOnHeap)
{
return SelectViaPoll(
checkRead, checkReadInitialCount,
checkWrite, checkWriteInitialCount,
checkError, checkErrorInitialCount,
eventsOnHeapPtr, count, microseconds);
}
}
}
private static unsafe SocketError SelectViaPoll(
IList checkRead, int checkReadInitialCount,
IList checkWrite, int checkWriteInitialCount,
IList checkError, int checkErrorInitialCount,
Interop.Sys.PollEvent* events, int eventsLength,
int microseconds)
{
// Add each of the list's contents to the events array
Debug.Assert(eventsLength == checkReadInitialCount + checkWriteInitialCount + checkErrorInitialCount, "Invalid eventsLength");
int offset = 0;
AddToPollArray(events, eventsLength, checkRead, ref offset, Interop.Sys.PollEvents.POLLIN | Interop.Sys.PollEvents.POLLHUP);
AddToPollArray(events, eventsLength, checkWrite, ref offset, Interop.Sys.PollEvents.POLLOUT);
AddToPollArray(events, eventsLength, checkError, ref offset, Interop.Sys.PollEvents.POLLPRI);
Debug.Assert(offset == eventsLength, $"Invalid adds. offset={offset}, eventsLength={eventsLength}.");
// Do the poll
uint triggered = 0;
int milliseconds = microseconds == -1 ? -1 : microseconds / 1000;
Interop.Error err = Interop.Sys.Poll(events, (uint)eventsLength, milliseconds, &triggered);
if (err != Interop.Error.SUCCESS)
{
return GetSocketErrorForErrorCode(err);
}
// Remove from the lists any entries which weren't set
if (triggered == 0)
{
checkRead?.Clear();
checkWrite?.Clear();
checkError?.Clear();
}
else
{
FilterPollList(checkRead, events, checkReadInitialCount - 1, Interop.Sys.PollEvents.POLLIN | Interop.Sys.PollEvents.POLLHUP);
FilterPollList(checkWrite, events, checkWriteInitialCount + checkReadInitialCount - 1, Interop.Sys.PollEvents.POLLOUT);
FilterPollList(checkError, events, checkErrorInitialCount + checkWriteInitialCount + checkReadInitialCount - 1, Interop.Sys.PollEvents.POLLERR | Interop.Sys.PollEvents.POLLPRI);
}
return SocketError.Success;
}
private static unsafe void AddToPollArray(Interop.Sys.PollEvent* arr, int arrLength, IList socketList, ref int arrOffset, Interop.Sys.PollEvents events)
{
if (socketList == null)
return;
int listCount = socketList.Count;
for (int i = 0; i < listCount; i++)
{
if (arrOffset >= arrLength)
{
Debug.Fail("IList.Count must have been faulty, returning a negative value and/or returning a different value across calls.");
throw new ArgumentOutOfRangeException(nameof(socketList));
}
Socket socket = socketList[i] as Socket;
if (socket == null)
{
throw new ArgumentException(SR.Format(SR.net_sockets_select, socket?.GetType().FullName ?? "null", typeof(Socket).FullName));
}
int fd = (int)socket.SafeHandle.DangerousGetHandle();
arr[arrOffset++] = new Interop.Sys.PollEvent { Events = events, FileDescriptor = fd };
}
}
private static unsafe void FilterPollList(IList socketList, Interop.Sys.PollEvent* arr, int arrEndOffset, Interop.Sys.PollEvents desiredEvents)
{
if (socketList == null)
return;
// The Select API requires leaving in the input lists only those sockets that were ready. As such, we need to loop
// through each poll event, and for each that wasn't ready, remove the corresponding Socket from its list. Technically
// this is O(n^2), due to removing from the list requiring shifting down all elements after it. However, this doesn't
// happen with the most common cases. If very few sockets were ready, then as we iterate from the end of the list, each
// removal will typically be O(1) rather than O(n). If most sockets were ready, then we only need to remove a few, in
// which case we're only doing a small number of O(n) shifts. It's only for the intermediate case, where a non-trivial
// number of sockets are ready and a non-trivial number of sockets are not ready that we end up paying the most. We could
// avoid these costs by, for example, allocating a side list that we fill with the sockets that should remain, clearing
// the original list, and then populating the original list with the contents of the side list. That of course has its
// own costs, and so for now we do the "simple" thing. This can be changed in the future as needed.
for (int i = socketList.Count - 1; i >= 0; --i, --arrEndOffset)
{
if (arrEndOffset < 0)
{
Debug.Fail("IList.Count must have been faulty, returning a negative value and/or returning a different value across calls.");
throw new ArgumentOutOfRangeException(nameof(arrEndOffset));
}
if ((arr[arrEndOffset].TriggeredEvents & desiredEvents) == 0)
{
socketList.RemoveAt(i);
}
}
}
public static SocketError Shutdown(SafeCloseSocket handle, bool isConnected, bool isDisconnected, SocketShutdown how)
{
Interop.Error err = Interop.Sys.Shutdown(handle, how);
if (err == Interop.Error.SUCCESS)
{
return SocketError.Success;
}
// If shutdown returns ENOTCONN and we think that this socket has ever been connected,
// ignore the error. This can happen for TCP connections if the underlying connection
// has reached the CLOSE state. Ignoring the error matches Winsock behavior.
if (err == Interop.Error.ENOTCONN && (isConnected || isDisconnected))
{
return SocketError.Success;
}
return GetSocketErrorForErrorCode(err);
}
public static SocketError ConnectAsync(Socket socket, SafeCloseSocket handle, byte[] socketAddress, int socketAddressLen, ConnectOverlappedAsyncResult asyncResult)
{
return handle.AsyncContext.ConnectAsync(socketAddress, socketAddressLen, asyncResult.CompletionCallback);
}
public static SocketError SendAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
return handle.AsyncContext.SendAsync(buffer, offset, count, socketFlags, asyncResult.CompletionCallback);
}
public static SocketError SendAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
return handle.AsyncContext.SendAsync(buffers, socketFlags, asyncResult.CompletionCallback);
}
public static SocketError SendToAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
asyncResult.SocketAddress = socketAddress;
return handle.AsyncContext.SendToAsync(buffer, offset, count, socketFlags, socketAddress.Buffer, socketAddress.Size, asyncResult.CompletionCallback);
}
public static SocketError ReceiveAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
return handle.AsyncContext.ReceiveAsync(buffer, offset, count, socketFlags, asyncResult.CompletionCallback);
}
public static SocketError ReceiveAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
return handle.AsyncContext.ReceiveAsync(buffers, socketFlags, asyncResult.CompletionCallback);
}
public static SocketError ReceiveFromAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
asyncResult.SocketAddress = socketAddress;
return handle.AsyncContext.ReceiveFromAsync(buffer, offset, count, socketFlags, socketAddress.Buffer, socketAddress.InternalSize, asyncResult.CompletionCallback);
}
public static SocketError ReceiveMessageFromAsync(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
{
asyncResult.SocketAddress = socketAddress;
bool isIPv4, isIPv6;
Socket.GetIPProtocolInformation(((Socket)asyncResult.AsyncObject).AddressFamily, socketAddress, out isIPv4, out isIPv6);
return handle.AsyncContext.ReceiveMessageFromAsync(buffer, offset, count, socketFlags, socketAddress.Buffer, socketAddress.InternalSize, isIPv4, isIPv6, asyncResult.CompletionCallback);
}
public static SocketError AcceptAsync(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
{
Debug.Assert(acceptHandle == null, $"Unexpected acceptHandle: {acceptHandle}");
Debug.Assert(receiveSize == 0, $"Unexpected receiveSize: {receiveSize}");
byte[] socketAddressBuffer = new byte[socketAddressSize];
return handle.AsyncContext.AcceptAsync(socketAddressBuffer, socketAddressSize, asyncResult.CompletionCallback);
}
}
}
| |
/**
* Copyright (c) 2015, GruntTheDivine 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 the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT ,STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
**/
using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using Iodine.Util;
namespace Iodine.Runtime
{
public class IodineBytes : IodineObject
{
public static readonly IodineTypeDefinition TypeDefinition = new BytesTypeDef ();
[BuiltinDocString (
"Returns a new Bytes instance, attempting to convert the supplied argument into a Bytes object.",
"@param value A value to convert into a bytes object."
)]
class BytesTypeDef : IodineTypeDefinition
{
public BytesTypeDef ()
: base ("Bytes")
{
}
public override IodineObject Invoke (VirtualMachine vm, IodineObject[] arguments)
{
if (arguments.Length <= 0) {
vm.RaiseException (new IodineArgumentException (1));
}
if (arguments [0] is IodineString) {
return new IodineBytes (arguments [0].ToString ());
}
var iter = arguments [0].GetIterator (vm);
iter.IterReset (vm);
var bytes = new List<byte> ();
while (iter.IterMoveNext (vm)) {
var current = iter.IterGetCurrent (vm);
long byteValue;
if (!MarshalUtil.MarshalAsInt64 (current, out byteValue)) {
vm.RaiseException (new IodineTypeException ("Int"));
return null;
}
bytes.Add ((byte)(byteValue & 0xFF));
}
return new IodineBytes (bytes.ToArray ());
}
public override IodineObject BindAttributes (IodineObject obj)
{
IodineIterableMixin.ApplyMixin (obj);
obj.SetAttribute ("contains", new BuiltinMethodCallback (Contains, obj));
obj.SetAttribute ("substr", new BuiltinMethodCallback (Substring, obj));
return obj;
}
IodineObject Contains (VirtualMachine vm, IodineObject self, IodineObject [] args)
{
var thisObj = self as IodineBytes;
if (thisObj == null) {
vm.RaiseException (new IodineFunctionInvocationException ());
return null;
}
if (args.Length == 0) {
vm.RaiseException (new IodineArgumentException (1));
return null;
}
var needle = args [0] as IodineBytes;
if (needle == null) {
vm.RaiseException (new IodineTypeException ("Bytes"));
return null;
}
for (int i = 0; i < thisObj.Value.Length; i++) {
bool found = true;
for (int sI = 0; sI < needle.Value.Length; sI++) {
if (needle.Value [sI] != thisObj.Value [i]) {
found = false;
break;
}
}
if (found) {
return IodineBool.True;
}
}
return IodineBool.False;
}
IodineObject Substring (VirtualMachine vm, IodineObject self, IodineObject [] args)
{
var thisObj = self as IodineBytes;
if (thisObj == null) {
vm.RaiseException (new IodineFunctionInvocationException ());
return null;
}
if (args.Length == 0) {
vm.RaiseException (new IodineArgumentException (1));
return null;
}
if (args.Length == 1) {
long startingIndex;
if (!MarshalUtil.MarshalAsInt64 (args [0], out startingIndex)) {
vm.RaiseException (new IodineTypeException ("Int"));
return null;
}
return Substring (vm, thisObj.Value, startingIndex);
} else {
long startingIndex;
long endingIndex;
if (!MarshalUtil.MarshalAsInt64 (args [0], out startingIndex) ||
!MarshalUtil.MarshalAsInt64 (args [1], out endingIndex)) {
vm.RaiseException (new IodineTypeException ("Int"));
return null;
}
return Substring (vm, thisObj.Value, startingIndex, endingIndex);
}
}
IodineObject Substring (VirtualMachine vm, byte [] value, long startingIndex)
{
byte [] newBytes = new byte [value.Length - (int)startingIndex];
int nI = 0;
for (int i = (int)startingIndex; i < newBytes.Length; i++) {
newBytes [nI++] = value [i];
}
return new IodineBytes (newBytes);
}
IodineObject Substring (VirtualMachine vm, byte [] value, long startingIndex, long endingIndex)
{
byte [] newBytes = new byte [(int)endingIndex];
int nI = 0;
for (int i = (int)startingIndex; nI < endingIndex; i++) {
newBytes [nI++] = value [i];
}
return new IodineBytes (newBytes);
}
}
class BytesIterator : IodineObject
{
static IodineTypeDefinition TypeDefinition = new IodineTypeDefinition ("BytesIterator");
byte [] value;
int iterIndex = 0;
public BytesIterator (byte[] value)
: base (TypeDefinition)
{
this.value = value;
}
public override IodineObject IterGetCurrent (VirtualMachine vm)
{
return new IodineInteger (value [iterIndex - 1]);
}
public override bool IterMoveNext (VirtualMachine vm)
{
if (iterIndex >= value.Length) {
return false;
}
iterIndex++;
return true;
}
public override void IterReset (VirtualMachine vm)
{
iterIndex = 0;
}
}
int iterIndex = 0;
public byte[] Value { private set; get; }
public IodineBytes ()
: base (TypeDefinition)
{
// HACK: Add __iter__ attribute to match Iterable trait
SetAttribute ("__iter__", new BuiltinMethodCallback ((VirtualMachine vm, IodineObject self, IodineObject [] args) => {
return GetIterator (vm);
}, this));
}
public IodineBytes (byte[] val)
: this ()
{
Value = val;
}
public IodineBytes (string val)
: this ()
{
Value = Encoding.ASCII.GetBytes (val);
}
public override IodineObject Represent (VirtualMachine vm)
{
return new IodineString (String.Format ("b'{0}'", Encoding.ASCII.GetString (Value)));
}
public override IodineObject Len (VirtualMachine vm)
{
return new IodineInteger (Value.Length);
}
public override IodineObject Add (VirtualMachine vm, IodineObject right)
{
var str = right as IodineBytes;
if (str == null) {
vm.RaiseException ("Right hand value must be of type Bytes!");
return null;
}
byte[] newArr = new byte[str.Value.Length + Value.Length];
Array.Copy (Value, newArr, Value.Length);
Array.Copy (str.Value, 0, newArr, Value.Length, str.Value.Length);
return new IodineBytes (newArr);
}
public override IodineObject Equals (VirtualMachine vm, IodineObject right)
{
var str = right as IodineBytes;
if (str == null) {
return base.Equals (vm, right);
}
return IodineBool.Create (Enumerable.SequenceEqual<byte> (str.Value, Value));
}
public override IodineObject NotEquals (VirtualMachine vm, IodineObject right)
{
var str = right as IodineBytes;
if (str == null) {
return base.NotEquals (vm, right);
}
return IodineBool.Create (!Enumerable.SequenceEqual<byte> (str.Value, Value));
}
public override string ToString ()
{
return Encoding.ASCII.GetString (Value);
}
public override int GetHashCode ()
{
return Value.GetHashCode ();
}
public override IodineObject GetIndex (VirtualMachine vm, IodineObject key)
{
var index = key as IodineInteger;
if (index == null) {
vm.RaiseException (new IodineTypeException ("Int"));
return null;
}
if (index.Value >= this.Value.Length) {
vm.RaiseException (new IodineIndexException ());
return null;
}
return new IodineInteger ((long)Value [(int)index.Value]);
}
public override IodineObject GetIterator (VirtualMachine vm)
{
return new BytesIterator (Value);
}
public override IodineObject IterGetCurrent (VirtualMachine vm)
{
return new IodineInteger ((long)Value [iterIndex - 1]);
}
public override bool IterMoveNext (VirtualMachine vm)
{
if (iterIndex >= Value.Length) {
return false;
}
iterIndex++;
return true;
}
public override void IterReset (VirtualMachine vm)
{
iterIndex = 0;
}
/**
* Iodine Function: Bytes.indexOf (self, value)
* Description: Returns the first position of value
*/
IodineObject IndexOf (VirtualMachine vm, IodineObject self, IodineObject [] args)
{
if (args.Length == 0) {
vm.RaiseException (new IodineArgumentException (1));
return null;
}
var val = ConvertToByte (args [0]);
if (val < 0) {
vm.RaiseException (new IodineTypeException ("Int"));
return null;
}
for (int i = 0; i < Value.Length; i++) {
if (Value [i] == val) {
return new IodineInteger (i);
}
}
return new IodineInteger (-1);
}
/**
* Iodine Function: Bytes.lastIndexOf (self, value)
* Description: Returns the last position of value
*/
IodineObject LastIndexOf (VirtualMachine vm, IodineObject self, IodineObject [] args)
{
if (args.Length == 0) {
vm.RaiseException (new IodineArgumentException (1));
return null;
}
var val = ConvertToByte (args [0]);
if (val < 0) {
vm.RaiseException (new IodineTypeException ("Int"));
return null;
}
int lastI = -1;
for (int i = 0; i < Value.Length; i++) {
if (Value [i] == val) {
lastI = i;
}
}
return new IodineInteger (lastI);
}
/**
* Iodine Function: Bytes.contains (self, value)
* Description: Returns true if this byte string contains value
*/
IodineObject Contains (VirtualMachine vm, IodineObject self, IodineObject [] args)
{
if (args.Length == 0) {
vm.RaiseException (new IodineArgumentException (1));
return null;
}
var needle = args [0] as IodineBytes;
if (needle == null) {
vm.RaiseException (new IodineTypeException ("Bytes"));
return null;
}
for (int i = 0; i < Value.Length; i++) {
bool found = true;
for (int sI = 0; sI < needle.Value.Length; sI++) {
if (needle.Value [sI] != Value [i]) {
found = false;
break;
}
}
if (found) {
return IodineBool.True;
}
}
return IodineBool.False;
}
static int ConvertToByte (IodineObject obj)
{
if (obj is IodineInteger) {
return (byte)((IodineInteger)obj).Value;
}
if (obj is IodineString) {
var val = obj.ToString ();
if (val.Length == 1) {
return (byte)val [0];
}
}
return -1;
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes the configuration of a Spot fleet request.
/// </summary>
public partial class SpotFleetRequestConfigData
{
private AllocationStrategy _allocationStrategy;
private string _clientToken;
private string _iamFleetRole;
private List<SpotFleetLaunchSpecification> _launchSpecifications = new List<SpotFleetLaunchSpecification>();
private string _spotPrice;
private int? _targetCapacity;
private bool? _terminateInstancesWithExpiration;
private DateTime? _validFrom;
private DateTime? _validUntil;
/// <summary>
/// Gets and sets the property AllocationStrategy.
/// <para>
/// Determines how to allocate the target capacity across the Spot pools specified by
/// the Spot fleet request. The default is <code>lowestPrice</code>.
/// </para>
/// </summary>
public AllocationStrategy AllocationStrategy
{
get { return this._allocationStrategy; }
set { this._allocationStrategy = value; }
}
// Check to see if AllocationStrategy property is set
internal bool IsSetAllocationStrategy()
{
return this._allocationStrategy != null;
}
/// <summary>
/// Gets and sets the property ClientToken.
/// <para>
/// A unique, case-sensitive identifier you provide to ensure idempotency of your listings.
/// This helps avoid duplicate listings. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html">Ensuring
/// Idempotency</a>.
/// </para>
/// </summary>
public string ClientToken
{
get { return this._clientToken; }
set { this._clientToken = value; }
}
// Check to see if ClientToken property is set
internal bool IsSetClientToken()
{
return this._clientToken != null;
}
/// <summary>
/// Gets and sets the property IamFleetRole.
/// <para>
/// Grants the Spot fleet permission to terminate Spot instances on your behalf when you
/// cancel its Spot fleet request using <a>CancelSpotFleetRequests</a> or when the Spot
/// fleet request expires, if you set <code>terminateInstancesWithExpiration</code>.
/// </para>
/// </summary>
public string IamFleetRole
{
get { return this._iamFleetRole; }
set { this._iamFleetRole = value; }
}
// Check to see if IamFleetRole property is set
internal bool IsSetIamFleetRole()
{
return this._iamFleetRole != null;
}
/// <summary>
/// Gets and sets the property LaunchSpecifications.
/// <para>
/// Information about the launch specifications for the Spot fleet request.
/// </para>
/// </summary>
public List<SpotFleetLaunchSpecification> LaunchSpecifications
{
get { return this._launchSpecifications; }
set { this._launchSpecifications = value; }
}
// Check to see if LaunchSpecifications property is set
internal bool IsSetLaunchSpecifications()
{
return this._launchSpecifications != null && this._launchSpecifications.Count > 0;
}
/// <summary>
/// Gets and sets the property SpotPrice.
/// <para>
/// The bid price per unit hour.
/// </para>
/// </summary>
public string SpotPrice
{
get { return this._spotPrice; }
set { this._spotPrice = value; }
}
// Check to see if SpotPrice property is set
internal bool IsSetSpotPrice()
{
return this._spotPrice != null;
}
/// <summary>
/// Gets and sets the property TargetCapacity.
/// <para>
/// The number of units to request. You can choose to set the target capacity in terms
/// of instances or a performance characteristic that is important to your application
/// workload, such as vCPUs, memory, or I/O.
/// </para>
/// </summary>
public int TargetCapacity
{
get { return this._targetCapacity.GetValueOrDefault(); }
set { this._targetCapacity = value; }
}
// Check to see if TargetCapacity property is set
internal bool IsSetTargetCapacity()
{
return this._targetCapacity.HasValue;
}
/// <summary>
/// Gets and sets the property TerminateInstancesWithExpiration.
/// <para>
/// Indicates whether running Spot instances should be terminated when the Spot fleet
/// request expires.
/// </para>
/// </summary>
public bool TerminateInstancesWithExpiration
{
get { return this._terminateInstancesWithExpiration.GetValueOrDefault(); }
set { this._terminateInstancesWithExpiration = value; }
}
// Check to see if TerminateInstancesWithExpiration property is set
internal bool IsSetTerminateInstancesWithExpiration()
{
return this._terminateInstancesWithExpiration.HasValue;
}
/// <summary>
/// Gets and sets the property ValidFrom.
/// <para>
/// The start date and time of the request, in UTC format (for example, <i>YYYY</i>-<i>MM</i>-<i>DD</i>T<i>HH</i>:<i>MM</i>:<i>SS</i>Z).
/// The default is to start fulfilling the request immediately.
/// </para>
/// </summary>
public DateTime ValidFrom
{
get { return this._validFrom.GetValueOrDefault(); }
set { this._validFrom = value; }
}
// Check to see if ValidFrom property is set
internal bool IsSetValidFrom()
{
return this._validFrom.HasValue;
}
/// <summary>
/// Gets and sets the property ValidUntil.
/// <para>
/// The end date and time of the request, in UTC format (for example, <i>YYYY</i>-<i>MM</i>-<i>DD</i>T<i>HH</i>:<i>MM</i>:<i>SS</i>Z).
/// At this point, no new Spot instance requests are placed or enabled to fulfill the
/// request.
/// </para>
/// </summary>
public DateTime ValidUntil
{
get { return this._validUntil.GetValueOrDefault(); }
set { this._validUntil = value; }
}
// Check to see if ValidUntil property is set
internal bool IsSetValidUntil()
{
return this._validUntil.HasValue;
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Implementation.Outlining;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.RQName;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal partial class VisualStudioSymbolNavigationService : ISymbolNavigationService
{
private readonly IServiceProvider _serviceProvider;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactory;
private readonly ITextEditorFactoryService _textEditorFactoryService;
private readonly ITextDocumentFactoryService _textDocumentFactoryService;
private readonly IMetadataAsSourceFileService _metadataAsSourceFileService;
private readonly OutliningTaggerProvider _outliningTaggerProvider;
public VisualStudioSymbolNavigationService(
SVsServiceProvider serviceProvider,
OutliningTaggerProvider outliningTaggerProvider)
{
_serviceProvider = serviceProvider;
_outliningTaggerProvider = outliningTaggerProvider;
var componentModel = GetService<SComponentModel, IComponentModel>();
_editorAdaptersFactory = componentModel.GetService<IVsEditorAdaptersFactoryService>();
_textEditorFactoryService = componentModel.GetService<ITextEditorFactoryService>();
_textDocumentFactoryService = componentModel.GetService<ITextDocumentFactoryService>();
_metadataAsSourceFileService = componentModel.GetService<IMetadataAsSourceFileService>();
}
public bool TryNavigateToSymbol(ISymbol symbol, Project project, bool usePreviewTab = false)
{
if (project == null || symbol == null)
{
return false;
}
symbol = symbol.OriginalDefinition;
// Prefer visible source locations if possible.
var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource);
var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
var sourceLocation = visibleSourceLocations.Any() ? visibleSourceLocations.First() : sourceLocations.FirstOrDefault();
if (sourceLocation != null)
{
var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
if (targetDocument != null)
{
var editorWorkspace = targetDocument.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
return navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, usePreviewTab);
}
}
// We don't have a source document, so show the Metadata as Source view in a preview tab.
var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();
if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
{
return false;
}
// Generate new source or retrieve existing source for the symbol in question
var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol).WaitAndGetResult(CancellationToken.None);
var vsRunningDocumentTable4 = GetService<SVsRunningDocumentTable, IVsRunningDocumentTable4>();
var fileAlreadyOpen = vsRunningDocumentTable4.IsMonikerValid((string)result.FilePath);
var openDocumentService = GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>();
IVsUIHierarchy hierarchy;
uint itemId;
IOleServiceProvider localServiceProvider;
IVsWindowFrame windowFrame;
openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out localServiceProvider, out hierarchy, out itemId, out windowFrame);
var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);
var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie);
var textBuffer = _editorAdaptersFactory.GetDataBuffer((IVsTextBuffer)vsTextBuffer);
if (!fileAlreadyOpen)
{
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
}
windowFrame.Show();
var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault();
if (openedDocument != null)
{
var editorWorkspace = openedDocument.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
return navigationService.TryNavigateToSpan(editorWorkspace, openedDocument.Id, result.IdentifierLocation.SourceSpan, usePreviewTab: true);
}
return true;
}
public bool TrySymbolNavigationNotify(ISymbol symbol, Solution solution)
{
foreach (var s in GetAllNavigationSymbols(symbol))
{
if (TryNotifyForSpecificSymbol(s, solution))
{
return true;
}
}
return false;
}
/// <summary>
/// If the symbol being navigated to is a constructor, then try navigating to the
/// constructor itself. If no third parties choose to navigate to the constructor, then try
/// the constructor's containing type.
/// </summary>
private IEnumerable<ISymbol> GetAllNavigationSymbols(ISymbol symbol)
{
yield return symbol;
if (symbol.IsConstructor())
{
yield return symbol.ContainingType;
}
}
private bool TryNotifyForSpecificSymbol(ISymbol symbol, Solution solution)
{
IVsHierarchy hierarchy;
IVsSymbolicNavigationNotify navigationNotify;
string rqname;
if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out hierarchy, out navigationNotify, out rqname))
{
return false;
}
int navigationHandled;
int returnCode = navigationNotify.OnBeforeNavigateToSymbol(
hierarchy,
(uint)VSConstants.VSITEMID.Nil,
rqname,
out navigationHandled);
if (returnCode == VSConstants.S_OK && navigationHandled == 1)
{
return true;
}
return false;
}
public bool WouldNavigateToSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset)
{
foreach (var s in GetAllNavigationSymbols(symbol))
{
if (WouldNotifyToSpecificSymbol(s, solution, out filePath, out lineNumber, out charOffset))
{
return true;
}
}
filePath = null;
lineNumber = 0;
charOffset = 0;
return false;
}
public bool WouldNotifyToSpecificSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset)
{
filePath = null;
lineNumber = 0;
charOffset = 0;
IVsHierarchy hierarchy;
IVsSymbolicNavigationNotify navigationNotify;
string rqname;
if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out hierarchy, out navigationNotify, out rqname))
{
return false;
}
IVsHierarchy navigateToHierarchy;
uint navigateToItem;
int wouldNavigate;
var navigateToTextSpan = new Microsoft.VisualStudio.TextManager.Interop.TextSpan[1];
int queryNavigateStatusCode = navigationNotify.QueryNavigateToSymbol(
hierarchy,
(uint)VSConstants.VSITEMID.Nil,
rqname,
out navigateToHierarchy,
out navigateToItem,
navigateToTextSpan,
out wouldNavigate);
if (queryNavigateStatusCode == VSConstants.S_OK && wouldNavigate == 1)
{
navigateToHierarchy.GetCanonicalName(navigateToItem, out filePath);
lineNumber = navigateToTextSpan[0].iStartLine;
charOffset = navigateToTextSpan[0].iStartIndex;
return true;
}
return false;
}
private bool TryGetNavigationAPIRequiredArguments(ISymbol symbol, Solution solution, out IVsHierarchy hierarchy, out IVsSymbolicNavigationNotify navigationNotify, out string rqname)
{
hierarchy = null;
navigationNotify = null;
rqname = null;
if (!symbol.Locations.Any() || !symbol.Locations[0].IsInSource)
{
return false;
}
var document = solution.GetDocument(symbol.Locations[0].SourceTree);
if (document == null)
{
return false;
}
hierarchy = GetVsHierarchy(document.Project);
navigationNotify = hierarchy as IVsSymbolicNavigationNotify;
if (navigationNotify == null)
{
return false;
}
return RQNameService.TryBuild(symbol, out rqname);
}
private IVsHierarchy GetVsHierarchy(Project project)
{
var visualStudioWorkspace = project.Solution.Workspace as VisualStudioWorkspaceImpl;
if (visualStudioWorkspace != null)
{
var hierarchy = visualStudioWorkspace.GetHierarchy(project.Id);
return hierarchy;
}
return null;
}
private I GetService<S, I>()
{
var service = (I)_serviceProvider.GetService(typeof(S));
Debug.Assert(service != null);
return service;
}
private IVsRunningDocumentTable GetRunningDocumentTable()
{
var runningDocumentTable = GetService<SVsRunningDocumentTable, IVsRunningDocumentTable>();
Debug.Assert(runningDocumentTable != null);
return runningDocumentTable;
}
}
}
| |
using System;
using System.Collections.Generic;
using Common;
using Fairweather.Service;
using Common.Sage;
namespace Common.Posting
{
public abstract class Sage_Collection : IReadWrite<string, object>, IRead<string, object>
{
protected abstract T Get<T>(string field);
protected abstract void Set<T>(string field, T value);
public abstract bool Contains(string field);
public object this[string field] {
get {
return Get<object>(field);
}
set {
Set<object>(field, value);
}
}
public void Add(string field, object obj) {
this[field] = obj;
}
public bool Same_Header(Sage_Collection other) {
other.tifn();
return this.ACCOUNT_REF == other.ACCOUNT_REF && !other.ACCOUNT_REF.IsNullOrEmpty()
&& this.TYPE == other.TYPE && !other.TYPE.IsNullOrEmpty()
&& this.DATE == other.DATE && !other.DATE.IsNullOrEmpty()
&& this.INV_REF == other.INV_REF && !other.INV_REF.IsNullOrEmpty();
//&& this.NOMINAL_CODE == other.NOMINAL_CODE && ! other.NOMINAL_CODE.IsNullOrEmpty()
//&& this.BANK_CODE == other.BANK_CODE && ! other.BANK_CODE.IsNullOrEmpty()
}
public string Clean(string key) {
return this[key].strdef().Trim().ToUpper();
}
#region CONSTANTS
const string CST_PROJ_REF = "PROJ_REF";
const string CST_COST_CODE = "COST_CODE";
const string CST_DATE = "DATE";
const string CST_UNIQUE_REF = "UNIQUE_REF";
const string CST_ACCOUNT_TYPE = "ACCOUNT_TYPE";
const string CST_ACCOUNT_REF = "ACCOUNT_REF";
const string CST_NOMINAL_CODE = "NOMINAL_CODE";
const string CST_STOCK_CODE = "STOCK_CODE";
const string CST_ADDRESS_1 = "ADDRESS_1";
const string CST_ADDRESS_2 = "ADDRESS_2";
const string CST_ADDRESS_3 = "ADDRESS_3";
const string CST_ADDRESS_4 = "ADDRESS_4";
const string CST_ADDRESS_5 = "ADDRESS_5";
const string CST_LAST_CHEQUE = "LAST_CHEQUE";
const string CST_TELEPHONE = "TELEPHONE";
const string CST_PRINTED_FLAG = "PRINTED_FLAG";
const string CST_FAX = "FAX";
const string CST_AMOUNT_PAID = "AMOUNT_PAID";
const string CST_AMOUNT_PREPAID = "AMOUNT_PREPAID";
const string CST_BANK_CODE = "BANK_CODE";
const string CST_BASE_AMOUNT_PAID = "BASE_AMOUNT_PAID";
const string CST_BASE_CURRENCY = "BASE_CURRENCY";
const string CST_BASE_TOT_NET = "BASE_TOT_NET";
const string CST_BASE_TOT_TAX = "BASE_TOT_TAX";
const string CST_CONTACT_NAME = "CONTACT_NAME";
const string CST_CUST_ORDER_NUMBER = "CUST_ORDER_NUMBER";
const string CST_CUST_TEL_NUMBER = "CUST_TEL_NUMBER";
const string CST_DEF_TAX_CODE = "DEF_TAX_CODE";
const string CST_DEL_ADDRESS = "DEL_ADDRESS";
const string CST_DEL_ADDRESS_1 = "DEL_ADDRESS_1";
const string CST_DEL_ADDRESS_2 = "DEL_ADDRESS_2";
const string CST_DEL_ADDRESS_3 = "DEL_ADDRESS_3";
const string CST_DEL_ADDRESS_4 = "DEL_ADDRESS_4";
const string CST_DEL_ADDRESS_5 = "DEL_ADDRESS_5";
const string CST_DELETED_FLAG = "DELETED_FLAG";
const string CST_DELIVERY_NAME = "DELIVERY_NAME";
const string CST_DEPT_NUMBER = "DEPT_NUMBER";
const string CST_DESCRIPTION = "DESCRIPTION";
const string CST_DETAILS = "DETAILS";
const string CST_DISCOUNT_AMOUNT = "DISCOUNT_AMOUNT";
const string CST_DISCOUNT_RATE = "DISCOUNT_RATE";
const string CST_FULL_NET_AMOUNT = "FULL_NET_AMOUNT";
const string CST_INV_REF = "INV_REF";
const string CST_INVOICE_DATE = "INVOICE_DATE";
const string CST_INVOICE_NUMBER = "INVOICE_NUMBER";
const string CST_INVOICE_TYPE_CODE = "INVOICE_TYPE_CODE";
const string CST_ITEMS_NET = "ITEMS_NET";
const string CST_ITEMS_TAX = "ITEMS_TAX";
const string CST_LAST_SPLIT = "LAST_SPLIT";
const string CST_NAME = "NAME";
const string CST_NET_AMOUNT = "NET_AMOUNT";
const string CST_NOTES_1 = "NOTES_1";
const string CST_NOTES_2 = "NOTES_2";
const string CST_NOTES_3 = "NOTES_3";
const string CST_ORDER_NUMBER = "ORDER_NUMBER";
const string CST_PAYMENT_TYPE = "PAYMENT_TYPE";
const string CST_POSTED_CODE = "POSTED_CODE";
const string CST_PRINTED_CODE = "PRINTED_CODE";
const string CST_POSTED_DATE = "POSTED_DATE";
const string CST_QTY_ORDER = "QTY_ORDER";
const string CST_QTY = "QTY";
const string CST_SALES_PRICE = "SALES_PRICE";
const string CST_SETTLED = "SETTLED";
const string CST_STOCK_CAT = "STOCK_CAT";
// Stock Quantity Decimal Precision
const string CST_STOCK_QTYDP = "STOCK_QTYDP";
// Stock Unit Decimal Precision
const string CST_STOCK_UNITDP = "STOCK_UNITDP";
const string CST_TAKEN_BY = "TAKEN_BY";
const string CST_TAX_AMOUNT = "TAX_AMOUNT";
const string CST_TAX_CODE = "TAX_CODE";
const string CST_TAX_RATE = "TAX_RATE";
const string CST_INTERNAL_REF = "INTERNAL_REF";
const string CST_COST_PRICE = "COST_PRICE";
const string CST_TYPE = "TYPE";
const string CST_UNIT_OF_SALE = "UNIT_OF_SALE";
const string CST_UNIT_PRICE = "UNIT_PRICE";
const string CST_USER_NAME = "USER_NAME";
const string CST_BANK = "BANK";
const string CST_GROSS_AMOUNT = "GROSS_AMOUNT";
const string CST_INDEX = "INDEX";
const string CST_LASTLINE_FLAG = "LASTLINE_FLAG";
const string CST_PAYMENT_AMOUNT = "PAYMENT_AMOUNT";
const string CST_PAYMENT_DATE = "PAYMENT_DATE";
const string CST_PAYMENT_FLAG = "PAYMENT_FLAG";
const string CST_PAYMENT_NO = "PAYMENT_NO";
const string CST_TRAN_TYPE = "TRAN_TYPE";
const string CST_URN = "URN";
const string CST_VAT_AMOUNT = "VAT_AMOUNT";
const string CST_COUNTRY_NAME = "COUNTRY_NAME";
const string CST_COUNTRY_CODE = "COUNTRY_CODE";
const string CST_VAT_FORMAT_1 = "VAT_FORMAT_1";
const string CST_VAT_FORMAT_2 = "VAT_FORMAT_2";
const string CST_VAT_FORMAT_3 = "VAT_FORMAT_3";
const string CST_VAT_FORMAT_4 = "VAT_FORMAT_4";
const string CST_VAT_FORMAT_5 = "VAT_FORMAT_5";
const string CST_HEADER_NUMBER = "HEADER_NUMBER";
const string CST_WIZ_START_SPLITS = "WIZ_START_SPLITS";
const string CST_FINYEAR_MONTH = "FINYEAR_MONTH";
const string CST_FINYEAR_YEAR = "FINYEAR_YEAR";
const string CST_EXCHANGE_RATE = "EXCHANGE_RATE";
const string CST_MINOR_UNIT = "MINOR_UNIT";
const string CST_MAJOR_UNIT = "MAJOR_UNIT";
const string CST_CODE = "CODE";
const string CST_SYMBOL = "SYMBOL";
const string CST_ACCOUNT_NUMBER = "ACCOUNT_NUMBER";
const string CST_CURRENCY = "CURRENCY";
const string CST_STATUS = "STATUS";
const string CST_FIRST_SPLIT = "FIRST_SPLIT";
const string CST_NO_OF_SPLIT = "NO_OF_SPLIT";
const string CST_NO_OF_HEADER = "NO_OF_HEADER";
const string CST_SDISCOUNT_NO = "SDISCOUNT_NO";
const string CST_PDISCOUNT_NO = "PDISCOUNT_NO";
const string CST_RECORD_NUMBER = "RECORD_NUMBER";
const string CST_LAST_PAY_DATE = "LAST_PAY_DATE";
const string CST_BASE_FULL_NET = "BASE_FULL_NET";
const string CST_BASE_NET = "BASE_NET";
const string CST_BASE_NETVALUE_DISCOUNT = "BASE_NETVALUE_DISCOUNT";
const string CST_NETVALUE_DISCOUNT = "NETVALUE_DISCOUNT";
const string CST_ITEM_NUMBER = "ITEM_NUMBER";
const string CST_ADD_DISC_RATE = "ADD_DISC_RATE";
const string CST_QTY_IN_STOCK = "QTY_IN_STOCK";
const string CST_REFERENCE = "REFERENCE";
const string CST_QUANTITY = "QUANTITY";
#endregion
// C:\Users\Fairweather\Desktop\temp.pl
#region PROPERTIES
public int ACCOUNT_NUMBER {
get {
return Get<int>(CST_ACCOUNT_NUMBER);
}
set {
Set(CST_ACCOUNT_NUMBER, value);
}
}
public string ACCOUNT_REF {
get {
return Get<string>(CST_ACCOUNT_REF);
}
set {
Set(CST_ACCOUNT_REF, value);
}
}
public string ACCOUNT_TYPE {
get {
return Get<string>(CST_ACCOUNT_TYPE);
}
set {
Set(CST_ACCOUNT_TYPE, value);
}
}
public string ADDRESS_1 {
get {
return Get<string>(CST_ADDRESS_1);
}
set {
Set(CST_ADDRESS_1, value);
}
}
public string ADDRESS_2 {
get {
return Get<string>(CST_ADDRESS_2);
}
set {
Set(CST_ADDRESS_2, value);
}
}
public string ADDRESS_3 {
get {
return Get<string>(CST_ADDRESS_3);
}
set {
Set(CST_ADDRESS_3, value);
}
}
public string ADDRESS_4 {
get {
return Get<string>(CST_ADDRESS_4);
}
set {
Set(CST_ADDRESS_4, value);
}
}
public string ADDRESS_5 {
get {
return Get<string>(CST_ADDRESS_5);
}
set {
Set(CST_ADDRESS_5, value);
}
}
public decimal ADD_DISC_RATE {
get {
return Get<decimal>(CST_ADD_DISC_RATE);
}
set {
Set(CST_ADD_DISC_RATE, value);
}
}
public decimal AMOUNT_PAID {
get {
return Get<decimal>(CST_AMOUNT_PAID);
}
set {
Set(CST_AMOUNT_PAID, value);
}
}
public decimal AMOUNT_PREPAID {
get {
return Get<decimal>(CST_AMOUNT_PREPAID);
}
set {
Set(CST_AMOUNT_PREPAID, value);
}
}
public string BANK {
get {
return Get<string>(CST_BANK);
}
set {
Set(CST_BANK, value);
}
}
public string BANK_CODE {
get {
return Get<string>(CST_BANK_CODE);
}
set {
Set(CST_BANK_CODE, value);
}
}
public decimal BASE_AMOUNT_PAID {
get {
return Get<decimal>(CST_BASE_AMOUNT_PAID);
}
set {
Set(CST_BASE_AMOUNT_PAID, value);
}
}
public string BASE_CURRENCY {
get {
return Get<string>(CST_BASE_CURRENCY);
}
set {
Set(CST_BASE_CURRENCY, value);
}
}
public decimal BASE_FULL_NET {
get {
return Get<decimal>(CST_BASE_FULL_NET);
}
set {
Set(CST_BASE_FULL_NET, value);
}
}
public decimal BASE_NET {
get {
return Get<decimal>(CST_BASE_NET);
}
set {
Set(CST_BASE_NET, value);
}
}
public decimal BASE_NETVALUE_DISCOUNT {
get {
return Get<decimal>(CST_BASE_NETVALUE_DISCOUNT);
}
set {
Set(CST_BASE_NETVALUE_DISCOUNT, value);
}
}
public decimal BASE_TOT_NET {
get {
return Get<decimal>(CST_BASE_TOT_NET);
}
set {
Set(CST_BASE_TOT_NET, value);
}
}
public string BASE_TOT_TAX {
get {
return Get<string>(CST_BASE_TOT_TAX);
}
set {
Set(CST_BASE_TOT_TAX, value);
}
}
public string CODE {
get {
return Get<string>(CST_CODE);
}
set {
Set(CST_CODE, value);
}
}
public string CONTACT_NAME {
get {
return Get<string>(CST_CONTACT_NAME);
}
set {
Set(CST_CONTACT_NAME, value);
}
}
public string COST_CODE {
get {
return Get<string>(CST_COST_CODE);
}
set {
Set(CST_COST_CODE, value);
}
}
public decimal COST_PRICE {
get {
return Get<decimal>(CST_COST_PRICE);
}
set {
Set(CST_COST_PRICE, value);
}
}
public string COUNTRY_CODE {
get {
return Get<string>(CST_COUNTRY_CODE);
}
set {
Set(CST_COUNTRY_CODE, value);
}
}
public string COUNTRY_NAME {
get {
return Get<string>(CST_COUNTRY_NAME);
}
set {
Set(CST_COUNTRY_NAME, value);
}
}
public string CURRENCY {
get {
return Get<string>(CST_CURRENCY);
}
set {
Set(CST_CURRENCY, value);
}
}
public int CUST_ORDER_NUMBER {
get {
return Get<int>(CST_CUST_ORDER_NUMBER);
}
set {
Set(CST_CUST_ORDER_NUMBER, value);
}
}
public int CUST_TEL_NUMBER {
get {
return Get<int>(CST_CUST_TEL_NUMBER);
}
set {
Set(CST_CUST_TEL_NUMBER, value);
}
}
public DateTime DATE {
get {
return Get<DateTime>(CST_DATE);
}
set {
Set(CST_DATE, value);
}
}
public string DEF_TAX_CODE {
get {
return Get<string>(CST_DEF_TAX_CODE);
}
set {
Set(CST_DEF_TAX_CODE, value);
}
}
public bool DELETED_FLAG {
get {
return Get<bool>(CST_DELETED_FLAG);
}
set {
Set(CST_DELETED_FLAG, value);
}
}
public string DELIVERY_NAME {
get {
return Get<string>(CST_DELIVERY_NAME);
}
set {
Set(CST_DELIVERY_NAME, value);
}
}
public string DEL_ADDRESS {
get {
return Get<string>(CST_DEL_ADDRESS);
}
set {
Set(CST_DEL_ADDRESS, value);
}
}
public string DEL_ADDRESS_1 {
get {
return Get<string>(CST_DEL_ADDRESS_1);
}
set {
Set(CST_DEL_ADDRESS_1, value);
}
}
public string DEL_ADDRESS_2 {
get {
return Get<string>(CST_DEL_ADDRESS_2);
}
set {
Set(CST_DEL_ADDRESS_2, value);
}
}
public string DEL_ADDRESS_3 {
get {
return Get<string>(CST_DEL_ADDRESS_3);
}
set {
Set(CST_DEL_ADDRESS_3, value);
}
}
public string DEL_ADDRESS_4 {
get {
return Get<string>(CST_DEL_ADDRESS_4);
}
set {
Set(CST_DEL_ADDRESS_4, value);
}
}
public string DEL_ADDRESS_5 {
get {
return Get<string>(CST_DEL_ADDRESS_5);
}
set {
Set(CST_DEL_ADDRESS_5, value);
}
}
public int DEPT_NUMBER {
get {
return Get<int>(CST_DEPT_NUMBER);
}
set {
Set(CST_DEPT_NUMBER, value);
}
}
public string DESCRIPTION {
get {
return Get<string>(CST_DESCRIPTION);
}
set {
Set(CST_DESCRIPTION, value);
}
}
public string DETAILS {
get {
return Get<string>(CST_DETAILS);
}
set {
Set(CST_DETAILS, value);
}
}
public decimal DISCOUNT_AMOUNT {
get {
return Get<decimal>(CST_DISCOUNT_AMOUNT);
}
set {
Set(CST_DISCOUNT_AMOUNT, value);
}
}
public decimal DISCOUNT_RATE {
get {
return Get<decimal>(CST_DISCOUNT_RATE);
}
set {
Set(CST_DISCOUNT_RATE, value);
}
}
public decimal EXCHANGE_RATE {
get {
return Get<decimal>(CST_EXCHANGE_RATE);
}
set {
Set(CST_EXCHANGE_RATE, value);
}
}
public string FAX {
get {
return Get<string>(CST_FAX);
}
set {
Set(CST_FAX, value);
}
}
public int FINYEAR_MONTH {
get {
return Get<int>(CST_FINYEAR_MONTH);
}
set {
Set(CST_FINYEAR_MONTH, value);
}
}
public int FINYEAR_YEAR {
get {
return Get<int>(CST_FINYEAR_YEAR);
}
set {
Set(CST_FINYEAR_YEAR, value);
}
}
public int FIRST_SPLIT {
get {
return Get<int>(CST_FIRST_SPLIT);
}
set {
Set(CST_FIRST_SPLIT, value);
}
}
public decimal FULL_NET_AMOUNT {
get {
return Get<decimal>(CST_FULL_NET_AMOUNT);
}
set {
Set(CST_FULL_NET_AMOUNT, value);
}
}
public decimal GROSS_AMOUNT {
get {
return Get<decimal>(CST_GROSS_AMOUNT);
}
set {
Set(CST_GROSS_AMOUNT, value);
}
}
public int HEADER_NUMBER {
get {
return Get<int>(CST_HEADER_NUMBER);
}
set {
Set(CST_HEADER_NUMBER, value);
}
}
public string INDEX {
get {
return Get<string>(CST_INDEX);
}
set {
Set(CST_INDEX, value);
}
}
public string INTERNAL_REF {
get {
return Get<string>(CST_INTERNAL_REF);
}
set {
Set(CST_INTERNAL_REF, value);
}
}
public DateTime INVOICE_DATE {
get {
return Get<DateTime>(CST_INVOICE_DATE);
}
set {
Set(CST_INVOICE_DATE, value);
}
}
public int INVOICE_NUMBER {
get {
return Get<int>(CST_INVOICE_NUMBER);
}
set {
Set(CST_INVOICE_NUMBER, value);
}
}
public string INVOICE_TYPE_CODE {
get {
return Get<string>(CST_INVOICE_TYPE_CODE);
}
set {
Set(CST_INVOICE_TYPE_CODE, value);
}
}
public string INV_REF {
get {
return Get<string>(CST_INV_REF);
}
set {
Set(CST_INV_REF, value);
}
}
public decimal ITEMS_NET {
get {
return Get<decimal>(CST_ITEMS_NET);
}
set {
Set(CST_ITEMS_NET, value);
}
}
public string ITEMS_TAX {
get {
return Get<string>(CST_ITEMS_TAX);
}
set {
Set(CST_ITEMS_TAX, value);
}
}
public int ITEM_NUMBER {
get {
return Get<int>(CST_ITEM_NUMBER);
}
set {
Set(CST_ITEM_NUMBER, value);
}
}
public bool LASTLINE_FLAG {
get {
return Get<bool>(CST_LASTLINE_FLAG);
}
set {
Set(CST_LASTLINE_FLAG, value);
}
}
public string LAST_CHEQUE {
get {
return Get<string>(CST_LAST_CHEQUE);
}
set {
Set(CST_LAST_CHEQUE, value);
}
}
public DateTime LAST_PAY_DATE {
get {
return Get<DateTime>(CST_LAST_PAY_DATE);
}
set {
Set(CST_LAST_PAY_DATE, value);
}
}
public int LAST_SPLIT {
get {
return Get<int>(CST_LAST_SPLIT);
}
set {
Set(CST_LAST_SPLIT, value);
}
}
public string MAJOR_UNIT {
get {
return Get<string>(CST_MAJOR_UNIT);
}
set {
Set(CST_MAJOR_UNIT, value);
}
}
public string MINOR_UNIT {
get {
return Get<string>(CST_MINOR_UNIT);
}
set {
Set(CST_MINOR_UNIT, value);
}
}
public string NAME {
get {
return Get<string>(CST_NAME);
}
set {
Set(CST_NAME, value);
}
}
public decimal NETVALUE_DISCOUNT {
get {
return Get<decimal>(CST_NETVALUE_DISCOUNT);
}
set {
Set(CST_NETVALUE_DISCOUNT, value);
}
}
public decimal NET_AMOUNT {
get {
return Get<decimal>(CST_NET_AMOUNT);
}
set {
Set(CST_NET_AMOUNT, value);
}
}
public string NOMINAL_CODE {
get {
return Get<string>(CST_NOMINAL_CODE);
}
set {
Set(CST_NOMINAL_CODE, value);
}
}
public string NOTES_1 {
get {
return Get<string>(CST_NOTES_1);
}
set {
Set(CST_NOTES_1, value);
}
}
public string NOTES_2 {
get {
return Get<string>(CST_NOTES_2);
}
set {
Set(CST_NOTES_2, value);
}
}
public string NOTES_3 {
get {
return Get<string>(CST_NOTES_3);
}
set {
Set(CST_NOTES_3, value);
}
}
public int NO_OF_HEADER {
get {
return Get<int>(CST_NO_OF_HEADER);
}
set {
Set(CST_NO_OF_HEADER, value);
}
}
public int NO_OF_SPLIT {
get {
return Get<int>(CST_NO_OF_SPLIT);
}
set {
Set(CST_NO_OF_SPLIT, value);
}
}
public int ORDER_NUMBER {
get {
return Get<int>(CST_ORDER_NUMBER);
}
set {
Set(CST_ORDER_NUMBER, value);
}
}
public decimal PAYMENT_AMOUNT {
get {
return Get<decimal>(CST_PAYMENT_AMOUNT);
}
set {
Set(CST_PAYMENT_AMOUNT, value);
}
}
public DateTime PAYMENT_DATE {
get {
return Get<DateTime>(CST_PAYMENT_DATE);
}
set {
Set(CST_PAYMENT_DATE, value);
}
}
public bool PAYMENT_FLAG {
get {
return Get<bool>(CST_PAYMENT_FLAG);
}
set {
Set(CST_PAYMENT_FLAG, value);
}
}
public string PAYMENT_NO {
get {
return Get<string>(CST_PAYMENT_NO);
}
set {
Set(CST_PAYMENT_NO, value);
}
}
public Versioning.TransType PAYMENT_TYPE {
get {
return Get<Versioning.TransType>(CST_PAYMENT_TYPE);
}
set {
Set(CST_PAYMENT_TYPE, value);
}
}
public string PDISCOUNT_NO {
get {
return Get<string>(CST_PDISCOUNT_NO);
}
set {
Set(CST_PDISCOUNT_NO, value);
}
}
public string POSTED_CODE {
get {
return Get<string>(CST_POSTED_CODE);
}
set {
Set(CST_POSTED_CODE, value);
}
}
public DateTime POSTED_DATE {
get {
return Get<DateTime>(CST_POSTED_DATE);
}
set {
Set(CST_POSTED_DATE, value);
}
}
public string PRINTED_CODE {
get {
return Get<string>(CST_PRINTED_CODE);
}
set {
Set(CST_PRINTED_CODE, value);
}
}
public bool PRINTED_FLAG {
get {
return Get<bool>(CST_PRINTED_FLAG);
}
set {
Set(CST_PRINTED_FLAG, value);
}
}
public string PROJ_REF {
get {
return Get<string>(CST_PROJ_REF);
}
set {
Set(CST_PROJ_REF, value);
}
}
public decimal QTY {
get {
return Get<decimal>(CST_QTY);
}
set {
Set(CST_QTY, value);
}
}
public decimal QTY_IN_STOCK {
get {
return Get<decimal>(CST_QTY_IN_STOCK);
}
set {
Set(CST_QTY_IN_STOCK, value);
}
}
public decimal QTY_ORDER {
get {
return Get<decimal>(CST_QTY_ORDER);
}
set {
Set(CST_QTY_ORDER, value);
}
}
public int QUANTITY {
get {
return Get<int>(CST_QUANTITY);
}
set {
Set(CST_QUANTITY, value);
}
}
public int RECORD_NUMBER {
get {
return Get<int>(CST_RECORD_NUMBER);
}
set {
Set(CST_RECORD_NUMBER, value);
}
}
public string REFERENCE {
get {
return Get<string>(CST_REFERENCE);
}
set {
Set(CST_REFERENCE, value);
}
}
public decimal SALES_PRICE {
get {
return Get<decimal>(CST_SALES_PRICE);
}
set {
Set(CST_SALES_PRICE, value);
}
}
public string SDISCOUNT_NO {
get {
return Get<string>(CST_SDISCOUNT_NO);
}
set {
Set(CST_SDISCOUNT_NO, value);
}
}
public bool SETTLED {
get {
return Get<bool>(CST_SETTLED);
}
set {
Set(CST_SETTLED, value);
}
}
public string STATUS {
get {
return Get<string>(CST_STATUS);
}
set {
Set(CST_STATUS, value);
}
}
public string STOCK_CAT {
get {
return Get<string>(CST_STOCK_CAT);
}
set {
Set(CST_STOCK_CAT, value);
}
}
public string STOCK_CODE {
get {
return Get<string>(CST_STOCK_CODE);
}
set {
Set(CST_STOCK_CODE, value);
}
}
public decimal STOCK_QTYDP {
get {
return Get<decimal>(CST_STOCK_QTYDP);
}
set {
Set(CST_STOCK_QTYDP, value);
}
}
public int STOCK_UNITDP {
get {
return Get<int>(CST_STOCK_UNITDP);
}
set {
Set(CST_STOCK_UNITDP, value);
}
}
public string SYMBOL {
get {
return Get<string>(CST_SYMBOL);
}
set {
Set(CST_SYMBOL, value);
}
}
public string TAKEN_BY {
get {
return Get<string>(CST_TAKEN_BY);
}
set {
Set(CST_TAKEN_BY, value);
}
}
public decimal TAX_AMOUNT {
get {
return Get<decimal>(CST_TAX_AMOUNT);
}
set {
Set(CST_TAX_AMOUNT, value);
}
}
public short TAX_CODE {
get {
return Get<short>(CST_TAX_CODE);
}
set {
Set(CST_TAX_CODE, value);
}
}
public decimal TAX_RATE {
get {
return Get<decimal>(CST_TAX_RATE);
}
set {
Set(CST_TAX_RATE, value);
}
}
public string TELEPHONE {
get {
return Get<string>(CST_TELEPHONE);
}
set {
Set(CST_TELEPHONE, value);
}
}
public Versioning.StockTransType TRAN_TYPE {
get {
return Get<Versioning.StockTransType>(CST_TRAN_TYPE);
}
set {
Set(CST_TRAN_TYPE, value);
}
}
public Versioning.InvoiceType INVOICE_TYPE {
get {
return Get<Versioning.InvoiceType>(CST_INVOICE_TYPE_CODE);
}
set {
Set(CST_INVOICE_TYPE_CODE, value);
}
}
public Versioning.TransType TYPE {
get {
return Get<Versioning.TransType>(CST_TYPE);
}
set {
Set(CST_TYPE, value);
}
}
public Versioning.StockTransType ST_TYPE {
get {
return Get<Versioning.StockTransType>(CST_TYPE);
}
set {
Set(CST_TYPE, value);
}
}
public string UNIQUE_REF {
get {
return Get<string>(CST_UNIQUE_REF);
}
set {
Set(CST_UNIQUE_REF, value);
}
}
public string UNIT_OF_SALE {
get {
return Get<string>(CST_UNIT_OF_SALE);
}
set {
Set(CST_UNIT_OF_SALE, value);
}
}
public decimal UNIT_PRICE {
get {
return Get<decimal>(CST_UNIT_PRICE);
}
set {
Set(CST_UNIT_PRICE, value);
}
}
public string URN {
get {
return Get<string>(CST_URN);
}
set {
Set(CST_URN, value);
}
}
public string USER_NAME {
get {
return Get<string>(CST_USER_NAME);
}
set {
Set(CST_USER_NAME, value);
}
}
public decimal VAT_AMOUNT {
get {
return Get<decimal>(CST_VAT_AMOUNT);
}
set {
Set(CST_VAT_AMOUNT, value);
}
}
public string VAT_FORMAT_1 {
get {
return Get<string>(CST_VAT_FORMAT_1);
}
set {
Set(CST_VAT_FORMAT_1, value);
}
}
public string VAT_FORMAT_2 {
get {
return Get<string>(CST_VAT_FORMAT_2);
}
set {
Set(CST_VAT_FORMAT_2, value);
}
}
public string VAT_FORMAT_3 {
get {
return Get<string>(CST_VAT_FORMAT_3);
}
set {
Set(CST_VAT_FORMAT_3, value);
}
}
public string VAT_FORMAT_4 {
get {
return Get<string>(CST_VAT_FORMAT_4);
}
set {
Set(CST_VAT_FORMAT_4, value);
}
}
public string VAT_FORMAT_5 {
get {
return Get<string>(CST_VAT_FORMAT_5);
}
set {
Set(CST_VAT_FORMAT_5, value);
}
}
public int WIZ_START_SPLITS {
get {
return Get<int>(CST_WIZ_START_SPLITS);
}
set {
Set(CST_WIZ_START_SPLITS, value);
}
}
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.Slippage;
using QuantConnect.Securities;
using QuantConnect.Securities.Equity;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
using QuantConnect.Util;
namespace QuantConnect.Brokerages
{
/// <summary>
/// Provides a default implementation of <see cref="IBrokerageModel"/> that allows all orders and uses
/// the default transaction models
/// </summary>
public class DefaultBrokerageModel : IBrokerageModel
{
/// <summary>
/// The default markets for the backtesting brokerage
/// </summary>
public static readonly IReadOnlyDictionary<SecurityType, string> DefaultMarketMap = new Dictionary<SecurityType, string>
{
{SecurityType.Base, Market.USA},
{SecurityType.Equity, Market.USA},
{SecurityType.Option, Market.USA},
{SecurityType.Future, Market.USA},
{SecurityType.Forex, Market.FXCM},
{SecurityType.Cfd, Market.FXCM},
{SecurityType.Crypto, Market.GDAX}
}.ToReadOnlyDictionary();
/// <summary>
/// Gets or sets the account type used by this model
/// </summary>
public virtual AccountType AccountType
{
get;
private set;
}
/// <summary>
/// Gets the brokerages model percentage factor used to determine the required unused buying power for the account.
/// From 1 to 0. Example: 0 means no unused buying power is required. 0.5 means 50% of the buying power should be left unused.
/// </summary>
public virtual decimal RequiredFreeBuyingPowerPercent => 0m;
/// <summary>
/// Gets a map of the default markets to be used for each security type
/// </summary>
public virtual IReadOnlyDictionary<SecurityType, string> DefaultMarkets
{
get { return DefaultMarketMap; }
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultBrokerageModel"/> class
/// </summary>
/// <param name="accountType">The type of account to be modelled, defaults to
/// <see cref="QuantConnect.AccountType.Margin"/></param>
public DefaultBrokerageModel(AccountType accountType = AccountType.Margin)
{
AccountType = accountType;
}
/// <summary>
/// Returns true if the brokerage could accept this order. This takes into account
/// order type, security type, and order size limits.
/// </summary>
/// <remarks>
/// For example, a brokerage may have no connectivity at certain times, or an order rate/size limit
/// </remarks>
/// <param name="security">The security being ordered</param>
/// <param name="order">The order to be processed</param>
/// <param name="message">If this function returns false, a brokerage message detailing why the order may not be submitted</param>
/// <returns>True if the brokerage could process the order, false otherwise</returns>
public virtual bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message)
{
message = null;
return true;
}
/// <summary>
/// Returns true if the brokerage would allow updating the order as specified by the request
/// </summary>
/// <param name="security">The security of the order</param>
/// <param name="order">The order to be updated</param>
/// <param name="request">The requested update to be made to the order</param>
/// <param name="message">If this function returns false, a brokerage message detailing why the order may not be updated</param>
/// <returns>True if the brokerage would allow updating the order, false otherwise</returns>
public virtual bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message)
{
message = null;
return true;
}
/// <summary>
/// Returns true if the brokerage would be able to execute this order at this time assuming
/// market prices are sufficient for the fill to take place. This is used to emulate the
/// brokerage fills in backtesting and paper trading. For example some brokerages may not perform
/// executions during extended market hours. This is not intended to be checking whether or not
/// the exchange is open, that is handled in the Security.Exchange property.
/// </summary>
/// <param name="security">The security being traded</param>
/// <param name="order">The order to test for execution</param>
/// <returns>True if the brokerage would be able to perform the execution, false otherwise</returns>
public virtual bool CanExecuteOrder(Security security, Order order)
{
return true;
}
/// <summary>
/// Applies the split to the specified order ticket
/// </summary>
/// <remarks>
/// This default implementation will update the orders to maintain a similar market value
/// </remarks>
/// <param name="tickets">The open tickets matching the split event</param>
/// <param name="split">The split event data</param>
public virtual void ApplySplit(List<OrderTicket> tickets, Split split)
{
// by default we'll just update the orders to have the same notional value
var splitFactor = split.SplitFactor;
tickets.ForEach(ticket => ticket.Update(new UpdateOrderFields
{
Quantity = (int?) (ticket.Quantity/splitFactor),
LimitPrice = ticket.OrderType.IsLimitOrder() ? ticket.Get(OrderField.LimitPrice)*splitFactor : (decimal?) null,
StopPrice = ticket.OrderType.IsStopOrder() ? ticket.Get(OrderField.StopPrice)*splitFactor : (decimal?) null
}));
}
/// <summary>
/// Gets the brokerage's leverage for the specified security
/// </summary>
/// <param name="security">The security's whose leverage we seek</param>
/// <returns>The leverage for the specified security</returns>
public virtual decimal GetLeverage(Security security)
{
if (AccountType == AccountType.Cash)
{
return 1m;
}
switch (security.Type)
{
case SecurityType.Equity:
return 2m;
case SecurityType.Forex:
case SecurityType.Cfd:
return 50m;
case SecurityType.Crypto:
return 1m;
case SecurityType.Base:
case SecurityType.Commodity:
case SecurityType.Option:
case SecurityType.Future:
default:
return 1m;
}
}
/// <summary>
/// Gets a new fill model that represents this brokerage's fill behavior
/// </summary>
/// <param name="security">The security to get fill model for</param>
/// <returns>The new fill model for this brokerage</returns>
public virtual IFillModel GetFillModel(Security security)
{
return new ImmediateFillModel();
}
/// <summary>
/// Gets a new fee model that represents this brokerage's fee structure
/// </summary>
/// <param name="security">The security to get a fee model for</param>
/// <returns>The new fee model for this brokerage</returns>
public virtual IFeeModel GetFeeModel(Security security)
{
switch (security.Type)
{
case SecurityType.Base:
case SecurityType.Forex:
case SecurityType.Cfd:
case SecurityType.Crypto:
return new ConstantFeeModel(0m);
case SecurityType.Equity:
case SecurityType.Option:
case SecurityType.Future:
return new InteractiveBrokersFeeModel();
case SecurityType.Commodity:
default:
return new ConstantFeeModel(0m);
}
}
/// <summary>
/// Gets a new slippage model that represents this brokerage's fill slippage behavior
/// </summary>
/// <param name="security">The security to get a slippage model for</param>
/// <returns>The new slippage model for this brokerage</returns>
public virtual ISlippageModel GetSlippageModel(Security security)
{
switch (security.Type)
{
case SecurityType.Base:
case SecurityType.Equity:
return new ConstantSlippageModel(0);
case SecurityType.Forex:
case SecurityType.Cfd:
case SecurityType.Crypto:
return new ConstantSlippageModel(0);
case SecurityType.Commodity:
case SecurityType.Option:
case SecurityType.Future:
default:
return new ConstantSlippageModel(0);
}
}
/// <summary>
/// Gets a new settlement model for the security
/// </summary>
/// <param name="security">The security to get a settlement model for</param>
/// <returns>The settlement model for this brokerage</returns>
public virtual ISettlementModel GetSettlementModel(Security security)
{
if (AccountType == AccountType.Cash)
{
switch (security.Type)
{
case SecurityType.Equity:
return new DelayedSettlementModel(Equity.DefaultSettlementDays, Equity.DefaultSettlementTime);
case SecurityType.Option:
return new DelayedSettlementModel(Option.DefaultSettlementDays, Option.DefaultSettlementTime);
}
}
return new ImmediateSettlementModel();
}
/// <summary>
/// Gets a new settlement model for the security
/// </summary>
/// <param name="security">The security to get a settlement model for</param>
/// <param name="accountType">The account type</param>
/// <returns>The settlement model for this brokerage</returns>
[Obsolete("Flagged deprecated and will remove December 1st 2018")]
public ISettlementModel GetSettlementModel(Security security, AccountType accountType)
{
return GetSettlementModel(security);
}
/// <summary>
/// Gets a new buying power model for the security, returning the default model with the security's configured leverage.
/// For cash accounts, leverage = 1 is used.
/// </summary>
/// <param name="security">The security to get a buying power model for</param>
/// <returns>The buying power model for this brokerage/security</returns>
public virtual IBuyingPowerModel GetBuyingPowerModel(Security security)
{
var leverage = GetLeverage(security);
IBuyingPowerModel model;
switch (security.Type)
{
case SecurityType.Crypto:
model = new CashBuyingPowerModel();
break;
case SecurityType.Forex:
case SecurityType.Cfd:
model = new SecurityMarginModel(leverage, RequiredFreeBuyingPowerPercent);
break;
case SecurityType.Option:
model = new OptionMarginModel(RequiredFreeBuyingPowerPercent);
break;
case SecurityType.Future:
model = new FutureMarginModel(RequiredFreeBuyingPowerPercent);
break;
default:
model = new SecurityMarginModel(leverage, RequiredFreeBuyingPowerPercent);
break;
}
return model;
}
/// <summary>
/// Gets a new buying power model for the security
/// </summary>
/// <param name="security">The security to get a buying power model for</param>
/// <param name="accountType">The account type</param>
/// <returns>The buying power model for this brokerage/security</returns>
[Obsolete("Flagged deprecated and will remove December 1st 2018")]
public IBuyingPowerModel GetBuyingPowerModel(Security security, AccountType accountType)
{
return GetBuyingPowerModel(security);
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace CustomRulesPageCS
{
partial class FrmNodeReductionRule
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.TxtDescription = new System.Windows.Forms.TextBox();
this.lblDescription = new System.Windows.Forms.Label();
this.cmbReducedNodeClass = new System.Windows.Forms.ComboBox();
this.lblReducedNode = new System.Windows.Forms.Label();
this.lblGroup = new System.Windows.Forms.GroupBox();
this.txtLinkAttribute = new System.Windows.Forms.TextBox();
this.chkLinkAttribute = new System.Windows.Forms.CheckBox();
this.cmbAttributeName = new System.Windows.Forms.ComboBox();
this.chkKeepVertices = new System.Windows.Forms.CheckBox();
this.lblTargetSuperspan = new System.Windows.Forms.Label();
this.cmbTargetSuperspanClass = new System.Windows.Forms.ComboBox();
this.lblAttributeName = new System.Windows.Forms.Label();
this.lblGroup.SuspendLayout();
this.SuspendLayout();
//
// TxtDescription
//
this.TxtDescription.Location = new System.Drawing.Point(27, 29);
this.TxtDescription.Name = "TxtDescription";
this.TxtDescription.Size = new System.Drawing.Size(336, 20);
this.TxtDescription.TabIndex = 0;
this.TxtDescription.TextChanged += new System.EventHandler(this.Changed);
//
// lblDescription
//
this.lblDescription.AutoSize = true;
this.lblDescription.Location = new System.Drawing.Point(24, 10);
this.lblDescription.Name = "lblDescription";
this.lblDescription.Size = new System.Drawing.Size(64, 14);
this.lblDescription.TabIndex = 5;
this.lblDescription.Text = "Description:";
//
// cmbReducedNodeClass
//
this.cmbReducedNodeClass.FormattingEnabled = true;
this.cmbReducedNodeClass.Location = new System.Drawing.Point(27, 84);
this.cmbReducedNodeClass.Name = "cmbReducedNodeClass";
this.cmbReducedNodeClass.Size = new System.Drawing.Size(336, 22);
this.cmbReducedNodeClass.TabIndex = 1;
this.cmbReducedNodeClass.SelectedIndexChanged += new System.EventHandler(this.Changed);
this.cmbReducedNodeClass.Click += new System.EventHandler(this.Changed);
//
// lblReducedNode
//
this.lblReducedNode.AutoSize = true;
this.lblReducedNode.Location = new System.Drawing.Point(24, 64);
this.lblReducedNode.Name = "lblReducedNode";
this.lblReducedNode.Size = new System.Drawing.Size(185, 14);
this.lblReducedNode.TabIndex = 6;
this.lblReducedNode.Text = "Select the schematic class to reduce";
//
// lblGroup
//
this.lblGroup.Controls.Add(this.txtLinkAttribute);
this.lblGroup.Controls.Add(this.chkLinkAttribute);
this.lblGroup.Controls.Add(this.cmbAttributeName);
this.lblGroup.Controls.Add(this.chkKeepVertices);
this.lblGroup.Controls.Add(this.lblTargetSuperspan);
this.lblGroup.Controls.Add(this.cmbTargetSuperspanClass);
this.lblGroup.Controls.Add(this.lblAttributeName);
this.lblGroup.Location = new System.Drawing.Point(27, 123);
this.lblGroup.Name = "lblGroup";
this.lblGroup.Size = new System.Drawing.Size(336, 221);
this.lblGroup.TabIndex = 7;
this.lblGroup.TabStop = false;
this.lblGroup.Text = "Target superspan link";
//
// txtLinkAttribute
//
this.txtLinkAttribute.Location = new System.Drawing.Point(11, 160);
this.txtLinkAttribute.Name = "txtLinkAttribute";
this.txtLinkAttribute.Size = new System.Drawing.Size(304, 20);
this.txtLinkAttribute.TabIndex = 5;
this.txtLinkAttribute.TextChanged += new System.EventHandler(this.Changed);
//
// chkLinkAttribute
//
this.chkLinkAttribute.AutoSize = true;
this.chkLinkAttribute.Checked = true;
this.chkLinkAttribute.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkLinkAttribute.Location = new System.Drawing.Point(12, 136);
this.chkLinkAttribute.Name = "chkLinkAttribute";
this.chkLinkAttribute.Size = new System.Drawing.Size(158, 17);
this.chkLinkAttribute.TabIndex = 4;
this.chkLinkAttribute.Text = "By Connected Link Attribute";
this.chkLinkAttribute.UseVisualStyleBackColor = true;
this.chkLinkAttribute.CheckedChanged += new System.EventHandler(this.chkLinkAttribute_CheckedChanged);
//
// cmbAttributeName
//
this.cmbAttributeName.FormattingEnabled = true;
this.cmbAttributeName.Location = new System.Drawing.Point(12, 99);
this.cmbAttributeName.Name = "cmbAttributeName";
this.cmbAttributeName.Size = new System.Drawing.Size(303, 22);
this.cmbAttributeName.TabIndex = 3;
this.cmbAttributeName.SelectedIndexChanged += new System.EventHandler(this.Changed);
this.cmbAttributeName.Click += new System.EventHandler(this.Changed);
//
// chkKeepVertices
//
this.chkKeepVertices.Checked = true;
this.chkKeepVertices.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkKeepVertices.Location = new System.Drawing.Point(11, 195);
this.chkKeepVertices.Name = "chkKeepVertices";
this.chkKeepVertices.Size = new System.Drawing.Size(305, 18);
this.chkKeepVertices.TabIndex = 6;
this.chkKeepVertices.Text = "Keep vertices";
this.chkKeepVertices.UseVisualStyleBackColor = true;
this.chkKeepVertices.CheckStateChanged += new System.EventHandler(this.Changed);
//
// lblTargetSuperspan
//
this.lblTargetSuperspan.AutoSize = true;
this.lblTargetSuperspan.Location = new System.Drawing.Point(7, 24);
this.lblTargetSuperspan.Name = "lblTargetSuperspan";
this.lblTargetSuperspan.Size = new System.Drawing.Size(136, 14);
this.lblTargetSuperspan.TabIndex = 8;
this.lblTargetSuperspan.Text = "Select the schematic class";
//
// cmbTargetSuperspanClass
//
this.cmbTargetSuperspanClass.FormattingEnabled = true;
this.cmbTargetSuperspanClass.Location = new System.Drawing.Point(11, 41);
this.cmbTargetSuperspanClass.Name = "cmbTargetSuperspanClass";
this.cmbTargetSuperspanClass.Size = new System.Drawing.Size(306, 22);
this.cmbTargetSuperspanClass.TabIndex = 2;
this.cmbTargetSuperspanClass.SelectedIndexChanged += new System.EventHandler(this.FillAttNames);
this.cmbTargetSuperspanClass.Click += new System.EventHandler(this.FillAttNames);
//
// lblAttributeName
//
this.lblAttributeName.AutoSize = true;
this.lblAttributeName.Location = new System.Drawing.Point(8, 78);
this.lblAttributeName.Name = "lblAttributeName";
this.lblAttributeName.Size = new System.Drawing.Size(130, 14);
this.lblAttributeName.TabIndex = 10;
this.lblAttributeName.Text = "Cumulative attribute name";
//
// FrmNodeReductionRule
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 14F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.ClientSize = new System.Drawing.Size(384, 355);
this.Controls.Add(this.lblGroup);
this.Controls.Add(this.lblReducedNode);
this.Controls.Add(this.cmbReducedNodeClass);
this.Controls.Add(this.lblDescription);
this.Controls.Add(this.TxtDescription);
this.Font = new System.Drawing.Font("Arial", 8F);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FrmNodeReductionRule";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "FrmNodeReductionRule";
this.lblGroup.ResumeLayout(false);
this.lblGroup.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public System.Windows.Forms.TextBox TxtDescription;
public System.Windows.Forms.ComboBox cmbReducedNodeClass;
public System.Windows.Forms.ComboBox cmbTargetSuperspanClass;
public System.Windows.Forms.Label lblDescription;
public System.Windows.Forms.Label lblReducedNode;
public System.Windows.Forms.Label lblTargetSuperspan;
public System.Windows.Forms.Label lblAttributeName;
public System.Windows.Forms.GroupBox lblGroup;
public System.Windows.Forms.CheckBox chkKeepVertices;
public System.Windows.Forms.ComboBox cmbAttributeName;
public System.Windows.Forms.TextBox txtLinkAttribute;
public System.Windows.Forms.CheckBox chkLinkAttribute;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Directory = Lucene.Net.Store.Directory;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using BitVector = Lucene.Net.Util.BitVector;
namespace Lucene.Net.Index
{
/// <summary> Information about a segment such as it's name, directory, and files related
/// to the segment.
///
/// * <p/><b>NOTE:</b> This API is new and still experimental
/// (subject to change suddenly in the next release)<p/>
/// </summary>
public sealed 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 System.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 System.Collections.Generic.IList<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 System.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 omitTermFreqAndPositions==false
private System.Collections.Generic.IDictionary<string, string> diagnostics;
public override System.String ToString()
{
return "si: " + dir.ToString() + " " + name + " docCount: " + docCount + " delCount: " + delCount + " delFileName: " + GetDelFileName();
}
public SegmentInfo(System.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(System.String name, int docCount, Directory dir, bool isCompoundFile, bool hasSingleNormFile):this(name, docCount, dir, isCompoundFile, hasSingleNormFile, - 1, null, false, true)
{
}
public SegmentInfo(System.String name, int docCount, Directory dir, bool isCompoundFile, bool hasSingleNormFile, int docStoreOffset, System.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, "dso=" + docStoreOffset + " dss=" + docStoreSegment + " docCount=" + docCount);
}
/// <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];
Array.Copy(src.normGen, 0, normGen, 0, src.normGen.Length);
}
isCompoundFile = src.isCompoundFile;
hasSingleNormFile = src.hasSingleNormFile;
delCount = src.delCount;
}
// must be Map<String, String>
internal void SetDiagnostics(System.Collections.Generic.IDictionary<string, string> diagnostics)
{
this.diagnostics = diagnostics;
}
// returns Map<String, String>
public System.Collections.Generic.IDictionary<string, string> GetDiagnostics()
{
return diagnostics;
}
/// <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;
if (format <= SegmentInfos.FORMAT_DIAGNOSTICS)
{
diagnostics = input.ReadStringStringMap();
}
else
{
diagnostics = new System.Collections.Generic.Dictionary<string,string>();
}
}
else
{
delGen = CHECK_DIR;
normGen = null;
isCompoundFile = (sbyte) (CHECK_DIR);
preLockless = true;
hasSingleNormFile = false;
docStoreOffset = - 1;
docStoreIsCompoundFile = false;
docStoreSegment = null;
delCount = - 1;
hasProx = true;
diagnostics = new System.Collections.Generic.Dictionary<string,string>();
}
}
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 long SizeInBytes()
{
if (sizeInBytes == - 1)
{
System.Collections.Generic.IList<string> files = Files();
int size = files.Count;
sizeInBytes = 0;
for (int i = 0; i < size; i++)
{
System.String fileName = (System.String) 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 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 System.Object Clone()
{
SegmentInfo si = new SegmentInfo(name, docCount, dir);
si.isCompoundFile = isCompoundFile;
si.delGen = delGen;
si.delCount = delCount;
si.hasProx = hasProx;
si.preLockless = preLockless;
si.hasSingleNormFile = hasSingleNormFile;
if (this.diagnostics != null)
{
si.diagnostics = new System.Collections.Generic.Dictionary<string, string>();
foreach (string o in diagnostics.Keys)
{
si.diagnostics.Add(o,diagnostics[o]);
}
}
if (normGen != null)
{
si.normGen = new long[normGen.Length];
normGen.CopyTo(si.normGen, 0);
}
si.docStoreOffset = docStoreOffset;
si.docStoreSegment = docStoreSegment;
si.docStoreIsCompoundFile = docStoreIsCompoundFile;
if (this.files != null)
{
si.files = new System.Collections.Generic.List<string>();
foreach (string file in files)
{
si.files.Add(file);
}
}
return si;
}
public System.String GetDelFileName()
{
if (delGen == NO)
{
// In this case we know there is no deletion filename
// against this segment
return null;
}
else
{
// If delGen is CHECK_DIR, it's the pre-lockless-commit file format
return IndexFileNames.FileNameFromGeneration(name, "." + IndexFileNames.DELETES_EXTENSION, delGen);
}
}
/// <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>
public bool HasSeparateNorms(int fieldNumber)
{
if ((normGen == null && preLockless) || (normGen != null && normGen[fieldNumber] == CHECK_DIR))
{
// Must fallback to directory file exists check:
System.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 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:
System.String[] result = dir.List();
if (result == null)
{
throw new System.IO.IOException("cannot read directory " + dir + ": list() returned null");
}
System.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>
public System.String GetNormFileName(int number)
{
System.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 bool GetUseCompoundFile()
{
if (isCompoundFile == NO)
{
return false;
}
else if (isCompoundFile == YES)
{
return true;
}
else
{
return dir.FileExists(name + "." + IndexFileNames.COMPOUND_FILE_EXTENSION);
}
}
public int GetDelCount()
{
if (delCount == - 1)
{
if (HasDeletions())
{
System.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);
}
public int GetDocStoreOffset()
{
return docStoreOffset;
}
public bool GetDocStoreIsCompoundFile()
{
return docStoreIsCompoundFile;
}
internal void SetDocStoreIsCompoundFile(bool v)
{
docStoreIsCompoundFile = v;
ClearFiles();
}
public System.String GetDocStoreSegment()
{
return docStoreSegment;
}
internal void SetDocStoreOffset(int offset)
{
docStoreOffset = offset;
ClearFiles();
}
internal void SetDocStore(int offset, System.String segment, bool isCompoundFile)
{
docStoreOffset = offset;
docStoreSegment = segment;
docStoreIsCompoundFile = isCompoundFile;
}
/// <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));
output.WriteStringStringMap(diagnostics);
}
internal void SetHasProx(bool hasProx)
{
this.hasProx = hasProx;
ClearFiles();
}
public bool GetHasProx()
{
return hasProx;
}
private void AddIfExists(System.Collections.Generic.IList<string> files, System.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 System.Collections.Generic.IList<string> Files()
{
if (files != null)
{
// Already cached:
return files;
}
files = new System.Collections.Generic.List<string>();
bool useCompoundFile = GetUseCompoundFile();
if (useCompoundFile)
{
files.Add(name + "." + IndexFileNames.COMPOUND_FILE_EXTENSION);
}
else
{
System.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
{
System.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
System.String[] exts = IndexFileNames.STORE_INDEX_EXTENSIONS;
for (int i = 0; i < exts.Length; i++)
AddIfExists(files, name + "." + exts[i]);
}
System.String delFileName = IndexFileNames.FileNameFromGeneration(name, "." + IndexFileNames.DELETES_EXTENSION, delGen);
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)
{
System.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
System.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:
System.String prefix;
if (useCompoundFile)
prefix = name + "." + IndexFileNames.SEPARATE_NORMS_EXTENSION;
else
prefix = name + "." + IndexFileNames.PLAIN_NORMS_EXTENSION;
int prefixLength = prefix.Length;
System.String[] allFiles = dir.ListAll();
IndexFileNameFilter filter = IndexFileNameFilter.GetFilter();
for (int i = 0; i < allFiles.Length; i++)
{
System.String fileName = allFiles[i];
if (filter.Accept(null, fileName) && 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 System.String SegString(Directory dir)
{
System.String cfs;
try
{
if (GetUseCompoundFile())
cfs = "c";
else
cfs = "C";
}
catch (System.IO.IOException ioe)
{
cfs = "?";
}
System.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(System.Object obj)
{
SegmentInfo other;
try
{
other = (SegmentInfo) obj;
}
catch (System.InvalidCastException cce)
{
return false;
}
return other.dir == dir && other.name.Equals(name);
}
public override int GetHashCode()
{
return dir.GetHashCode() + name.GetHashCode();
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// gRPC server. A single server can server arbitrary number of services and can listen on more than one ports.
/// </summary>
public class Server
{
const int DefaultRequestCallTokensPerCq = 2000;
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>();
readonly AtomicCounter activeCallCounter = new AtomicCounter();
readonly ServiceDefinitionCollection serviceDefinitions;
readonly ServerPortCollection ports;
readonly GrpcEnvironment environment;
readonly List<ChannelOption> options;
readonly ServerSafeHandle handle;
readonly object myLock = new object();
readonly List<ServerServiceDefinition> serviceDefinitionsList = new List<ServerServiceDefinition>();
readonly List<ServerPort> serverPortList = new List<ServerPort>();
readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>();
readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>();
bool startRequested;
volatile bool shutdownRequested;
int requestCallTokensPerCq = DefaultRequestCallTokensPerCq;
/// <summary>
/// Creates a new server.
/// </summary>
public Server() : this(null)
{
}
/// <summary>
/// Creates a new server.
/// </summary>
/// <param name="options">Channel options.</param>
public Server(IEnumerable<ChannelOption> options)
{
this.serviceDefinitions = new ServiceDefinitionCollection(this);
this.ports = new ServerPortCollection(this);
this.environment = GrpcEnvironment.AddRef();
this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>();
using (var channelArgs = ChannelOptions.CreateChannelArgs(this.options))
{
this.handle = ServerSafeHandle.NewServer(channelArgs);
}
foreach (var cq in environment.CompletionQueues)
{
this.handle.RegisterCompletionQueue(cq);
}
GrpcEnvironment.RegisterServer(this);
}
/// <summary>
/// Services that will be exported by the server once started. Register a service with this
/// server by adding its definition to this collection.
/// </summary>
public ServiceDefinitionCollection Services
{
get
{
return serviceDefinitions;
}
}
/// <summary>
/// Ports on which the server will listen once started. Register a port with this
/// server by adding its definition to this collection.
/// </summary>
public ServerPortCollection Ports
{
get
{
return ports;
}
}
/// <summary>
/// To allow awaiting termination of the server.
/// </summary>
public Task ShutdownTask
{
get
{
return shutdownTcs.Task;
}
}
/// <summary>
/// Experimental API. Might anytime change without prior notice.
/// Number or calls requested via grpc_server_request_call at any given time for each completion queue.
/// </summary>
public int RequestCallTokensPerCompletionQueue
{
get
{
return requestCallTokensPerCq;
}
set
{
lock (myLock)
{
GrpcPreconditions.CheckState(!startRequested);
GrpcPreconditions.CheckArgument(value > 0);
requestCallTokensPerCq = value;
}
}
}
/// <summary>
/// Starts the server.
/// </summary>
public void Start()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!startRequested);
GrpcPreconditions.CheckState(!shutdownRequested);
startRequested = true;
handle.Start();
for (int i = 0; i < requestCallTokensPerCq; i++)
{
foreach (var cq in environment.CompletionQueues)
{
AllowOneRpc(cq);
}
}
}
}
/// <summary>
/// Requests server shutdown and when there are no more calls being serviced,
/// cleans up used resources. The returned task finishes when shutdown procedure
/// is complete.
/// </summary>
/// <remarks>
/// It is strongly recommended to shutdown all previously created servers before exiting from the process.
/// </remarks>
public Task ShutdownAsync()
{
return ShutdownInternalAsync(false);
}
/// <summary>
/// Requests server shutdown while cancelling all the in-progress calls.
/// The returned task finishes when shutdown procedure is complete.
/// </summary>
/// <remarks>
/// It is strongly recommended to shutdown all previously created servers before exiting from the process.
/// </remarks>
public Task KillAsync()
{
return ShutdownInternalAsync(true);
}
internal void AddCallReference(object call)
{
activeCallCounter.Increment();
bool success = false;
handle.DangerousAddRef(ref success);
GrpcPreconditions.CheckState(success);
}
internal void RemoveCallReference(object call)
{
handle.DangerousRelease();
activeCallCounter.Decrement();
}
/// <summary>
/// Shuts down the server.
/// </summary>
private async Task ShutdownInternalAsync(bool kill)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
GrpcEnvironment.UnregisterServer(this);
var cq = environment.CompletionQueues.First(); // any cq will do
handle.ShutdownAndNotify(HandleServerShutdown, cq);
if (kill)
{
handle.CancelAllCalls();
}
await ShutdownCompleteOrEnvironmentDeadAsync().ConfigureAwait(false);
DisposeHandle();
await GrpcEnvironment.ReleaseAsync().ConfigureAwait(false);
}
/// <summary>
/// In case the environment's threadpool becomes dead, the shutdown completion will
/// never be delivered, but we need to release the environment's handle anyway.
/// </summary>
private async Task ShutdownCompleteOrEnvironmentDeadAsync()
{
while (true)
{
var task = await Task.WhenAny(shutdownTcs.Task, Task.Delay(20)).ConfigureAwait(false);
if (shutdownTcs.Task == task)
{
return;
}
if (!environment.IsAlive)
{
return;
}
}
}
/// <summary>
/// Adds a service definition.
/// </summary>
private void AddServiceDefinitionInternal(ServerServiceDefinition serviceDefinition)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!startRequested);
foreach (var entry in serviceDefinition.CallHandlers)
{
callHandlers.Add(entry.Key, entry.Value);
}
serviceDefinitionsList.Add(serviceDefinition);
}
}
/// <summary>
/// Adds a listening port.
/// </summary>
private int AddPortInternal(ServerPort serverPort)
{
lock (myLock)
{
GrpcPreconditions.CheckNotNull(serverPort.Credentials, "serverPort");
GrpcPreconditions.CheckState(!startRequested);
var address = string.Format("{0}:{1}", serverPort.Host, serverPort.Port);
int boundPort;
using (var nativeCredentials = serverPort.Credentials.ToNativeCredentials())
{
if (nativeCredentials != null)
{
boundPort = handle.AddSecurePort(address, nativeCredentials);
}
else
{
boundPort = handle.AddInsecurePort(address);
}
}
var newServerPort = new ServerPort(serverPort, boundPort);
this.serverPortList.Add(newServerPort);
return boundPort;
}
}
/// <summary>
/// Allows one new RPC call to be received by server.
/// </summary>
private void AllowOneRpc(CompletionQueueSafeHandle cq)
{
if (!shutdownRequested)
{
handle.RequestCall((success, ctx) => HandleNewServerRpc(success, ctx, cq), cq);
}
}
private void DisposeHandle()
{
var activeCallCount = activeCallCounter.Count;
if (activeCallCount > 0)
{
Logger.Warning("Server shutdown has finished but there are still {0} active calls for that server.", activeCallCount);
}
handle.Dispose();
}
/// <summary>
/// Selects corresponding handler for given call and handles the call.
/// </summary>
private async Task HandleCallAsync(ServerRpcNew newRpc, CompletionQueueSafeHandle cq, Action continuation)
{
try
{
IServerCallHandler callHandler;
if (!callHandlers.TryGetValue(newRpc.Method, out callHandler))
{
callHandler = UnimplementedMethodCallHandler.Instance;
}
await callHandler.HandleCall(newRpc, cq).ConfigureAwait(false);
}
catch (Exception e)
{
Logger.Warning(e, "Exception while handling RPC.");
}
finally
{
continuation();
}
}
/// <summary>
/// Handles the native callback.
/// </summary>
private void HandleNewServerRpc(bool success, RequestCallContextSafeHandle ctx, CompletionQueueSafeHandle cq)
{
bool nextRpcRequested = false;
if (success)
{
var newRpc = ctx.GetServerRpcNew(this);
// after server shutdown, the callback returns with null call
if (!newRpc.Call.IsInvalid)
{
nextRpcRequested = true;
// Start asynchronous handler for the call.
// Don't await, the continuations will run on gRPC thread pool once triggered
// by cq.Next().
#pragma warning disable 4014
HandleCallAsync(newRpc, cq, () => AllowOneRpc(cq));
#pragma warning restore 4014
}
}
if (!nextRpcRequested)
{
AllowOneRpc(cq);
}
}
/// <summary>
/// Handles native callback.
/// </summary>
private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx)
{
shutdownTcs.SetResult(null);
}
/// <summary>
/// Collection of service definitions.
/// </summary>
public class ServiceDefinitionCollection : IEnumerable<ServerServiceDefinition>
{
readonly Server server;
internal ServiceDefinitionCollection(Server server)
{
this.server = server;
}
/// <summary>
/// Adds a service definition to the server. This is how you register
/// handlers for a service with the server. Only call this before Start().
/// </summary>
public void Add(ServerServiceDefinition serviceDefinition)
{
server.AddServiceDefinitionInternal(serviceDefinition);
}
/// <summary>
/// Gets enumerator for this collection.
/// </summary>
public IEnumerator<ServerServiceDefinition> GetEnumerator()
{
return server.serviceDefinitionsList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return server.serviceDefinitionsList.GetEnumerator();
}
}
/// <summary>
/// Collection of server ports.
/// </summary>
public class ServerPortCollection : IEnumerable<ServerPort>
{
readonly Server server;
internal ServerPortCollection(Server server)
{
this.server = server;
}
/// <summary>
/// Adds a new port on which server should listen.
/// Only call this before Start().
/// <returns>The port on which server will be listening.</returns>
/// </summary>
public int Add(ServerPort serverPort)
{
return server.AddPortInternal(serverPort);
}
/// <summary>
/// Adds a new port on which server should listen.
/// <returns>The port on which server will be listening.</returns>
/// </summary>
/// <param name="host">the host</param>
/// <param name="port">the port. If zero, an unused port is chosen automatically.</param>
/// <param name="credentials">credentials to use to secure this port.</param>
public int Add(string host, int port, ServerCredentials credentials)
{
return Add(new ServerPort(host, port, credentials));
}
/// <summary>
/// Gets enumerator for this collection.
/// </summary>
public IEnumerator<ServerPort> GetEnumerator()
{
return server.serverPortList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return server.serverPortList.GetEnumerator();
}
}
}
}
| |
namespace Nancy.Authentication.Forms.Tests
{
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading;
using FakeItEasy;
using Bootstrapper;
using Cryptography;
using Nancy.Tests;
using Nancy.Tests.Fakes;
using Xunit;
public class FormsAuthenticationFixture
{
private FormsAuthenticationConfiguration config;
private FormsAuthenticationConfiguration secureConfig;
private FormsAuthenticationConfiguration domainPathConfig;
private NancyContext context;
private Guid userGuid;
private string validCookieValue =
"C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9";
private string cookieWithNoHmac =
"k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9";
private string cookieWithEmptyHmac =
"k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9";
private string cookieWithInvalidHmac =
"C+QzbqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9";
private string cookieWithBrokenEncryptedData =
"C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3spwI0jB0KeVY9";
private CryptographyConfiguration cryptographyConfiguration;
private string domain = ".nancyfx.org";
private string path = "/";
public FormsAuthenticationFixture()
{
this.cryptographyConfiguration = new CryptographyConfiguration(
new AesEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)),
new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)));
this.config = new FormsAuthenticationConfiguration()
{
CryptographyConfiguration = this.cryptographyConfiguration,
RedirectUrl = "/login",
UserMapper = A.Fake<IUserMapper>(),
RequiresSSL = false
};
this.secureConfig = new FormsAuthenticationConfiguration()
{
CryptographyConfiguration = this.cryptographyConfiguration,
RedirectUrl = "/login",
UserMapper = A.Fake<IUserMapper>(),
RequiresSSL = true
};
this.domainPathConfig = new FormsAuthenticationConfiguration()
{
CryptographyConfiguration = this.cryptographyConfiguration,
RedirectUrl = "/login",
UserMapper = A.Fake<IUserMapper>(),
RequiresSSL = false,
Domain = domain,
Path = path
};
this.context = new NancyContext
{
Request = new Request(
"GET",
new Url { Scheme = "http", BasePath = "/testing", HostName = "test.com", Path = "test" })
};
this.userGuid = new Guid("3D97EB33-824A-4173-A2C1-633AC16C1010");
}
[Fact]
public void Should_throw_with_null_application_pipelines_passed_to_enable()
{
var result = Record.Exception(() => FormsAuthentication.Enable((IPipelines)null, this.config));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_with_null_config_passed_to_enable()
{
var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), null));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_with_invalid_config_passed_to_enable()
{
var fakeConfig = A.Fake<FormsAuthenticationConfiguration>();
A.CallTo(() => fakeConfig.EnsureConfigurationIsValid()).Throws<InvalidOperationException>();
var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), fakeConfig));
result.ShouldBeOfType(typeof(InvalidOperationException));
}
[Fact]
public void Should_add_a_pre_and_post_hook_when_enabled()
{
var pipelines = A.Fake<IPipelines>();
FormsAuthentication.Enable(pipelines, this.config);
A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored))
.MustHaveHappenedOnceExactly();
A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored))
.MustHaveHappenedOnceExactly();
}
[Fact]
public void Should_add_a_pre_hook_but_not_a_post_hook_when_DisableRedirect_is_true()
{
var pipelines = A.Fake<IPipelines>();
this.config.DisableRedirect = true;
FormsAuthentication.Enable(pipelines, this.config);
A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored))
.MustHaveHappenedOnceExactly();
A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored))
.MustNotHaveHappened();
}
[Fact]
public void Should_return_redirect_response_when_user_logs_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
}
[Fact]
public void Should_return_ok_response_when_user_logs_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.OK);
}
[Fact]
public void Should_have_authentication_cookie_in_login_response_when_logging_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue();
}
[Fact]
public void Should_have_authentication_cookie_in_login_response_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_httponly_when_logging_in_with_redirect()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.HttpOnly.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_httponly_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.HttpOnly.ShouldBeTrue();
}
[Fact]
public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldBeNull();
}
[Fact]
public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldBeNull();
}
[Fact]
public void Should_set_expiry_date_if_one_specified_when_logging_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldNotBeNull();
}
[Fact]
public void Should_set_expiry_date_if_one_specified_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldNotBeNull();
}
[Fact]
public void Should_encrypt_cookie_when_logging_in_with_redirect()
{
var mockEncrypter = A.Fake<IEncryptionProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));
A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored))
.MustHaveHappenedOnceExactly();
}
[Fact]
public void Should_encrypt_cookie_when_logging_in_without_redirect()
{
// Given
var mockEncrypter = A.Fake<IEncryptionProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));
// Then
A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored))
.MustHaveHappenedOnceExactly();
}
[Fact]
public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_with_redirect()
{
var fakeEncrypter = A.Fake<IEncryptionProvider>();
var fakeCryptoText = "FakeText";
A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored))
.Returns(fakeCryptoText);
var mockHmac = A.Fake<IHmacProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));
A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText))
.MustHaveHappenedOnceExactly();
}
[Fact]
public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_without_redirect()
{
// Given
var fakeEncrypter = A.Fake<IEncryptionProvider>();
var fakeCryptoText = "FakeText";
A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored))
.Returns(fakeCryptoText);
var mockHmac = A.Fake<IHmacProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));
// Then
A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText))
.MustHaveHappenedOnceExactly();
}
[Fact]
public void Should_return_redirect_response_when_user_logs_out_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/");
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
}
[Fact]
public void Should_return_ok_response_when_user_logs_out_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.LogOutResponse();
// Then
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.OK);
}
[Fact]
public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/");
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Value.ShouldBeEmpty();
cookie.Expires.ShouldNotBeNull();
(cookie.Expires < DateTime.Now).ShouldBeTrue();
}
[Fact]
public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.LogOutResponse();
// Then
var cookie = result.Cookies.First(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName);
cookie.Value.ShouldBeEmpty();
cookie.Expires.ShouldNotBeNull();
(cookie.Expires < DateTime.Now).ShouldBeTrue();
}
[Fact]
public void Should_get_username_from_mapping_service_with_valid_cookie()
{
var fakePipelines = new Pipelines();
var mockMapper = A.Fake<IUserMapper>();
this.config.UserMapper = mockMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue);
fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
A.CallTo(() => mockMapper.GetUserFromIdentifier(this.userGuid, this.context))
.MustHaveHappenedOnceExactly();
}
[Fact]
public void Should_set_user_in_context_with_valid_cookie()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeSameAs(fakeUser);
}
[Fact]
public void Should_not_set_user_in_context_with_empty_cookie()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, string.Empty);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_user_in_context_with_invalid_hmac()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithInvalidHmac);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_user_in_context_with_empty_hmac()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithEmptyHmac);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_user_in_context_with_no_hmac()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithNoHmac);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_username_in_context_with_broken_encryption_data()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithBrokenEncryptedData);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_retain_querystring_when_redirecting_to_login_page()
{
// Given
var fakePipelines = new Pipelines();
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_change_the_forms_authentication_redirect_uri_querystring_key()
{
// Given
var fakePipelines = new Pipelines();
this.config.RedirectQuerystringKey = "next";
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?next=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_null()
{
// Given
var fakePipelines = new Pipelines();
this.config.RedirectQuerystringKey = null;
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_empty()
{
// Given
var fakePipelines = new Pipelines();
this.config.RedirectQuerystringKey = string.Empty;
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_retain_querystring_when_redirecting_after_successfull_login()
{
// Given
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "returnUrl=/secure%3Ffoo%3Dbar")
};
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInRedirectResponse(queryContext, userGuid, DateTime.Now.AddDays(1));
// Then
result.Headers["Location"].ShouldEqual("/secure?foo=bar");
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_with_redirect()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
result.Cookies
.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName)
.First()
.Secure.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies
.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName)
.First()
.Secure.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/");
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Secure.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
// When
var result = FormsAuthentication.LogOutResponse();
// Then
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Secure.ShouldBeTrue();
}
[Fact]
public void Should_redirect_to_base_path_if_non_local_url_and_no_fallback()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/";
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
result.Headers["Location"].ShouldEqual("/testing");
}
[Fact]
public void Should_redirect_to_fallback_if_non_local_url_and_fallback_set()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/";
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, fallbackRedirectUrl:"/moo");
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
result.Headers["Location"].ShouldEqual("/moo");
}
[Fact]
public void Should_redirect_to_given_url_if_local()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
context.Request.Query[config.RedirectQuerystringKey] = "~/login";
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
result.Headers["Location"].ShouldEqual("/testing/login");
}
[Fact]
public void Should_set_Domain_when_config_provides_domain_value()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Domain.ShouldEqual(domain);
}
[Fact]
public void Should_set_Path_when_config_provides_path_value()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Path.ShouldEqual(path);
}
[Fact]
public void Should_throw_with_null_module_passed_to_enable()
{
var result = Record.Exception(() => FormsAuthentication.Enable((INancyModule)null, this.config));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_with_null_config_passed_to_enable_with_module()
{
var result = Record.Exception(() => FormsAuthentication.Enable(new FakeModule(), null));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
class FakeModule : NancyModule
{
public FakeModule()
{
this.After = new AfterPipeline();
this.Before = new BeforePipeline();
this.OnError = new ErrorPipeline();
}
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Text;
using IxMilia.Iges.Entities;
using Xunit;
namespace IxMilia.Iges.Test
{
public class IgesWriterTests
{
private static void VerifyFileText(IgesFile file, string expected, Action<string, string> verifier)
{
var stream = new MemoryStream();
file.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
var bytes = stream.ToArray();
var actual = Encoding.ASCII.GetString(bytes);
verifier(expected.Trim('\r', '\n').Replace("\r", ""), actual.Trim('\r', '\n'));
}
private static void VerifyFileExactly(IgesFile file, string expected)
{
VerifyFileText(file, expected, (ex, ac) => Assert.Equal(ex, ac));
}
private static void VerifyFileContains(IgesFile file, string expected)
{
VerifyFileText(file, expected, (ex, ac) => Assert.Contains(ex, ac));
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteEmptyFileTest()
{
var date = new DateTime(2000, 12, 25, 13, 8, 5);
var file = new IgesFile()
{
ModifiedTime = date,
TimeStamp = date
};
VerifyFileExactly(file, @"
S 1
1H,,1H;,,,,,32,8,23,11,52,,1.,1,,0,1.,15H20001225.130805,1E-10,0.,,,11, G 1
0,15H20001225.130805,; G 2
S 1G 2D 0P 0 T 1
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteLineWithSpanningParametersTest()
{
var file = new IgesFile();
file.Entities.Add(new IgesLine()
{
P1 = new IgesPoint(1.1234512345, 2.1234512345, 3.1234512345),
P2 = new IgesPoint(4.1234512345, 5.1234512345, 6.1234512345),
Color = IgesColorNumber.Green
});
VerifyFileContains(file, @"
110 1 0 0 0 00000000D 1
110 0 3 2 0 D 2
110,1.1234512345,2.1234512345,3.1234512345,4.1234512345, 1P 1
5.1234512345,6.1234512345; 1P 2
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteLineWithCommentTest()
{
var file = new IgesFile();
file.Entities.Add(new IgesLine() { Comment = "This is a really long comment that should be ignored.\nIt also contains things that look like fields, and also contains things that look like 7Hstrings and records;" });
VerifyFileContains(file, @"
110 1 0 0 0 00000000D 1
110 0 0 3 0 D 2
110,0.,0.,0.,0.,0.,0.;This is a really long comment that should 1P 1
be ignored.\nIt also contains things that look like fields, and 1P 2
also contains things that look like 7Hstrings and records; 1P 3
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteFileWithInvariantCultureTest()
{
var existingCulture = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo("de-DE");
var date = new DateTime(2000, 12, 25, 13, 8, 5);
var file = new IgesFile()
{
ModifiedTime = date,
TimeStamp = date
};
VerifyFileExactly(file, @"
S 1
1H,,1H;,,,,,32,8,23,11,52,,1.,1,,0,1.,15H20001225.130805,1E-10,0.,,,11, G 1
0,15H20001225.130805,; G 2
S 1G 2D 0P 0 T 1
");
}
finally
{
CultureInfo.CurrentCulture = existingCulture;
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteLineWithViewTest()
{
var file = new IgesFile();
var line = new IgesLine() { View = new IgesView() };
file.Entities.Add(line);
VerifyFileContains(file, @"
410 1 0 0 0 00000100D 1
410 0 0 1 0 D 2
110 2 0 0 0 1 00000000D 3
110 0 0 1 0 D 4
410,0,0.,0,0,0,0,0,0; 1P 1
110,0.,0.,0.,0.,0.,0.; 3P 2
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteLineWithLineWeightTest()
{
var file = new IgesFile();
var line = new IgesLine() { LineWeight = 42 };
file.Entities.Add(line);
VerifyFileContains(file, @"
110 1 0 0 0 00000000D 1
110 42 0 1 0 D 2
110,0.,0.,0.,0.,0.,0.; 1P 1
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteLineWithTransformationMatrixTest()
{
var file = new IgesFile();
var trans = new IgesTransformationMatrix()
{
R11 = 1.0,
R12 = 2.0,
R13 = 3.0,
T1 = 4.0,
R21 = 5.0,
R22 = 6.0,
R23 = 7.0,
T2 = 8.0,
R31 = 9.0,
R32 = 10.0,
R33 = 11.0,
T3 = 12.0
};
var line = new IgesLine()
{
P1 = new IgesPoint(1, 2, 3),
P2 = new IgesPoint(4, 5, 6),
TransformationMatrix = trans,
};
file.Entities.Add(line);
VerifyFileContains(file, @"
124 1 0 0 0 00000000D 1
124 0 0 1 0 D 2
110 2 0 0 0 1 00000000D 3
110 0 0 1 0 D 4
124,1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12.; 1P 1
110,1.,2.,3.,4.,5.,6.; 3P 2
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteLineWithStructureTest()
{
var file = new IgesFile();
var circle = new IgesCircularArc() { StructureEntity = new IgesLine() };
file.Entities.Add(circle);
VerifyFileContains(file, @"
110 1 0 0 0 00000000D 1
110 0 0 1 0 D 2
100 2 -1 0 0 00000000D 3
100 0 0 1 0 D 4
110,0.,0.,0.,0.,0.,0.; 1P 1
100,0.,0.,0.,0.,0.,0.,0.; 3P 2
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteLineWithLineFontPatternTest()
{
var file = new IgesFile();
var line = new IgesLine() { LineFont = IgesLineFontPattern.Phantom };
file.Entities.Add(line);
VerifyFileContains(file, @"
110 1 0 3 0 00000000D 1
110 0 0 1 0 D 2
110,0.,0.,0.,0.,0.,0.; 1P 1
");
line.CustomLineFont = new IgesPatternLineFontDefinition();
VerifyFileContains(file, @"
304 1 0 0 0 00000200D 1
304 0 0 1 2 D 2
110 2 0 -1 0 00000000D 3
110 0 0 1 0 D 4
304,0,1H0; 1P 1
110,0.,0.,0.,0.,0.,0.; 3P 2
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteLineWithLevelsTest()
{
var file = new IgesFile();
var line = new IgesLine();
file.Entities.Add(line);
// no levels defined
line.Levels.Clear();
VerifyFileContains(file, @"
110 1 0 0 0 00000000D 1
110 0 0 1 0 D 2
110,0.,0.,0.,0.,0.,0.; 1P 1
");
// one level defined
line.Levels.Add(13);
VerifyFileContains(file, @"
110 1 0 0 13 00000000D 1
110 0 0 1 0 D 2
110,0.,0.,0.,0.,0.,0.; 1P 1
");
// multiple levels defined
line.Levels.Add(23);
VerifyFileContains(file, @"
406 1 0 0 0 00000000D 1
406 0 0 1 1 D 2
110 2 0 0 -1 00000000D 3
110 0 0 1 0 D 4
406,2,13,23; 1P 1
110,0.,0.,0.,0.,0.,0.; 3P 2
");
// multiple entities referencing different multiple levels
var otherLine = new IgesLine();
otherLine.Levels.Add(40);
otherLine.Levels.Add(41);
file.Entities.Add(otherLine);
VerifyFileContains(file, @"
406 1 0 0 0 00000000D 1
406 0 0 1 1 D 2
110 2 0 0 -1 00000000D 3
110 0 0 1 0 D 4
406 3 0 0 0 00000000D 5
406 0 0 1 1 D 6
110 4 0 0 -5 00000000D 7
110 0 0 1 0 D 8
406,2,13,23; 1P 1
110,0.,0.,0.,0.,0.,0.; 3P 2
406,2,40,41; 5P 3
110,0.,0.,0.,0.,0.,0.; 7P 4
");
// multiple entities referencing the same multiple levels
otherLine.Levels.Clear();
foreach (var level in line.Levels)
{
otherLine.Levels.Add(level);
}
VerifyFileContains(file, @"
406 1 0 0 0 00000000D 1
406 0 0 1 1 D 2
110 2 0 0 -1 00000000D 3
110 0 0 1 0 D 4
110 3 0 0 -1 00000000D 5
110 0 0 1 0 D 6
406,2,13,23; 1P 1
110,0.,0.,0.,0.,0.,0.; 3P 2
110,0.,0.,0.,0.,0.,0.; 5P 3
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteLineWithAssociatedLabelDisplayTest()
{
var file = new IgesFile();
var line = new IgesLine();
var label = new IgesLocation(); // cheating and using an IgesLocation as a fake label type
line.LabelDisplay = new IgesLabelDisplayAssociativity();
line.LabelDisplay.LabelPlacements.Add(
new IgesLabelPlacement(new IgesPerspectiveView(), new IgesPoint(1, 2, 3), new IgesLeader(), 7, label));
file.Entities.Add(line);
Assert.True(ReferenceEquals(line, line.LabelDisplay.AssociatedEntity));
VerifyFileContains(file, @"
410 1 0 0 0 00000100D 1
410 0 0 2 1 D 2
214 3 0 0 0 00000100D 3
214 0 0 1 1 D 4
116 4 0 0 0 00000000D 5
116 0 0 1 0 D 6
402 5 0 0 0 00000000D 7
402 0 0 1 5 D 8
110 6 0 0 0 700000000D 9
110 0 0 1 0 D 10
410,0,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0, 1P 1
0.,0.; 1P 2
214,0,0.,0.,0.,0.,0.; 3P 3
116,0.,0.,0.; 5P 4
402,1,1,1.,2.,3.,3,7,5; 7P 5
110,0.,0.,0.,0.,0.,0.; 9P 6
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteLineWithEntityLabelAndSubscriptTest()
{
var file = new IgesFile();
var line = new IgesLine()
{
EntityLabel = "abcdefghijklmnopqrstuvwxyz", // will be truncated to 8 characters
EntitySubscript = 15
};
file.Entities.Add(line);
VerifyFileContains(file, @"
110 1 0 0 0 00000000D 1
110 0 0 1 0 abcdefgh 15D 2
110,0.,0.,0.,0.,0.,0.; 1P 1
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteSpecificGlobalValuesTest()
{
var file = new IgesFile()
{
FieldDelimiter = ',',
RecordDelimiter = ';',
Identification = "identifier",
FullFileName = @"C:\path\to\full\filename.igs",
SystemIdentifier = "abcd",
SystemVersion = "1.0",
IntegerSize = 16,
SingleSize = 7,
DecimalDigits = 22,
DoubleMagnitude = 10,
DoublePrecision = 51,
Identifier = "ident2",
ModelSpaceScale = 0.75,
ModelUnits = IgesUnits.Centimeters,
CustomModelUnits = null,
MaxLineWeightGraduations = 4,
MaxLineWeight = 0.8,
TimeStamp = new DateTime(2000, 12, 25, 13, 8, 11),
MinimumResolution = 0.001,
MaxCoordinateValue = 500.0,
Author = "Brett",
Organization = "IxMilia",
IgesVersion = IgesVersion.v5_0,
DraftingStandard = IgesDraftingStandard.BSI,
ModifiedTime = new DateTime(1987, 5, 8, 12, 34, 56),
ApplicationProtocol = "protocol"
};
VerifyFileExactly(file, @"
S 1
1H,,1H;,10Hidentifier,28HC:\path\to\full\filename.igs,4Habcd,3H1.0,16,7,G 1
22,10,51,6Hident2,0.75,10,,4,0.8,15H20001225.130811,0.001,500.,5HBrett, G 2
7HIxMilia,8,4,15H19870508.123456,8Hprotocol; G 3
S 1G 3D 0P 0 T 1
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteFileWithNonStandardDelimitersTest()
{
var file = new IgesFile()
{
FieldDelimiter = '/',
RecordDelimiter = '#',
};
file.Entities.Add(new IgesLine());
// verify global section uses appropriate delimiters
VerifyFileContains(file, "1H//1H#/");
// verify entity writing uses appropriate delimiters
VerifyFileContains(file, "110/0./0./0./0./0./0.# 1P 1");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteCommonPointersTest()
{
// all other write tests validate the case where there are no common pointers
var line = new IgesLine();
line.AssociatedEntities.Add(new IgesLabelDisplayAssociativity());
line.AssociatedEntities.Add(new IgesGeneralNote());
line.AssociatedEntities.Add(new IgesTextDisplayTemplate());
line.Properties.Add(new IgesLocation());
var file = new IgesFile();
file.Entities.Add(line);
VerifyFileContains(file, @"
402 1 0 0 0 00000000D 1
402 0 0 1 5 D 2
212 2 0 0 0 00000100D 3
212 0 0 1 0 D 4
312 3 0 0 0 00000200D 5
312 0 0 1 0 D 6
116 4 0 0 0 00000000D 7
116 0 0 1 0 D 8
110 5 0 0 0 00000000D 9
110 0 0 1 0 D 10
402,0; 1P 1
212,0; 3P 2
312,0.,0.,1,0.,0.,0,0,0.,0.,0.; 5P 3
116,0.,0.,0.; 7P 4
110,0.,0.,0.,0.,0.,0.,3,1,3,5,1,7; 9P 5
");
// no properties
line.Properties.Clear();
VerifyFileContains(file, @"
402 1 0 0 0 00000000D 1
402 0 0 1 5 D 2
212 2 0 0 0 00000100D 3
212 0 0 1 0 D 4
312 3 0 0 0 00000200D 5
312 0 0 1 0 D 6
110 4 0 0 0 00000000D 7
110 0 0 1 0 D 8
402,0; 1P 1
212,0; 3P 2
312,0.,0.,1,0.,0.,0,0,0.,0.,0.; 5P 3
110,0.,0.,0.,0.,0.,0.,3,1,3,5; 7P 4
");
// no associated entities
line.AssociatedEntities.Clear();
line.Properties.Add(new IgesLocation());
VerifyFileContains(file, @"
116 1 0 0 0 00000000D 1
116 0 0 1 0 D 2
110 2 0 0 0 00000000D 3
110 0 0 1 0 D 4
116,0.,0.,0.; 1P 1
110,0.,0.,0.,0.,0.,0.,0,1,1; 3P 2
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Writing)]
public void WriteOnlyNewlinesTest()
{
var file = new IgesFile();
file.Entities.Add(new IgesLine(new IgesPoint(0.0, 0.0, 0.0), new IgesPoint(1.0, 1.0, 1.0)));
using (var ms = new MemoryStream())
{
file.Save(ms);
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms))
{
var text = reader.ReadToEnd();
Assert.DoesNotContain("\r", text);
}
}
}
}
}
| |
/**
The new controller will go through a basic round robin
free-inject&throttle test to obtain each application's sensitivity to
throttling. The number of this test can be specified through
config.apps_test_freq.
If the application is not sensitive(small ipc differnece),
it will be put into an always-throttled cluster. The old mechanism that
divides applications into low and high cluster is still intact. The
additional cluster is just the always throttled cluster. The
controller tests the application sensitivity every several sampling
periods(config.sampling_period_freq).
**/
//#define DEBUG_NETUTIL
//#define DEBUG
#define DEBUG_CLUSTER
#define DEBUG_CLUSTER2
using System;
using System.Collections.Generic;
namespace ICSimulator
{
public class Controller_Three_Level_LowBin_Cluster: Controller_Adaptive_Cluster
{
public static int num_throttle_periods;
public static int num_test_phases;
public static bool isTestPhase;
//nodes in these clusters are always throttled without given it a free injection slot!
public static Cluster throttled_cluster;
public static Cluster low_intensity_cluster;
/* Stats for applications' sensitivity to throttling test */
public static double[] ipc_accum_diff=new double[Config.N];
//total ipc retired during every free injection slot
public static double[] ipc_free=new double[Config.N];
public static double[] ipc_throttled=new double[Config.N];
public static ulong[] ins_free=new ulong[Config.N];
public static ulong[] ins_throttled=new ulong[Config.N];
public static int[] last_free_nodes=new int[Config.N];
//override the cluster_pool defined in Batch Controller!
public static new UniformBatchClusterPool cluster_pool;
string getName(int ID)
{
return Simulator.network.workload.getName(ID);
}
void writeNode(int ID)
{
Console.Write("{0} ({1}) ", ID, getName(ID));
}
public Controller_Three_Level_LowBin_Cluster()
{
isThrottling = false;
for (int i = 0; i < Config.N; i++)
{
//initialization on stats for the test
ipc_accum_diff[i]=0.0;
ipc_free[i]=0.0;
ipc_throttled[i]=0.0;
ins_free[i]=0;
ins_throttled[i]=0;
last_free_nodes[i]=0;
//test phase timing
num_throttle_periods=0;
num_test_phases=0;
isTestPhase=false;
MPKI[i]=0.0;
num_ins_last_epoch[i]=0;
m_isThrottled[i]=false;
L1misses[i]=0;
lastNetUtil = 0;
}
throttled_cluster=new Cluster();
low_intensity_cluster=new Cluster();
cluster_pool=new UniformBatchClusterPool(Config.cluster_MPKI_threshold);
}
public override void doThrottling()
{
//All nodes in the low intensity can alway freely inject.
int [] low_nodes=low_intensity_cluster.allNodes();
if(low_nodes.Length>0 && isTestPhase==true)
{
low_intensity_cluster.printCluster();
throw new Exception("ERROR: Low nodes exist during sensitivity test phase.");
}
if(low_nodes.Length>0)
{
#if DEBUG_CLUSTER2
Console.WriteLine("\n:: cycle {0} ::", Simulator.CurrentRound);
Console.Write("\nLow nodes *NOT* throttled: ");
double mpki_low=0.0;
#endif
foreach (int node in low_nodes)
{
#if DEBUG_CLUSTER2
writeNode(node);
mpki_low+=MPKI[node];
#endif
setThrottleRate(node,false);
m_nodeStates[node] = NodeState.Low;
}
#if DEBUG_CLUSTER2
Console.Write(" TOTAL MPKI: {0}",mpki_low);
#endif
}
//Throttle all the high other nodes
int [] high_nodes=cluster_pool.allNodes();
#if DEBUG_CLUSTER2
Console.Write("\nAll high other nodes: ");
#endif
foreach (int node in high_nodes)
{
#if DEBUG_CLUSTER2
writeNode(node);
#endif
setThrottleRate(node,true);
m_nodeStates[node] = NodeState.HighOther;
}
//Unthrottle all the nodes in the free-injecting cluster
int [] nodes=cluster_pool.nodesInNextCluster();
#if DEBUG_CLUSTER2
Console.Write("\nUnthrottling cluster nodes: ");
double mpki=0.0;
#endif
if(nodes.Length>0)
{
//Clear the vector for last free nodes
Array.Clear(last_free_nodes,0,last_free_nodes.Length);
foreach (int node in nodes)
{
ins_free[node]=(ulong)Simulator.stats.insns_persrc[node].Count;
last_free_nodes[node]=1;
setThrottleRate(node,false);
m_nodeStates[node] = NodeState.HighGolden;
Simulator.stats.throttle_time_bysrc[node].Add();
#if DEBUG_CLUSTER2
mpki+=MPKI[node];
writeNode(node);
#endif
}
#if DEBUG_CLUSTER2
Console.Write(" TOTAL MPKI: {0}",mpki);
#endif
}
/* Throttle nodes in always throttled mode. */
int [] throttled_nodes=throttled_cluster.allNodes();
if(throttled_nodes.Length>0 && isTestPhase==true)
{
throttled_cluster.printCluster();
throw new Exception("ERROR: Throttled nodes exist during sensitivity test phase.");
}
if(throttled_nodes.Length>0)
{
#if DEBUG_CLUSTER2
Console.Write("\nAlways Throttled nodes: ");
#endif
foreach (int node in throttled_nodes)
{
setThrottleRate(node,true);
//TODO: need another state for throttled throttled_nodes
m_nodeStates[node] = NodeState.AlwaysThrottled;
Simulator.stats.always_throttle_time_bysrc[node].Add();
#if DEBUG_CLUSTER2
writeNode(node);
#endif
}
}
#if DEBUG_CLUSTER2
double mpki_all=0.0;
Console.Write("\n*NOT* Throttled nodes: ");
for(int i=0;i<Config.N;i++)
if(!m_isThrottled[i])
{
writeNode(i);
mpki_all+=MPKI[i];
}
Console.Write(" TOTAL MPKI: {0}",mpki_all);
Console.Write("\n");
#endif
}
public void collectIPCDiff()
{
#if DEBUG_CLUSTER
Console.WriteLine("\n***COLLECT IPC DIFF*** CYCLE{0}",Simulator.CurrentRound);
#endif
int free_inj_count=Config.throttle_sampling_period/Config.interval_length/Config.N;
int throttled_inj_count=(Config.throttle_sampling_period/Config.interval_length)-free_inj_count;
for(int i=0;i<Config.N;i++)
{
ipc_free[i]/=free_inj_count;
ipc_throttled[i]/=throttled_inj_count;
double temp_ipc_diff;
if(ipc_free[i]==0)
temp_ipc_diff=0;
else
temp_ipc_diff=(ipc_free[i]==0)?0:(ipc_free[i]-ipc_throttled[i])/ipc_throttled[i];
//record the % difference
ipc_accum_diff[i]+=temp_ipc_diff;
Simulator.stats.ipc_diff_bysrc[i].Add(temp_ipc_diff);
#if DEBUG_CLUSTER
Console.Write("id:");
writeNode(i);
Console.WriteLine("ipc_free:{0} ipc_th:{1} ipc free gain:{2}%",
ipc_free[i],ipc_throttled[i],(int)(temp_ipc_diff*100));
#endif
//Reset
//ipc_accum_diff[i]=0.0;
ipc_free[i]=0.0;
ipc_throttled[i]=0.0;
ins_free[i]=0;
ins_throttled[i]=0;
last_free_nodes[i]=0;
}
}
public void updateInsCount()
{
#if DEBUG_CLUSTER
Console.WriteLine("***Update instructions count*** CYCLE{0}",Simulator.CurrentRound);
#endif
for(int node=0;node<Config.N;node++)
{
/* Calculate IPC during the last free-inject and throtttled interval */
if(ins_throttled[node]==0)
ins_throttled[node]=(ulong)Simulator.stats.insns_persrc[node].Count;
if(last_free_nodes[node]==1)
{
ulong ins_retired=(ulong)Simulator.stats.insns_persrc[node].Count-ins_free[node];
ipc_free[node]+=(double)ins_retired/Config.interval_length;
#if DEBUG_CLUSTER
Console.Write("Free calc: Node ");
writeNode(node);
Console.WriteLine(" w/ ins {0}->{2} retired {1}::IPC accum:{3}",
ins_free[node],ins_retired,Simulator.stats.insns_persrc[node].Count,
ipc_free[node]);
#endif
}
else
{
ulong ins_retired=(ulong)Simulator.stats.insns_persrc[node].Count-ins_throttled[node];
ipc_throttled[node]+=(double)ins_retired/Config.interval_length;
}
ins_throttled[node]=(ulong)Simulator.stats.insns_persrc[node].Count;
}
}
/* Need to have a better dostep function along with RR monitor phase.
* Also need to change setthrottle and dothrottle*/
public override void doStep()
{
//Gather stats at the beginning of next sampling period.
if(isTestPhase==true)
{
if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)Config.interval_length) == 0)
updateInsCount();
//Obtain the ipc difference between free injection and throttled.
if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0)
collectIPCDiff();
}
//sampling period: Examine the network state and determine whether to throttle or not
if (Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0)
{
setThrottling();
lastNetUtil = Simulator.stats.netutil.Total;
resetStat();
}
//once throttle mode is turned on. Let each cluster run for a certain time interval
//to ensure fairness. Otherwise it's throttled most of the time.
if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)Config.interval_length) == 0)
doThrottling();
}
public override void setThrottling()
{
#if DEBUG_NETUTIL
Console.Write("\n:: cycle {0} ::",
Simulator.CurrentRound);
#endif
//get the MPKI value
for (int i = 0; i < Config.N; i++)
{
prev_MPKI[i]=MPKI[i];
if(num_ins_last_epoch[i]==0)
MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count);
else
{
if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]>0)
MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]);
else if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]==0)
MPKI[i]=0;
else
throw new Exception("MPKI error!");
}
}
recordStats();
if(isThrottling)
{
double netutil=((double)(Simulator.stats.netutil.Total-lastNetUtil)/(double)Config.throttle_sampling_period);
#if DEBUG_NETUTIL
Console.WriteLine("In throttle mode: avg netUtil = {0} thres at {1}",
netutil,Config.netutil_throttling_threshold);
#endif
/* TODO:
* 1.If the netutil remains high, lower the threshold value for each cluster
* to reduce the netutil further more and create a new pool/schedule for
* all the clusters. How to raise it back?
* Worst case: 1 app per cluster.
*
* 2.Find the difference b/w the current netutil and the threshold.
* Then increase the throttle rate for each cluster based on that difference.
*
* 3.maybe add stalling clusters?
* */
isThrottling=false;
//un-throttle the network
for(int i=0;i<Config.N;i++)
setThrottleRate(i,false);
//Clear all the clusters
#if DEBUG_CLUSTER
Console.WriteLine("cycle {0} ___Clear clusters___",Simulator.CurrentRound);
#endif
cluster_pool.removeAllClusters();
throttled_cluster.removeAllNodes();
low_intensity_cluster.removeAllNodes();
double diff=netutil-Config.netutil_throttling_threshold;
//Option1: adjust the mpki thresh for each cluster
//if netutil within range of 10% increase MPKI boundary for each cluster
if(Config.adaptive_cluster_mpki)
{
double new_MPKI_thresh=cluster_pool.clusterThreshold();
if(diff<0.10)
new_MPKI_thresh+=10;
else if(diff>0.2)
new_MPKI_thresh-=20;
cluster_pool.changeThresh(new_MPKI_thresh);
}
//Option2: adjust the throttle rate
//
//
//Use alpha*total_MPKI+base to find the optimal netutil for performance
//0.5 is the baseline netutil threshold
//0.03 is calculated empricically using some base cases to find this number b/w total_mpki and target netutil
double total_mpki=0.0;
for(int i=0;i<Config.N;i++)
total_mpki+=MPKI[i];
double target_netutil=(0.03*total_mpki+50)/100;
//50% baseline
if(Config.alpha)
{
//within 2% range
if(netutil<(0.98*target_netutil))
Config.RR_throttle_rate-=0.02;
else if(netutil>(1.02*target_netutil))
if(Config.RR_throttle_rate<0.95)//max is 95%
Config.RR_throttle_rate+=0.01;
//if target is too high, only throttle max to 95% inj rate
if(target_netutil>0.9)
Config.RR_throttle_rate=0.95;
}
//Trying to force 60-70% netutil
if(Config.adaptive_rate)
{
if(diff<0.1)
Config.RR_throttle_rate-=0.02;
else if(diff>0.2)
if(Config.RR_throttle_rate<0.95)
Config.RR_throttle_rate+=0.01;
}
#if DEBUG_NETUTIL
Console.WriteLine("Netutil diff: {2}-{3}={1} New th rate:{0} New MPKI thresh: {6} Target netutil:{4} Total MPKI:{5}",
Config.RR_throttle_rate,diff,
netutil,Config.netutil_throttling_threshold,target_netutil,total_mpki,cluster_pool.clusterThreshold());
#endif
Simulator.stats.total_th_rate.Add(Config.RR_throttle_rate);
}
#if DEBUG_CLUSTER
Console.WriteLine("***SET THROTTLING Thresh trigger point*** CYCLE{0}",Simulator.CurrentRound);
#endif
//TODO: test phase can also reduce the mpki,so...might not have consecutive test phases
if (thresholdTrigger()) // an abstract fn() that trigger whether to start throttling or not
{
#if DEBUG_CLUSTER
Console.WriteLine("Congested!! Trigger throttling! isTest {0}, num th {1}, num samp {2}",
isTestPhase,num_test_phases,num_throttle_periods);
#endif
#if DEBUG_CLUSTER
Console.WriteLine("cycle {0} ___Clear clusters___",Simulator.CurrentRound);
#endif
cluster_pool.removeAllClusters();
throttled_cluster.removeAllNodes();
low_intensity_cluster.removeAllNodes();
///////State Trasition
//Initial state
if(num_throttle_periods==0&&num_test_phases==0&&Config.use_ipc_delta)
isTestPhase=true;
//From test->cluster throttling
if(isTestPhase && num_test_phases==Config.apps_test_freq)
{
isTestPhase=false;
num_test_phases=0;
}
//From cluster throttling->test
if(num_throttle_periods==Config.sampling_period_freq)
{
//reset ipc_accum_diff
for(int node_id=0;node_id<Config.N;node_id++)
ipc_accum_diff[node_id]=0.0;
isTestPhase=true;
num_throttle_periods=0;
}
///////Cluster Distribution
if(isTestPhase==true)
{
num_test_phases++;
//Add every node to high cluster
int total_high = 0;
double total_mpki=0.0;
for (int i = 0; i < Config.N; i++)
{
total_mpki+=MPKI[i];
cluster_pool.addNewNodeUniform(i,MPKI[i]);
total_high++;
#if DEBUG
Console.Write("#ON#:Node {0} with MPKI {1} ",i,MPKI[i]);
#endif
}
Simulator.stats.total_sum_mpki.Add(total_mpki);
#if DEBUG
Console.WriteLine(")");
#endif
//if no node needs to be throttled, set throttling to false
isThrottling = (total_high>0)?true:false;
#if DEBUG_CLUSTER
cluster_pool.printClusterPool();
#endif
}
else
{
//Increment the number of throttle periods so that the test phase can kick back
//in after certain number of throttle periods.
num_throttle_periods++;
List<int> sortedList = new List<int>();
double total_mpki=0.0;
double small_mpki=0.0;
double current_allow=0.0;
int total_high=0;
for(int i=0;i<Config.N;i++)
{
sortedList.Add(i);
total_mpki+=MPKI[i];
//stats recording-see what's the total mpki composed by low/med apps
if(MPKI[i]<=30)
small_mpki+=MPKI[i];
}
//sort by mpki
sortedList.Sort(CompareByMpki);
#if DEBUG_CLUSTER
for(int i=0;i<Config.N;i++)
Console.WriteLine("ID:{0} MPKI:{1}",sortedList[i],MPKI[sortedList[i]]);
Console.WriteLine("*****total MPKI: {0}",total_mpki);
Console.WriteLine("*****total MPKIs of apps with MPKI<30: {0}\n",small_mpki);
#endif
//1:low 2:high 3:always
int [] binVector = new int [Config.N];
//find the first few apps that will be allowed to run freely without being throttled
for(int list_index=0;list_index<Config.N;list_index++)
{
int node_id=sortedList[list_index];
//add the node that has no performance gain from free injection slot to
//always throttled cluster.
double ipc_avg_diff=ipc_accum_diff[node_id]/Config.apps_test_freq;
#if DEBUG_CLUSTER
Console.WriteLine("Node {0} with ipc diff {1}",node_id,ipc_avg_diff*100);
#endif
//If an application doesn't fit into one cluster, it will always be throttled
if((Config.use_ipc_delta && ipc_avg_diff<Config.sensitivity_threshold) || (Config.use_cluster_threshold && MPKI[node_id]>Config.cluster_MPKI_threshold))
{
#if DEBUG_CLUSTER
Console.WriteLine("->Throttled node: {0}",node_id);
#endif
throttled_cluster.addNode(node_id,MPKI[node_id]);
binVector[node_id]=3;
}
}
//Find the best bining for low nodes
int [] low_nodes=bestBin(Config.free_total_MPKI,binVector,false);
foreach (int node_id in low_nodes)
{
#if DEBUG_CLUSTER
Console.WriteLine("->Low node: {0}",node_id);
#endif
low_intensity_cluster.addNode(node_id,MPKI[node_id]);
binVector[node_id]=1;
}
for(int i=0;i<Config.N;i++)
{
if(binVector[i]==0)
{
#if DEBUG_CLUSTER
Console.WriteLine("->High node: {0}",i);
#endif
cluster_pool.addNewNode(i,MPKI[i]);
total_high++;
}
}
#if DEBUG_CLUSTER
Console.WriteLine("total high: {0}\n",total_high);
#endif
//STATS
Simulator.stats.allowed_sum_mpki.Add(current_allow);
Simulator.stats.total_sum_mpki.Add(total_mpki);
sortedList.Clear();
isThrottling = (total_high>0)?true:false;
#if DEBUG_CLUSTER
cluster_pool.printClusterPool();
#endif
}
}
}
public int[] bestBin(double mpki_target, int []binVector, bool mpki_prio)
{
//find all the possible candidates to put in the low intensity cluster
List<int> lowApps=new List<int>();
int i,shift,best_match=0;
for(i=0;i<Config.N;i++)
if(binVector[i]!=3 && MPKI[i]<mpki_target)
lowApps.Add(i);
double cur_diff=mpki_target;
int cur_num_apps=0;
//0 to 2^(num apps)-1 combinations
Console.WriteLine("Total apps to bin:{0}",lowApps.Count);
for(i=0;i<=Math.Pow(2,lowApps.Count)-1;i++)
{
uint num=(uint)i;
double mpki_sum=0;
int num_apps=0;
double diff=mpki_target;
shift=0;
while(num!=0)
{
if(((num)&(0x1))==1)
{
mpki_sum+=MPKI[lowApps[shift]];
num_apps++;
}
//uint is logical right shift
num>>=1;
shift++;
}
//Console.WriteLine("Index:{0} target:{1} sum:{2}",i,mpki_target,mpki_sum);
if(mpki_sum>mpki_target)
continue;
diff=mpki_target-mpki_sum;
//trying to get the maximum mpki count
if(mpki_prio==true)
{
if(diff<cur_diff)
{
cur_diff=diff;
cur_num_apps=num_apps;
best_match=i;
continue;
}
//tie-breaker
if(diff==cur_diff)
{
if(num_apps>cur_num_apps)
{
cur_diff=diff;
cur_num_apps=num_apps;
best_match=i;
}
}
}
else //max apps count
{
if(num_apps>cur_num_apps)
{
cur_diff=diff;
cur_num_apps=num_apps;
best_match=i;
continue;
}
if(num_apps==cur_num_apps)
{
if(diff<cur_diff)
{
cur_diff=diff;
cur_num_apps=num_apps;
best_match=i;
}
}
}
}
Console.Write("Best match: index:{0} NODES:",best_match);
List<int> lowIntenseApps=new List<int>();
shift=0;
double mpki=0;
while(best_match!=0)
{
if(((best_match)&0x1)==1)
{
lowIntenseApps.Add(lowApps[shift]);
Console.Write("{0} ",lowApps[shift]);
mpki+=MPKI[lowApps[shift]];
}
//uint is logical right shift
best_match>>=1;
shift++;
}
Console.WriteLine(" MPKI:{0}",mpki);
return lowIntenseApps.ToArray();
}
}
}
| |
using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using Thinktecture.Text;
// ReSharper disable AssignNullToNotNullAttribute
namespace Thinktecture.IO.Adapters
{
/// <summary>
/// Adapter for <see cref="StreamReader"/>.
/// </summary>
public class StreamReaderAdapter : TextReaderAdapter, IStreamReader
{
/// <summary>A <see cref="T:System.IO.StreamReader" /> object around an empty stream.</summary>
public new static readonly IStreamReader Null = new StreamReaderAdapter(StreamReader.Null);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public new StreamReader UnsafeConvert()
{
return Implementation;
}
/// <summary>
/// Implementation used by the adapter.
/// </summary>
protected new StreamReader Implementation { get; }
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream.</summary>
/// <param name="stream">The stream to be read. </param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="stream" /> does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> is null. </exception>
public StreamReaderAdapter(IStream stream)
: this(stream.ToImplementation())
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream.</summary>
/// <param name="stream">The stream to be read. </param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="stream" /> does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> is null. </exception>
public StreamReaderAdapter(Stream stream)
: this(new StreamReader(stream))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified byte order mark detection option.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="stream" /> does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> is null. </exception>
public StreamReaderAdapter(IStream stream, bool detectEncodingFromByteOrderMarks)
: this(stream.ToImplementation(), detectEncodingFromByteOrderMarks)
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified byte order mark detection option.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="stream" /> does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> is null. </exception>
public StreamReaderAdapter(Stream stream, bool detectEncodingFromByteOrderMarks)
: this(new StreamReader(stream, detectEncodingFromByteOrderMarks))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding and byte order mark detection option.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="stream" /> does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
public StreamReaderAdapter(IStream stream, IEncoding encoding, bool detectEncodingFromByteOrderMarks)
: this(stream.ToImplementation(), encoding.ToImplementation(), detectEncodingFromByteOrderMarks)
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding and byte order mark detection option.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="stream" /> does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
public StreamReaderAdapter(Stream stream, IEncoding encoding, bool detectEncodingFromByteOrderMarks)
: this(stream, encoding.ToImplementation(), detectEncodingFromByteOrderMarks)
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding and byte order mark detection option.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="stream" /> does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
public StreamReaderAdapter(IStream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
: this(stream.ToImplementation(), encoding, detectEncodingFromByteOrderMarks)
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding and byte order mark detection option.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="stream" /> does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
public StreamReaderAdapter(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
: this(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <param name="bufferSize">The minimum buffer size. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="bufferSize" /> is less than or equal to zero. </exception>
public StreamReaderAdapter(IStream stream, IEncoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
: this(stream.ToImplementation(), encoding.ToImplementation(), detectEncodingFromByteOrderMarks, bufferSize)
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <param name="bufferSize">The minimum buffer size. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="bufferSize" /> is less than or equal to zero. </exception>
public StreamReaderAdapter(Stream stream, IEncoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
: this(stream, encoding.ToImplementation(), detectEncodingFromByteOrderMarks, bufferSize)
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <param name="bufferSize">The minimum buffer size. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="bufferSize" /> is less than or equal to zero. </exception>
public StreamReaderAdapter(IStream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
: this(stream.ToImplementation(), encoding, detectEncodingFromByteOrderMarks, bufferSize)
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException"> <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
public StreamReaderAdapter(Stream stream, Encoding encoding)
: this(new StreamReader(stream, encoding))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException"> <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
public StreamReaderAdapter(Stream stream, IEncoding encoding)
: this(new StreamReader(stream, encoding.ToImplementation()))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
public StreamReaderAdapter(IStream stream, Encoding encoding)
: this(new StreamReader(stream.ToImplementation(), encoding))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
public StreamReaderAdapter(IStream stream, IEncoding encoding)
: this(new StreamReader(stream.ToImplementation(), encoding.ToImplementation()))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="path">The file path to be read. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
public StreamReaderAdapter(string path)
: this(new StreamReader(path))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="path">The file path to be read. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
public StreamReaderAdapter(string path, bool detectEncodingFromByteOrderMarks)
: this(new StreamReader(path, detectEncodingFromByteOrderMarks))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="path">The file path to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
public StreamReaderAdapter(string path, Encoding encoding)
: this(new StreamReader(path, encoding))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="path">The file path to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
public StreamReaderAdapter(string path, IEncoding encoding)
: this(new StreamReader(path, encoding.ToImplementation()))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="path">The file path to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
public StreamReaderAdapter(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
: this(new StreamReader(path, encoding, detectEncodingFromByteOrderMarks))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="path">The file path to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
public StreamReaderAdapter(string path, IEncoding encoding, bool detectEncodingFromByteOrderMarks)
: this(new StreamReader(path, encoding.ToImplementation(), detectEncodingFromByteOrderMarks))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="path">The file path to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <param name="bufferSize">The minimum buffer size. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
public StreamReaderAdapter(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
: this(new StreamReader(path, encoding, detectEncodingFromByteOrderMarks, bufferSize))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="path">The file path to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <param name="bufferSize">The minimum buffer size. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
public StreamReaderAdapter(string path, IEncoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
: this(new StreamReader(path, encoding.ToImplementation(), detectEncodingFromByteOrderMarks, bufferSize))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.</summary>
/// <param name="stream">The stream to be read. </param>
/// <param name="encoding">The character encoding to use. </param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file. </param>
/// <param name="bufferSize">The minimum buffer size. </param>
/// <exception cref="T:System.ArgumentException">The stream does not support reading. </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="bufferSize" /> is less than or equal to zero. </exception>
public StreamReaderAdapter(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
: this(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize))
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream based on the specified character encoding, byte order mark detection option, and buffer size, and optionally leaves the stream open.</summary>
/// <param name="stream">The stream to read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">true to look for byte order marks at the beginning of the file; otherwise, false.</param>
/// <param name="bufferSize">The minimum buffer size.</param>
/// <param name="leaveOpen">true to leave the stream open after the <see cref="T:System.IO.StreamReader" /> object is disposed; otherwise, false.</param>
public StreamReaderAdapter(IStream stream, IEncoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)
: this(stream.ToImplementation(), encoding.ToImplementation(), detectEncodingFromByteOrderMarks, bufferSize, leaveOpen)
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream based on the specified character encoding, byte order mark detection option, and buffer size, and optionally leaves the stream open.</summary>
/// <param name="stream">The stream to read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">true to look for byte order marks at the beginning of the file; otherwise, false.</param>
/// <param name="bufferSize">The minimum buffer size.</param>
/// <param name="leaveOpen">true to leave the stream open after the <see cref="T:System.IO.StreamReader" /> object is disposed; otherwise, false.</param>
public StreamReaderAdapter(Stream stream, IEncoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)
: this(stream, encoding.ToImplementation(), detectEncodingFromByteOrderMarks, bufferSize, leaveOpen)
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream based on the specified character encoding, byte order mark detection option, and buffer size, and optionally leaves the stream open.</summary>
/// <param name="stream">The stream to read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">true to look for byte order marks at the beginning of the file; otherwise, false.</param>
/// <param name="bufferSize">The minimum buffer size.</param>
/// <param name="leaveOpen">true to leave the stream open after the <see cref="T:System.IO.StreamReader" /> object is disposed; otherwise, false.</param>
public StreamReaderAdapter(IStream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)
: this(stream.ToImplementation(), encoding, detectEncodingFromByteOrderMarks, bufferSize, leaveOpen)
{
}
/// <summary>Initializes a new instance of the <see cref="StreamReaderAdapter" /> class for the specified stream based on the specified character encoding, byte order mark detection option, and buffer size, and optionally leaves the stream open.</summary>
/// <param name="stream">The stream to read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">true to look for byte order marks at the beginning of the file; otherwise, false.</param>
/// <param name="bufferSize">The minimum buffer size.</param>
/// <param name="leaveOpen">true to leave the stream open after the <see cref="T:System.IO.StreamReader" /> object is disposed; otherwise, false.</param>
public StreamReaderAdapter(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)
: this(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, leaveOpen))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StreamReaderAdapter" /> class.
/// </summary>
/// <param name="reader">Reader to be used by the adapter.</param>
public StreamReaderAdapter(StreamReader reader)
: base(reader)
{
Implementation = reader ?? throw new ArgumentNullException(nameof(reader));
}
/// <inheritdoc />
public IStream BaseStream => Implementation.BaseStream.ToInterface();
/// <inheritdoc />
public IEncoding CurrentEncoding => Implementation.CurrentEncoding.ToInterface();
/// <inheritdoc />
public bool EndOfStream => Implementation.EndOfStream;
/// <inheritdoc />
public void DiscardBufferedData()
{
Implementation.DiscardBufferedData();
}
}
}
| |
using System;
using System.Linq;
using Signum.Utilities;
using Signum.Entities.UserAssets;
using Signum.Entities.Chart;
using System.Reflection;
using System.Xml.Linq;
using Signum.Utilities.DataStructures;
using Signum.Entities.UserQueries;
using Signum.Entities;
using System.Linq.Expressions;
using Signum.Entities.Basics;
namespace Signum.Entities.Dashboard
{
[Serializable]
public class PanelPartEmbedded : EmbeddedEntity, IGridEntity
{
[StringLengthValidator(Min = 3, Max = 100)]
public string? Title { get; set; }
[StringLengthValidator(Min = 3, Max = 100)]
public string? IconName { get; set; }
[StringLengthValidator(Min = 3, Max = 100)]
public string? IconColor { get; set; }
[NumberIsValidator(ComparisonType.GreaterThanOrEqualTo, 0)]
public int Row { get; set; }
[NumberBetweenValidator(0, 11)]
public int StartColumn { get; set; }
[NumberBetweenValidator(1, 12)]
public int Columns { get; set; }
public BootstrapStyle Style { get; set; }
[ImplementedBy(
typeof(UserChartPartEntity),
typeof(CombinedUserChartPartEntity),
typeof(UserQueryPartEntity),
typeof(ValueUserQueryListPartEntity),
typeof(LinkListPartEntity))]
public IPartEntity Content { get; set; }
public override string ToString()
{
return Title.HasText() ? Title :
Content==null?"":
Content.ToString()!;
}
protected override string? PropertyValidation(PropertyInfo pi)
{
if (pi.Name == nameof(Title) && string.IsNullOrEmpty(Title))
{
if (Content != null && Content.RequiresTitle)
return DashboardMessage.DashboardDN_TitleMustBeSpecifiedFor0.NiceToString().FormatWith(Content.GetType().NicePluralName());
}
return base.PropertyValidation(pi);
}
public PanelPartEmbedded Clone()
{
return new PanelPartEmbedded
{
Columns = Columns,
StartColumn = StartColumn,
Content = Content.Clone(),
Title = Title,
Row = Row,
Style = Style,
};
}
internal void NotifyRowColumn()
{
Notify(() => StartColumn);
Notify(() => Columns);
}
internal XElement ToXml(IToXmlContext ctx)
{
return new XElement("Part",
new XAttribute("Row", Row),
new XAttribute("StartColumn", StartColumn),
new XAttribute("Columns", Columns),
Title == null ? null! : new XAttribute("Title", Title),
IconName == null ? null! : new XAttribute("IconName", IconName),
IconColor == null ? null! : new XAttribute("IconColor", IconColor),
new XAttribute("Style", Style),
Content.ToXml(ctx));
}
internal void FromXml(XElement x, IFromXmlContext ctx)
{
Row = int.Parse(x.Attribute("Row")!.Value);
StartColumn = int.Parse(x.Attribute("StartColumn")!.Value);
Columns = int.Parse(x.Attribute("Columns")!.Value);
Title = x.Attribute("Title")?.Value;
IconName = x.Attribute("IconName")?.Value;
IconColor = x.Attribute("IconColor")?.Value;
Style = (BootstrapStyle)(x.Attribute("Style")?.Let(a => Enum.Parse(typeof(BootstrapStyle), a.Value)) ?? BootstrapStyle.Light);
Content = ctx.GetPart(Content, x.Elements().Single());
}
internal Interval<int> ColumnInterval()
{
return new Interval<int>(this.StartColumn, this.StartColumn + this.Columns);
}
}
public interface IGridEntity
{
int Row { get; set; }
int StartColumn { get; set; }
int Columns { get; set; }
}
public interface IPartEntity : IEntity
{
bool RequiresTitle { get; }
IPartEntity Clone();
XElement ToXml(IToXmlContext ctx);
void FromXml(XElement element, IFromXmlContext ctx);
}
[Serializable, EntityKind(EntityKind.Part, EntityData.Master)]
public class UserQueryPartEntity : Entity, IPartEntity
{
public UserQueryEntity UserQuery { get; set; }
public UserQueryPartRenderMode RenderMode { get; set; }
public bool AllowSelection { get; set; }
public bool ShowFooter { get; set; }
public bool CreateNew { get; set; } = false;
[AutoExpressionField]
public override string ToString() => As.Expression(() => UserQuery + "");
public bool RequiresTitle
{
get { return false; }
}
public IPartEntity Clone()
{
return new UserQueryPartEntity
{
UserQuery = this.UserQuery,
RenderMode = this.RenderMode,
AllowSelection = this.AllowSelection,
ShowFooter = this.ShowFooter,
CreateNew = this.CreateNew,
};
}
public XElement ToXml(IToXmlContext ctx)
{
return new XElement("UserQueryPart",
new XAttribute("UserQuery", ctx.Include(UserQuery)),
new XAttribute("RenderMode", RenderMode.ToString()),
new XAttribute("AllowSelection", AllowSelection.ToString()),
new XAttribute("ShowFooter", ShowFooter.ToString()),
new XAttribute("CreateNew", CreateNew.ToString())
);
}
public void FromXml(XElement element, IFromXmlContext ctx)
{
UserQuery = (UserQueryEntity)ctx.GetEntity(Guid.Parse(element.Attribute("UserQuery")!.Value));
RenderMode = element.Attribute("RenderMode")?.Value.ToEnum<UserQueryPartRenderMode>() ?? UserQueryPartRenderMode.SearchControl;
AllowSelection = element.Attribute("AllowSelection")?.Value.ToBool() ?? true;
ShowFooter = element.Attribute("ShowFooter")?.Value.ToBool() ?? false;
CreateNew = element.Attribute("CreateNew")?.Value.ToBool() ?? false;
}
}
public enum UserQueryPartRenderMode
{
SearchControl,
BigValue,
}
[Serializable, EntityKind(EntityKind.Part, EntityData.Master)]
public class UserTreePartEntity : Entity, IPartEntity
{
public UserQueryEntity UserQuery { get; set; }
[AutoExpressionField]
public override string ToString() => As.Expression(() => UserQuery + "");
public bool RequiresTitle
{
get { return false; }
}
public IPartEntity Clone()
{
return new UserTreePartEntity
{
UserQuery = this.UserQuery,
};
}
public XElement ToXml(IToXmlContext ctx)
{
return new XElement("UserTreePart",
new XAttribute("UserQuery", ctx.Include(UserQuery))
);
}
public void FromXml(XElement element, IFromXmlContext ctx)
{
UserQuery = (UserQueryEntity)ctx.GetEntity(Guid.Parse(element.Attribute("UserQuery")!.Value));
}
}
[Serializable, EntityKind(EntityKind.Part, EntityData.Master)]
public class UserChartPartEntity : Entity, IPartEntity
{
public UserChartEntity UserChart { get; set; }
public bool ShowData { get; set; } = false;
public bool AllowChangeShowData { get; set; } = false;
public bool CreateNew { get; set; } = false;
public bool AutoRefresh { get; set; } = false;
[AutoExpressionField]
public override string ToString() => As.Expression(() => UserChart + "");
public bool RequiresTitle
{
get { return false; }
}
public IPartEntity Clone()
{
return new UserChartPartEntity
{
UserChart = this.UserChart,
ShowData = this.ShowData,
AllowChangeShowData = this.AllowChangeShowData,
};
}
public XElement ToXml(IToXmlContext ctx)
{
return new XElement("UserChartPart",
new XAttribute("ShowData", ShowData),
new XAttribute("AllowChangeShowData", AllowChangeShowData),
CreateNew ? new XAttribute("CreateNew", CreateNew) : null!,
AutoRefresh ? new XAttribute("AutoRefresh", AutoRefresh) : null!,
new XAttribute("UserChart", ctx.Include(UserChart)));
}
public void FromXml(XElement element, IFromXmlContext ctx)
{
ShowData = element.Attribute("ShowData")?.Value.ToBool() ?? false;
AllowChangeShowData = element.Attribute("AllowChangeShowData")?.Value.ToBool() ?? false;
CreateNew = element.Attribute("CreateNew")?.Value.ToBool() ?? false;
AutoRefresh = element.Attribute("AutoRefresh")?.Value.ToBool() ?? false;
UserChart = (UserChartEntity)ctx.GetEntity(Guid.Parse(element.Attribute("UserChart")!.Value));
}
}
[Serializable, EntityKind(EntityKind.Part, EntityData.Master)]
public class CombinedUserChartPartEntity : Entity, IPartEntity
{
[PreserveOrder, NoRepeatValidator]
public MList<UserChartEntity> UserCharts { get; set; } = new MList<UserChartEntity>();
public bool ShowData { get; set; } = false;
public bool AllowChangeShowData { get; set; } = false;
public bool CombinePinnedFiltersWithSameLabel { get; set; } = true;
public bool UseSameScale { get; set; }
public override string ToString()
{
return UserCharts.ToString(", ");
}
public bool RequiresTitle
{
get { return true; }
}
public IPartEntity Clone()
{
return new CombinedUserChartPartEntity
{
UserCharts = this.UserCharts.ToMList(),
};
}
public XElement ToXml(IToXmlContext ctx)
{
return new XElement("CombinedUserChartPart",
new XAttribute("ShowData", ShowData),
new XAttribute("AllowChangeShowData", AllowChangeShowData),
new XAttribute("CombinePinnedFiltersWithSameLabel", CombinePinnedFiltersWithSameLabel),
new XAttribute("UseSameScale", UseSameScale),
UserCharts.Select(uc => new XElement("UserChart", new XAttribute("Guid", ctx.Include(uc)))));
}
public void FromXml(XElement element, IFromXmlContext ctx)
{
var newUserCharts = element.Elements("UserChart").Select(uc => (UserChartEntity)ctx.GetEntity(Guid.Parse(uc.Attribute("Guid")!.Value))).ToList();
ShowData = element.Attribute("ShowData")?.Value.ToBool() ?? false;
AllowChangeShowData = element.Attribute("AllowChangeShowData")?.Value.ToBool() ?? false;
CombinePinnedFiltersWithSameLabel = element.Attribute("CombinePinnedFiltersWithSameLabel")?.Value.ToBool() ?? false;
UseSameScale = element.Attribute("UseSameScale")?.Value.ToBool() ?? false;
UserCharts.Synchronize(newUserCharts);
}
}
[Serializable, EntityKind(EntityKind.Part, EntityData.Master)]
public class ValueUserQueryListPartEntity : Entity, IPartEntity
{
public MList<ValueUserQueryElementEmbedded> UserQueries { get; set; } = new MList<ValueUserQueryElementEmbedded>();
public override string ToString()
{
return "{0} {1}".FormatWith(UserQueries.Count, typeof(UserQueryEntity).NicePluralName());
}
public bool RequiresTitle
{
get { return true; }
}
public IPartEntity Clone()
{
return new ValueUserQueryListPartEntity
{
UserQueries = this.UserQueries.Select(e => e.Clone()).ToMList(),
};
}
public XElement ToXml(IToXmlContext ctx)
{
return new XElement("ValueUserQueryListPart",
UserQueries.Select(cuqe => cuqe.ToXml(ctx)));
}
public void FromXml(XElement element, IFromXmlContext ctx)
{
UserQueries.Synchronize(element.Elements().ToList(), (cuqe, x) => cuqe.FromXml(x, ctx));
}
}
[Serializable]
public class ValueUserQueryElementEmbedded : EmbeddedEntity
{
[StringLengthValidator(Max = 200)]
public string? Label { get; set; }
public UserQueryEntity UserQuery { get; set; }
[StringLengthValidator(Max = 200)]
public string? Href { get; set; }
public ValueUserQueryElementEmbedded Clone()
{
return new ValueUserQueryElementEmbedded
{
Href = this.Href,
Label = this.Label,
UserQuery = UserQuery,
};
}
internal XElement ToXml(IToXmlContext ctx)
{
return new XElement("ValueUserQueryElement",
Label == null ? null! : new XAttribute("Label", Label),
Href == null ? null! : new XAttribute("Href", Href),
new XAttribute("UserQuery", ctx.Include(UserQuery)));
}
internal void FromXml(XElement element, IFromXmlContext ctx)
{
Label = element.Attribute("Label")?.Value;
Href = element.Attribute("Href")?.Value;
UserQuery = (UserQueryEntity)ctx.GetEntity(Guid.Parse(element.Attribute("UserQuery")!.Value));
}
}
[Serializable, EntityKind(EntityKind.Part, EntityData.Master)]
public class LinkListPartEntity : Entity, IPartEntity
{
public MList<LinkElementEmbedded> Links { get; set; } = new MList<LinkElementEmbedded>();
public override string ToString()
{
return "{0} {1}".FormatWith(Links.Count, typeof(LinkElementEmbedded).NicePluralName());
}
public bool RequiresTitle
{
get { return true; }
}
public IPartEntity Clone()
{
return new LinkListPartEntity
{
Links = this.Links.Select(e => e.Clone()).ToMList(),
};
}
public XElement ToXml(IToXmlContext ctx)
{
return new XElement("LinkListPart",
Links.Select(lin => lin.ToXml(ctx)));
}
public void FromXml(XElement element, IFromXmlContext ctx)
{
Links.Synchronize(element.Elements().ToList(), (le, x) => le.FromXml(x));
}
}
[Serializable]
public class LinkElementEmbedded : EmbeddedEntity
{
[StringLengthValidator(Max = 200)]
public string Label { get; set; }
[URLValidator(absolute: true, aspNetSiteRelative: true), StringLengthValidator(Max = int.MaxValue)]
public string Link { get; set; }
public LinkElementEmbedded Clone()
{
return new LinkElementEmbedded
{
Label = this.Label,
Link = this.Link
};
}
internal XElement ToXml(IToXmlContext ctx)
{
return new XElement("LinkElement",
new XAttribute("Label", Label),
new XAttribute("Link", Link));
}
internal void FromXml(XElement element)
{
Label = element.Attribute("Label")!.Value;
Link = element.Attribute("Link")!.Value;
}
}
}
| |
using System.Runtime.Serialization;
namespace GoogleApi.Entities.Common.Enums
{
/// <summary>
/// Place Location Types
/// https://developers.google.com/places/supported_types#table1
/// https://developers.google.com/places/supported_types#table2
/// </summary>
public enum PlaceLocationType
{
/// <summary>
/// Unknown is set when unmapped place location types is returned.
/// </summary>
[EnumMember(Value = "unknown")]
Uknown,
/// <summary>
/// Geocode instructs the Place Autocomplete service to return only geocoding results,
/// rather than business results. Generally, you use this request to disambiguate results where the location specified may be indeterminate.
/// </summary>
[EnumMember(Value = "geocode")]
Geocode,
/// <summary>
/// Indicates a precise street address.
/// </summary>
[EnumMember(Value = "street_address")]
Street_Address,
/// <summary>
/// Indicates a named route (such as "US 101").
/// </summary>
[EnumMember(Value = "route")]
Route,
/// <summary>
/// Indicates a major intersection, usually of two major roads.
/// </summary>
[EnumMember(Value = "intersection")]
Intersection,
/// <summary>
/// Indicates a political entity. Usually, this type indicates a polygon of some civil administration.
/// </summary>
[EnumMember(Value = "political")]
Political,
/// <summary>
/// Indicates the national political entity, and is typically the highest order type returned by the Geocoder.
/// </summary>
[EnumMember(Value = "country")]
Country,
/// <summary>
/// Indicates a first-order civil entity below the country level. Within the United States,
/// these administrative levels are states. Not all nations exhibit these administrative levels.
/// </summary>
[EnumMember(Value = "administrative_area_level_1")]
Administrative_Area_Level_1,
/// <summary>
/// Indicates a second-order civil entity below the country level. Within the United States,
/// these administrative levels are counties. Not all nations exhibit these administrative levels.
/// </summary>
[EnumMember(Value = "administrative_area_level_2")]
Administrative_Area_Level_2,
/// <summary>
/// Indicates a third-order civil entity below the country level. This type indicates a minor civil division.
/// Not all nations exhibit these administrative levels.
/// </summary>
[EnumMember(Value = "administrative_area_level_3")]
Administrative_Area_Level_3,
/// <summary>
/// Indicates a fourth-order civil entity below the country level. This type indicates a minor civil division.
/// Not all nations exhibit these administrative levels.
/// </summary>
[EnumMember(Value = "administrative_area_level_4")]
Administrative_Area_Level_4,
/// <summary>
/// Indicates a fifth-order civil entity below the country level. This type indicates a minor civil division.
/// Not all nations exhibit these administrative levels.
/// </summary>
[EnumMember(Value = "administrative_area_level_5")]
Administrative_Area_Level_5,
/// <summary>
/// Indicates a commonly-used alternative name for the entity.
/// </summary>
[EnumMember(Value = "colloquial_area")]
Colloquial_Area,
/// <summary>
/// Indicates an incorporated city or town political entity.
/// </summary>
[EnumMember(Value = "locality")]
Locality,
/// <summary>
/// locality.
/// </summary>
[EnumMember(Value = "sublocality")]
Sublocality,
/// <summary>
/// indicates an first-order civil entity below a locality.
/// </summary>
[EnumMember(Value = "sublocality_level_1")]
Sublocality_Level_1,
/// <summary>
/// indicates an second-order civil entity below a locality.
/// </summary>
[EnumMember(Value = "sublocality_level_2")]
Sublocality_Level_2,
/// <summary>
/// indicates an third-order civil entity below a locality.
/// </summary>
[EnumMember(Value = "sublocality_level_3")]
Sublocality_Level_3,
/// <summary>
/// indicates an first-order civil entity below a locality.
/// </summary>
[EnumMember(Value = "sublocality_level_4")]
Sublocality_Level_4,
/// <summary>
/// indicates an first-order civil entity below a locality.
/// </summary>
[EnumMember(Value = "sublocality_level_5")]
Sublocality_Level_5,
/// <summary>
/// Indicates a named neighborhood
/// </summary>
[EnumMember(Value = "neighborhood")]
Neighborhood,
/// <summary>
/// Indicates a named location, usually a building or collection of buildings with a common name.
/// </summary>
[EnumMember(Value = "premise")]
Premise,
/// <summary>
/// Indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a common name.
/// </summary>
[EnumMember(Value = "subpremise")]
Subpremise,
/// <summary>
/// Indicates a postal code as used to address postal mail within the country.
/// </summary>
[EnumMember(Value = "postal_code")]
Postal_Code,
/// <summary>
/// Indicates a postal code prefix.
/// </summary>
[EnumMember(Value = "postal_code_prefix")]
Postal_Code_Prefix,
/// <summary>
/// Indicates a postal code suffix.
/// </summary>
[EnumMember(Value = "postal_code_suffix")]
Postal_Code_Suffix,
/// <summary>
/// Indicates a prominent natural feature.
/// </summary>
[EnumMember(Value = "natural_feature")]
Natural_Feature,
/// <summary>
/// Indicates a named point of interest. Typically, these "POI"s are prominent local entities that don't easily fit in another category such as "Empire State Building" or "Statue of Liberty."
/// </summary>
[EnumMember(Value = "point_of_interest")]
Point_Of_Interest,
/// <summary>
/// Indicates the floor of a building address.
/// </summary>
[EnumMember(Value = "floor")]
Floor,
/// <summary>
/// post_box indicates a specific postal box.
/// </summary>
[EnumMember(Value = "post_box")]
Post_Box,
/// <summary>
/// postal_town indicates a grouping of geographic areas, such as locality and sublocality, used for mailing addresses in some countries.
/// </summary>
[EnumMember(Value = "postal_town")]
Postal_Town,
/// <summary>
/// room indicates the room of a building address.
/// </summary>
[EnumMember(Value = "room")]
Room,
/// <summary>
/// street_number indicates the precise street number.
/// </summary>
[EnumMember(Value = "street_number")]
Street_Number,
/// <summary>
/// Indicate the location of a public transit stop.
/// </summary>
[EnumMember(Value = "transit_station")]
Transit_Station,
/// <summary>
/// Accounting.
/// </summary>
[EnumMember(Value = "accounting")]
Accounting,
/// <summary>
/// Airport.
/// </summary>
[EnumMember(Value = "airport")]
Airport,
/// <summary>
/// Amusement Park.
/// </summary>
[EnumMember(Value = "amusement_park")]
Amusement_Park,
/// <summary>
/// Aquarium.
/// </summary>
[EnumMember(Value = "aquarium")]
Aquarium,
/// <summary>
/// Art Gallery.
/// </summary>
[EnumMember(Value = "art_gallery")]
Art_Gallery,
/// <summary>
/// Atm.
/// </summary>
[EnumMember(Value = "atm")]
Atm,
/// <summary>
/// Bakery.
/// </summary>
[EnumMember(Value = "bakery")]
Bakery,
/// <summary>
/// Bank.
/// </summary>
[EnumMember(Value = "bank")]
Bank,
/// <summary>
/// Bar.
/// </summary>
[EnumMember(Value = "bar")]
Bar,
/// <summary>
/// Beauty Salon.
/// </summary>
[EnumMember(Value = "beauty_salon")]
Beauty_Salon,
/// <summary>
/// Bicycle Store.
/// </summary>
[EnumMember(Value = "bicycle_store")]
Bicycle_Store,
/// <summary>
/// Book Store.
/// </summary>
[EnumMember(Value = "book_store")]
Book_Store,
/// <summary>
/// Bowling Alley.
/// </summary>
[EnumMember(Value = "bowling_alley")]
Bowling_Alley,
/// <summary>
/// Bus Station.
/// </summary>
[EnumMember(Value = "bus_station")]
Bus_Station,
/// <summary>
/// Cafe.
/// </summary>
[EnumMember(Value = "cafe")]
Cafe,
/// <summary>
/// Campground.
/// </summary>
[EnumMember(Value = "campground")]
Campground,
/// <summary>
/// Car Dealer.
/// </summary>
[EnumMember(Value = "car_dealer")]
Car_Dealer,
/// <summary>
/// Car Rental.
/// </summary>
[EnumMember(Value = "car_rental")]
Car_Rental,
/// <summary>
/// Car Repair.
/// </summary>
[EnumMember(Value = "car_repair")]
Car_Repair,
/// <summary>
/// Car Wash.
/// </summary>
[EnumMember(Value = "car_wash")]
Car_Wash,
/// <summary>
/// Casino.
/// </summary>
[EnumMember(Value = "casino")]
Casino,
/// <summary>
/// Cemetery.
/// </summary>
[EnumMember(Value = "cemetery")]
Cemetery,
/// <summary>
/// Church.
/// </summary>
[EnumMember(Value = "church")]
Church,
/// <summary>
/// City Hall.
/// </summary>
[EnumMember(Value = "city_hall")]
City_Hall,
/// <summary>
/// Clothing Store.
/// </summary>
[EnumMember(Value = "clothing_store")]
Clothing_Store,
/// <summary>
/// Convenience Store.
/// </summary>
[EnumMember(Value = "convenience_store")]
Convenience_Store,
/// <summary>
/// Courthouse.
/// </summary>
[EnumMember(Value = "courthouse")]
Courthouse,
/// <summary>
/// Dentist.
/// </summary>
[EnumMember(Value = "dentist")]
Dentist,
/// <summary>
/// Department Store.
/// </summary>
[EnumMember(Value = "department_store")]
Department_Store,
/// <summary>
/// Doctor.
/// </summary>
[EnumMember(Value = "doctor")]
Doctor,
/// <summary>
/// Electrician.
/// </summary>
[EnumMember(Value = "electrician")]
Electrician,
/// <summary>
/// Electronics Store.
/// </summary>
[EnumMember(Value = "electronics_store")]
Electronics_Store,
/// <summary>
/// Embassy.
/// </summary>
[EnumMember(Value = "embassy")]
Embassy,
/// <summary>
/// Establishment.
/// </summary>
[EnumMember(Value = "establishment")]
Establishment,
/// <summary>
/// Finance.
/// </summary>
[EnumMember(Value = "finance")]
Finance,
/// <summary>
/// Fire Station.
/// </summary>
[EnumMember(Value = "fire_station")]
Fire_Station,
/// <summary>
/// Florist.
/// </summary>
[EnumMember(Value = "florist")]
Florist,
/// <summary>
/// Food.
/// </summary>
[EnumMember(Value = "food")]
Food,
/// <summary>
/// Funeral Home.
/// </summary>
[EnumMember(Value = "funeral_home")]
Funeral_Home,
/// <summary>
/// Furniture Store.
/// </summary>
[EnumMember(Value = "furniture_store")]
Furniture_Store,
/// <summary>
/// Gas Station.
/// </summary>
[EnumMember(Value = "gas_station")]
Gas_Station,
/// <summary>
/// General Contractor.
/// </summary>
[EnumMember(Value = "general_contractor")]
General_Contractor,
/// <summary>
/// Supermarket.
/// </summary>
[EnumMember(Value = "supermarket")]
Supermarket,
/// <summary>
/// Grocery Or Supermarket.
/// </summary>
[EnumMember(Value = "grocery_or_supermarket")]
Grocery_Or_Supermarket,
/// <summary>
/// Gym.
/// </summary>
[EnumMember(Value = "gym")]
Gym,
/// <summary>
/// Hair Care.
/// </summary>
[EnumMember(Value = "hair_care")]
Hair_Care,
/// <summary>
/// Hardware Store.
/// </summary>
[EnumMember(Value = "hardware_store")]
Hardware_Store,
/// <summary>
/// Health.
/// </summary>
[EnumMember(Value = "health")]
Health,
/// <summary>
/// Hindu Temple.
/// </summary>
[EnumMember(Value = "hindu_temple")]
Hindu_Temple,
/// <summary>
/// Home Goods Store.
/// </summary>
[EnumMember(Value = "home_goods_store")]
Home_Goods_Store,
/// <summary>
/// Hospital.
/// </summary>
[EnumMember(Value = "hospital")]
Hospital,
/// <summary>
/// Insurance Agency.
/// </summary>
[EnumMember(Value = "insurance_agency")]
Insurance_Agency,
/// <summary>
/// Jewelry Store.
/// </summary>
[EnumMember(Value = "jewelry_store")]
Jewelry_Store,
/// <summary>
/// Laundry.
/// </summary>
[EnumMember(Value = "laundry")]
Laundry,
/// <summary>
/// Lawyer.
/// </summary>
[EnumMember(Value = "lawyer")]
Lawyer,
/// <summary>
/// Library.
/// </summary>
[EnumMember(Value = "library")]
Library,
/// <summary>
/// Liquor Store.
/// </summary>
[EnumMember(Value = "liquor_store")]
Liquor_Store,
/// <summary>
/// Local Government Office.
/// </summary>
[EnumMember(Value = "local_government_office")]
Local_Government_Office,
/// <summary>
/// Locksmith.
/// </summary>
[EnumMember(Value = "locksmith")]
Locksmith,
/// <summary>
/// Lodging.
/// </summary>
[EnumMember(Value = "lodging")]
Lodging,
/// <summary>
/// Meal Delivery.
/// </summary>
[EnumMember(Value = "meal_delivery")]
Meal_Delivery,
/// <summary>
///
/// </summary>
[EnumMember(Value = "meal_takeaway")]
Meal_Takeaway,
/// <summary>
/// Mosque.
/// </summary>
[EnumMember(Value = "mosque")]
Mosque,
/// <summary>
/// Movie Rental.
/// </summary>
[EnumMember(Value = "movie_rental")]
Movie_Rental,
/// <summary>
/// Movie Theater.
/// </summary>
[EnumMember(Value = "movie_theater")]
Movie_Theater,
/// <summary>
/// Moving Company.
/// </summary>
[EnumMember(Value = "moving_company")]
Moving_Company,
/// <summary>
/// Museum.
/// </summary>
[EnumMember(Value = "museum")]
Museum,
/// <summary>
/// Night Club.
/// </summary>
[EnumMember(Value = "night_club")]
Night_Club,
/// <summary>
/// Painter.
/// </summary>
[EnumMember(Value = "painter")]
Painter,
/// <summary>
/// Park.
/// </summary>
[EnumMember(Value = "park")]
Park,
/// <summary>
/// Parking.
/// </summary>
[EnumMember(Value = "parking")]
Parking,
/// <summary>
/// Pet Store.
/// </summary>
[EnumMember(Value = "pet_store")]
Pet_Store,
/// <summary>
/// Pharmacy.
/// </summary>
[EnumMember(Value = "pharmacy")]
Pharmacy,
/// <summary>
/// Physiotherapist.
/// </summary>
[EnumMember(Value = "physiotherapist")]
Physiotherapist,
/// <summary>
/// Place Of Worship.
/// </summary>
[EnumMember(Value = "place_of_worship")]
Place_Of_Worship,
/// <summary>
/// Plumber.
/// </summary>
[EnumMember(Value = "plumber")]
Plumber,
/// <summary>
/// Police.
/// </summary>
[EnumMember(Value = "police")]
Police,
/// <summary>
/// Post Office.
/// </summary>
[EnumMember(Value = "post_office")]
PostOffice,
/// <summary>
/// Real Estate Agency.
/// </summary>
[EnumMember(Value = "real_estate_agency")]
Real_Estate_Agency,
/// <summary>
/// Restaurant.
/// </summary>
[EnumMember(Value = "restaurant")]
Restaurant,
/// <summary>
/// Roofing Contractor.
/// </summary>
[EnumMember(Value = "roofing_contractor")]
Roofing_Contractor,
/// <summary>
/// Rv Park.
/// </summary>
[EnumMember(Value = "rv_park")]
Rv_Park,
/// <summary>
/// School.
/// </summary>
[EnumMember(Value = "school")]
School,
/// <summary>
///
/// </summary>
[EnumMember(Value = "shoe_store")]
Shoe_Store,
/// <summary>
/// Shopping Mall.
/// </summary>
[EnumMember(Value = "shopping_mall")]
Shopping_Mall,
/// <summary>
/// Spa.
/// </summary>
[EnumMember(Value = "spa")]
Spa,
/// <summary>
/// Stadium.
/// </summary>
[EnumMember(Value = "stadium")]
Stadium,
/// <summary>
/// Storage.
/// </summary>
[EnumMember(Value = "storage")]
Storage,
/// <summary>
/// Store-
/// </summary>
[EnumMember(Value = "store")]
Store,
/// <summary>
/// Subway Station.
/// </summary>
[EnumMember(Value = "subway_station")]
Subway_Station,
/// <summary>
/// Synagogue.
/// </summary>
[EnumMember(Value = "synagogue")]
Synagogue,
/// <summary>
/// Tourist Attracton.
/// </summary>
[EnumMember(Value = "tourist_attraction")]
Tourist_Attracton,
/// <summary>
/// Taxi Stand.
/// </summary>
[EnumMember(Value = "taxi_stand")]
Taxi_Stand,
/// <summary>
/// Train Station.
/// </summary>
[EnumMember(Value = "train_station")]
Train_Station,
/// <summary>
/// Travel Agency.
/// </summary>
[EnumMember(Value = "travel_agency")]
Travel_Agency,
/// <summary>
/// University.
/// </summary>
[EnumMember(Value = "university")]
University,
/// <summary>
/// VeterinaryCare.
/// </summary>
[EnumMember(Value = "veterinary_care")]
Veterinary_Care,
/// <summary>
/// Zoo.
/// </summary>
[EnumMember(Value = "zoo")]
Zoo,
/// <summary>
/// Indicates an encoded location reference, derived from latitude and longitude.
/// <para/>
/// Plus codes can be used as a replacement for street addresses in places where they do not exist
/// (where buildings are not numbered or streets are not named).
/// <para/>
/// See <see href="https://plus.codes"/> for details.
/// </summary>
[EnumMember(Value = "plus_code")]
Plus_Code,
}
}
| |
/*
'===============================================================================
' Generated From - MySQL4_CSharp_BusinessEntity.vbgen
'
' The supporting base class MySql4Entity is in the Architecture directory in "dOOdads".
'
' This object is 'abstract' which means you need to inherit from it to be able
' to instantiate it. This is very easilly done. You can override properties and
' methods in your derived class, this allows you to regenerate this class at any
' time and not worry about overwriting custom code.
'
' NEVER EDIT THIS FILE.
'
' public class YourObject : _YourObject
' {
'
' }
'
'===============================================================================
*/
// Generated by MyGeneration Version # (1.1.3.5)
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Collections;
using System.Collections.Specialized;
using MyGeneration.dOOdads;
namespace MyGeneration.dOOdads.Tests.MySql
{
public abstract class _aggregatetest : MySql4Entity
{
public _aggregatetest()
{
this.QuerySource = "aggregatetest";
this.MappingName = "aggregatetest";
}
//=================================================================
// public Overrides void AddNew()
//=================================================================
//
//=================================================================
public override void AddNew()
{
base.AddNew();
}
public override void FlushData()
{
this._whereClause = null;
this._aggregateClause = null;
base.FlushData();
}
public override string GetAutoKeyColumns()
{
return "ID";
}
//=================================================================
// public Function LoadAll() As Boolean
//=================================================================
// Loads all of the records in the database, and sets the currentRow to the first row
//=================================================================
public bool LoadAll()
{
return this.Query.Load();
}
//=================================================================
// public Overridable Function LoadByPrimaryKey() As Boolean
//=================================================================
// Loads a single row of via the primary key
//=================================================================
public virtual bool LoadByPrimaryKey(int ID)
{
this.Where.ID.Value = ID;
return this.Query.Load();
}
#region Parameters
protected class Parameters
{
public static MySqlParameter ID
{
get
{
return new MySqlParameter("?ID", MySqlDbType.Int32);
}
}
public static MySqlParameter DepartmentID
{
get
{
return new MySqlParameter("?DepartmentID", MySqlDbType.Int32);
}
}
public static MySqlParameter FirstName
{
get
{
return new MySqlParameter("?FirstName", MySqlDbType.VarChar);
}
}
public static MySqlParameter LastName
{
get
{
return new MySqlParameter("?LastName", MySqlDbType.VarChar);
}
}
public static MySqlParameter Age
{
get
{
return new MySqlParameter("?Age", MySqlDbType.Int32);
}
}
public static MySqlParameter HireDate
{
get
{
return new MySqlParameter("?HireDate", MySqlDbType.Datetime);
}
}
public static MySqlParameter Salary
{
get
{
return new MySqlParameter("?Salary", MySqlDbType.Decimal);
}
}
public static MySqlParameter IsActive
{
get
{
return new MySqlParameter("?IsActive", MySqlDbType.Byte);
}
}
}
#endregion
#region ColumnNames
public class ColumnNames
{
public const string ID = "ID";
public const string DepartmentID = "DepartmentID";
public const string FirstName = "FirstName";
public const string LastName = "LastName";
public const string Age = "Age";
public const string HireDate = "HireDate";
public const string Salary = "Salary";
public const string IsActive = "IsActive";
static public string ToPropertyName(string columnName)
{
if(ht == null)
{
ht = new Hashtable();
ht[ID] = _aggregatetest.PropertyNames.ID;
ht[DepartmentID] = _aggregatetest.PropertyNames.DepartmentID;
ht[FirstName] = _aggregatetest.PropertyNames.FirstName;
ht[LastName] = _aggregatetest.PropertyNames.LastName;
ht[Age] = _aggregatetest.PropertyNames.Age;
ht[HireDate] = _aggregatetest.PropertyNames.HireDate;
ht[Salary] = _aggregatetest.PropertyNames.Salary;
ht[IsActive] = _aggregatetest.PropertyNames.IsActive;
}
return (string)ht[columnName];
}
static private Hashtable ht = null;
}
#endregion
#region PropertyNames
public class PropertyNames
{
public const string ID = "ID";
public const string DepartmentID = "DepartmentID";
public const string FirstName = "FirstName";
public const string LastName = "LastName";
public const string Age = "Age";
public const string HireDate = "HireDate";
public const string Salary = "Salary";
public const string IsActive = "IsActive";
static public string ToColumnName(string propertyName)
{
if(ht == null)
{
ht = new Hashtable();
ht[ID] = _aggregatetest.ColumnNames.ID;
ht[DepartmentID] = _aggregatetest.ColumnNames.DepartmentID;
ht[FirstName] = _aggregatetest.ColumnNames.FirstName;
ht[LastName] = _aggregatetest.ColumnNames.LastName;
ht[Age] = _aggregatetest.ColumnNames.Age;
ht[HireDate] = _aggregatetest.ColumnNames.HireDate;
ht[Salary] = _aggregatetest.ColumnNames.Salary;
ht[IsActive] = _aggregatetest.ColumnNames.IsActive;
}
return (string)ht[propertyName];
}
static private Hashtable ht = null;
}
#endregion
#region StringPropertyNames
public class StringPropertyNames
{
public const string ID = "s_ID";
public const string DepartmentID = "s_DepartmentID";
public const string FirstName = "s_FirstName";
public const string LastName = "s_LastName";
public const string Age = "s_Age";
public const string HireDate = "s_HireDate";
public const string Salary = "s_Salary";
public const string IsActive = "s_IsActive";
}
#endregion
#region Properties
public virtual int ID
{
get
{
return base.Getint(ColumnNames.ID);
}
set
{
base.Setint(ColumnNames.ID, value);
}
}
public virtual int DepartmentID
{
get
{
return base.Getint(ColumnNames.DepartmentID);
}
set
{
base.Setint(ColumnNames.DepartmentID, value);
}
}
public virtual string FirstName
{
get
{
return base.Getstring(ColumnNames.FirstName);
}
set
{
base.Setstring(ColumnNames.FirstName, value);
}
}
public virtual string LastName
{
get
{
return base.Getstring(ColumnNames.LastName);
}
set
{
base.Setstring(ColumnNames.LastName, value);
}
}
public virtual int Age
{
get
{
return base.Getint(ColumnNames.Age);
}
set
{
base.Setint(ColumnNames.Age, value);
}
}
public virtual DateTime HireDate
{
get
{
return base.GetDateTime(ColumnNames.HireDate);
}
set
{
base.SetDateTime(ColumnNames.HireDate, value);
}
}
public virtual decimal Salary
{
get
{
return base.Getdecimal(ColumnNames.Salary);
}
set
{
base.Setdecimal(ColumnNames.Salary, value);
}
}
public virtual byte IsActive
{
get
{
return base.Getbyte(ColumnNames.IsActive);
}
set
{
base.Setbyte(ColumnNames.IsActive, value);
}
}
#endregion
#region String Properties
public virtual string s_ID
{
get
{
return this.IsColumnNull(ColumnNames.ID) ? string.Empty : base.GetintAsString(ColumnNames.ID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ID);
else
this.ID = base.SetintAsString(ColumnNames.ID, value);
}
}
public virtual string s_DepartmentID
{
get
{
return this.IsColumnNull(ColumnNames.DepartmentID) ? string.Empty : base.GetintAsString(ColumnNames.DepartmentID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.DepartmentID);
else
this.DepartmentID = base.SetintAsString(ColumnNames.DepartmentID, value);
}
}
public virtual string s_FirstName
{
get
{
return this.IsColumnNull(ColumnNames.FirstName) ? string.Empty : base.GetstringAsString(ColumnNames.FirstName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.FirstName);
else
this.FirstName = base.SetstringAsString(ColumnNames.FirstName, value);
}
}
public virtual string s_LastName
{
get
{
return this.IsColumnNull(ColumnNames.LastName) ? string.Empty : base.GetstringAsString(ColumnNames.LastName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.LastName);
else
this.LastName = base.SetstringAsString(ColumnNames.LastName, value);
}
}
public virtual string s_Age
{
get
{
return this.IsColumnNull(ColumnNames.Age) ? string.Empty : base.GetintAsString(ColumnNames.Age);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Age);
else
this.Age = base.SetintAsString(ColumnNames.Age, value);
}
}
public virtual string s_HireDate
{
get
{
return this.IsColumnNull(ColumnNames.HireDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.HireDate);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.HireDate);
else
this.HireDate = base.SetDateTimeAsString(ColumnNames.HireDate, value);
}
}
public virtual string s_Salary
{
get
{
return this.IsColumnNull(ColumnNames.Salary) ? string.Empty : base.GetdecimalAsString(ColumnNames.Salary);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Salary);
else
this.Salary = base.SetdecimalAsString(ColumnNames.Salary, value);
}
}
public virtual string s_IsActive
{
get
{
return this.IsColumnNull(ColumnNames.IsActive) ? string.Empty : base.GetbyteAsString(ColumnNames.IsActive);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.IsActive);
else
this.IsActive = base.SetbyteAsString(ColumnNames.IsActive, value);
}
}
#endregion
#region Where Clause
public class WhereClause
{
public WhereClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffWhereParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffWhereParameter(this);
}
return _tearOff;
}
}
#region WhereParameter TearOff's
public class TearOffWhereParameter
{
public TearOffWhereParameter(WhereClause clause)
{
this._clause = clause;
}
public WhereParameter ID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ID, Parameters.ID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter DepartmentID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.DepartmentID, Parameters.DepartmentID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter FirstName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.FirstName, Parameters.FirstName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter LastName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.LastName, Parameters.LastName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Age
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Age, Parameters.Age);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter HireDate
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.HireDate, Parameters.HireDate);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Salary
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Salary, Parameters.Salary);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter IsActive
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.IsActive, Parameters.IsActive);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
private WhereClause _clause;
}
#endregion
public WhereParameter ID
{
get
{
if(_ID_W == null)
{
_ID_W = TearOff.ID;
}
return _ID_W;
}
}
public WhereParameter DepartmentID
{
get
{
if(_DepartmentID_W == null)
{
_DepartmentID_W = TearOff.DepartmentID;
}
return _DepartmentID_W;
}
}
public WhereParameter FirstName
{
get
{
if(_FirstName_W == null)
{
_FirstName_W = TearOff.FirstName;
}
return _FirstName_W;
}
}
public WhereParameter LastName
{
get
{
if(_LastName_W == null)
{
_LastName_W = TearOff.LastName;
}
return _LastName_W;
}
}
public WhereParameter Age
{
get
{
if(_Age_W == null)
{
_Age_W = TearOff.Age;
}
return _Age_W;
}
}
public WhereParameter HireDate
{
get
{
if(_HireDate_W == null)
{
_HireDate_W = TearOff.HireDate;
}
return _HireDate_W;
}
}
public WhereParameter Salary
{
get
{
if(_Salary_W == null)
{
_Salary_W = TearOff.Salary;
}
return _Salary_W;
}
}
public WhereParameter IsActive
{
get
{
if(_IsActive_W == null)
{
_IsActive_W = TearOff.IsActive;
}
return _IsActive_W;
}
}
private WhereParameter _ID_W = null;
private WhereParameter _DepartmentID_W = null;
private WhereParameter _FirstName_W = null;
private WhereParameter _LastName_W = null;
private WhereParameter _Age_W = null;
private WhereParameter _HireDate_W = null;
private WhereParameter _Salary_W = null;
private WhereParameter _IsActive_W = null;
public void WhereClauseReset()
{
_ID_W = null;
_DepartmentID_W = null;
_FirstName_W = null;
_LastName_W = null;
_Age_W = null;
_HireDate_W = null;
_Salary_W = null;
_IsActive_W = null;
this._entity.Query.FlushWhereParameters();
}
private BusinessEntity _entity;
private TearOffWhereParameter _tearOff;
}
public WhereClause Where
{
get
{
if(_whereClause == null)
{
_whereClause = new WhereClause(this);
}
return _whereClause;
}
}
private WhereClause _whereClause = null;
#endregion
#region Aggregate Clause
public class AggregateClause
{
public AggregateClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffAggregateParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffAggregateParameter(this);
}
return _tearOff;
}
}
#region AggregateParameter TearOff's
public class TearOffAggregateParameter
{
public TearOffAggregateParameter(AggregateClause clause)
{
this._clause = clause;
}
public AggregateParameter ID
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.ID, Parameters.ID);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter DepartmentID
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.DepartmentID, Parameters.DepartmentID);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter FirstName
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.FirstName, Parameters.FirstName);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter LastName
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.LastName, Parameters.LastName);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter Age
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.Age, Parameters.Age);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter HireDate
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.HireDate, Parameters.HireDate);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter Salary
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.Salary, Parameters.Salary);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter IsActive
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.IsActive, Parameters.IsActive);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
private AggregateClause _clause;
}
#endregion
public AggregateParameter ID
{
get
{
if(_ID_W == null)
{
_ID_W = TearOff.ID;
}
return _ID_W;
}
}
public AggregateParameter DepartmentID
{
get
{
if(_DepartmentID_W == null)
{
_DepartmentID_W = TearOff.DepartmentID;
}
return _DepartmentID_W;
}
}
public AggregateParameter FirstName
{
get
{
if(_FirstName_W == null)
{
_FirstName_W = TearOff.FirstName;
}
return _FirstName_W;
}
}
public AggregateParameter LastName
{
get
{
if(_LastName_W == null)
{
_LastName_W = TearOff.LastName;
}
return _LastName_W;
}
}
public AggregateParameter Age
{
get
{
if(_Age_W == null)
{
_Age_W = TearOff.Age;
}
return _Age_W;
}
}
public AggregateParameter HireDate
{
get
{
if(_HireDate_W == null)
{
_HireDate_W = TearOff.HireDate;
}
return _HireDate_W;
}
}
public AggregateParameter Salary
{
get
{
if(_Salary_W == null)
{
_Salary_W = TearOff.Salary;
}
return _Salary_W;
}
}
public AggregateParameter IsActive
{
get
{
if(_IsActive_W == null)
{
_IsActive_W = TearOff.IsActive;
}
return _IsActive_W;
}
}
private AggregateParameter _ID_W = null;
private AggregateParameter _DepartmentID_W = null;
private AggregateParameter _FirstName_W = null;
private AggregateParameter _LastName_W = null;
private AggregateParameter _Age_W = null;
private AggregateParameter _HireDate_W = null;
private AggregateParameter _Salary_W = null;
private AggregateParameter _IsActive_W = null;
public void AggregateClauseReset()
{
_ID_W = null;
_DepartmentID_W = null;
_FirstName_W = null;
_LastName_W = null;
_Age_W = null;
_HireDate_W = null;
_Salary_W = null;
_IsActive_W = null;
this._entity.Query.FlushAggregateParameters();
}
private BusinessEntity _entity;
private TearOffAggregateParameter _tearOff;
}
public AggregateClause Aggregate
{
get
{
if(_aggregateClause == null)
{
_aggregateClause = new AggregateClause(this);
}
return _aggregateClause;
}
}
private AggregateClause _aggregateClause = null;
#endregion
protected override IDbCommand GetInsertCommand()
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"INSERT INTO `aggregatetest`
(
`DepartmentID`,
`FirstName`,
`LastName`,
`Age`,
`HireDate`,
`Salary`,
`IsActive`
)
VALUES
(
?DepartmentID,
?FirstName,
?LastName,
?Age,
?HireDate,
?Salary,
?IsActive
)";
CreateParameters(cmd);
return cmd;
}
protected override IDbCommand GetUpdateCommand()
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"UPDATE `aggregatetest` SET
`DepartmentID`=?DepartmentID,
`FirstName`=?FirstName,
`LastName`=?LastName,
`Age`=?Age,
`HireDate`=?HireDate,
`Salary`=?Salary,
`IsActive`=?IsActive
WHERE
`ID`=?ID";
CreateParameters(cmd);
return cmd;
}
protected override IDbCommand GetDeleteCommand()
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"DELETE FROM `aggregatetest`
WHERE
`ID`=?ID";
MySqlParameter p;
p = cmd.Parameters.Add(Parameters.ID);
p.SourceColumn = ColumnNames.ID;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
private IDbCommand CreateParameters(MySqlCommand cmd)
{
MySqlParameter p;
p = cmd.Parameters.Add(Parameters.ID);
p.SourceColumn = ColumnNames.ID;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.DepartmentID);
p.SourceColumn = ColumnNames.DepartmentID;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.FirstName);
p.SourceColumn = ColumnNames.FirstName;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.LastName);
p.SourceColumn = ColumnNames.LastName;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.Age);
p.SourceColumn = ColumnNames.Age;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.HireDate);
p.SourceColumn = ColumnNames.HireDate;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.Salary);
p.SourceColumn = ColumnNames.Salary;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.IsActive);
p.SourceColumn = ColumnNames.IsActive;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
}
}
| |
namespace Nancy.Tests.Unit.Routing
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FakeItEasy;
using Nancy.Helpers;
using Nancy.Responses.Negotiation;
using Nancy.Routing;
using Nancy.Tests.Fakes;
using Nancy.Tests.xUnitExtensions;
using Xunit;
public class DefaultRequestDispatcherFixture
{
private readonly DefaultRequestDispatcher requestDispatcher;
private readonly IRouteResolver routeResolver;
private readonly IRouteInvoker routeInvoker;
private readonly IList<IResponseProcessor> responseProcessors;
private IResponseNegotiator negotiator;
public DefaultRequestDispatcherFixture()
{
this.responseProcessors = new List<IResponseProcessor>();
this.routeResolver = A.Fake<IRouteResolver>();
this.routeInvoker = A.Fake<IRouteInvoker>();
this.negotiator = A.Fake<IResponseNegotiator>();
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._))
.ReturnsLazily(async arg =>
{
var actionResult = await ((Route)arg.Arguments[0]).Action.Invoke(arg.Arguments[2], new CancellationToken());
return actionResult;
});
this.requestDispatcher =
new DefaultRequestDispatcher(this.routeResolver, this.responseProcessors, this.routeInvoker, this.negotiator);
var resolvedRoute = new ResolveResult
{
Route = new FakeRoute(),
Parameters = DynamicDictionary.Empty,
Before = null,
After = null,
OnError = null
};
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>._)).Returns(resolvedRoute);
}
[Fact]
public async Task Should_invoke_module_before_hook_followed_by_resolved_route_followed_by_module_after_hook()
{
// Given
var capturedExecutionOrder = new List<string>();
var expectedExecutionOrder = new[] { "Prehook", "RouteInvoke", "Posthook" };
var route = new FakeRoute
{
Action = (parameters, token) =>
{
capturedExecutionOrder.Add("RouteInvoke");
return CreateResponseTask(null);
}
};
var before = new BeforePipeline();
before += (ctx) =>
{
capturedExecutionOrder.Add("Prehook");
return null;
};
var after = new AfterPipeline();
after += (ctx) =>
{
capturedExecutionOrder.Add("Posthook");
};
var resolvedRoute = new ResolveResult
{
Route = route,
Parameters = DynamicDictionary.Empty,
Before = before,
After = after,
OnError = null
};
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
capturedExecutionOrder.Count().ShouldEqual(3);
capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
}
[Fact]
public async Task Should_not_invoke_resolved_route_if_module_before_hook_returns_response_but_should_invoke_module_after_hook()
{
// Given
var capturedExecutionOrder = new List<string>();
var expectedExecutionOrder = new[] { "Prehook", "Posthook" };
var route = new FakeRoute
{
Action = (parameters, token) =>
{
capturedExecutionOrder.Add("RouteInvoke");
return null;
}
};
var before = new BeforePipeline();
before += ctx =>
{
capturedExecutionOrder.Add("Prehook");
return new Response();
};
var after = new AfterPipeline();
after += ctx => capturedExecutionOrder.Add("Posthook");
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
null);
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
capturedExecutionOrder.Count().ShouldEqual(2);
capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
}
[Fact]
public async Task Should_return_response_from_module_before_hook_when_not_null()
{
// Given
var expectedResponse = new Response();
Func<NancyContext, Response> moduleBeforeHookResponse = ctx => expectedResponse;
var before = new BeforePipeline();
before += moduleBeforeHookResponse;
var after = new AfterPipeline();
after += ctx => { };
var route = new FakeRoute();
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
null);
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
context.Response.ShouldBeSameAs(expectedResponse);
}
[Fact]
public async Task Should_allow_module_after_hook_to_change_response()
{
// Given
var before = new BeforePipeline();
before += ctx => null;
var response = new Response();
Func<NancyContext, Response> moduleAfterHookResponse = ctx => response;
var after = new AfterPipeline();
after += ctx =>
{
ctx.Response = moduleAfterHookResponse(ctx);
};
var route = new FakeRoute();
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
null);
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
context.Response.ShouldBeSameAs(response);
}
[Fact]
public async Task HandleRequest_should_allow_module_after_hook_to_add_items_to_context()
{
// Given
var route = new FakeRoute();
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx => ctx.Items.Add("RoutePostReq", new object());
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
null);
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
context.Items.ContainsKey("RoutePostReq").ShouldBeTrue();
}
[Fact]
public async Task Should_set_the_route_parameters_from_resolved_route()
{
// Given
const string expectedPath = "/the/path";
var context =
new NancyContext
{
Request = new FakeRequest("GET", expectedPath)
};
var parameters = new DynamicDictionary();
var resolvedRoute = new ResolveResult(
new FakeRoute(),
parameters,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
((DynamicDictionary)context.Parameters).ShouldBeSameAs(parameters);
}
[Fact]
public async Task Should_set_the_context_resolved_route_from_resolve_result()
{
// Given
const string expectedPath = "/the/path";
var context =
new NancyContext
{
Request = new FakeRequest("GET", expectedPath)
};
var expectedRoute = new FakeRoute();
var resolveResult = new ResolveResult(
expectedRoute,
new DynamicDictionary(),
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolveResult);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
context.ResolvedRoute.ShouldBeSameAs(expectedRoute);
}
[Fact]
public async Task Should_invoke_route_resolver_with_context_for_current_request()
{
// Given
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/")
};
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
A.CallTo(() => this.routeResolver.Resolve(context)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public async Task Should_invoke_route_resolver_with_path_when_path_does_not_contain_file_extension()
{
// Given
const string expectedPath = "/the/path";
var requestedPath = string.Empty;
var context =
new NancyContext
{
Request = new FakeRequest("GET", expectedPath)
};
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)
.Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedPath.ShouldEqual(expectedPath);
}
[Fact]
public async Task Should_invoke_route_resolver_with_passed_in_accept_headers_when_path_does_not_contain_file_extensions()
{
// Given
var expectedAcceptHeaders = new List<Tuple<string, decimal>>
{
{ new Tuple<string, decimal>("application/json", 0.8m) },
{ new Tuple<string, decimal>("application/xml", 0.4m) }
};
var requestedAcceptHeaders =
new List<Tuple<string, decimal>>();
var request = new FakeRequest("GET", "/")
{
Headers = { Accept = expectedAcceptHeaders }
};
var context =
new NancyContext { Request = request };
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())
.Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedAcceptHeaders.ShouldHaveCount(2);
requestedAcceptHeaders[0].Item1.ShouldEqual("application/json");
requestedAcceptHeaders[0].Item2.ShouldEqual(0.8m);
requestedAcceptHeaders[1].Item1.ShouldEqual("application/xml");
requestedAcceptHeaders[1].Item2.ShouldEqual(0.4m);
}
[Fact]
public async Task Should_invoke_route_resolver_with_extension_stripped_from_path_when_path_does_contain_file_extension_and_mapped_response_processor_exists()
{
// Given
var requestedPath = string.Empty;
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var processor =
A.Fake<IResponseProcessor>();
this.responseProcessors.Add(processor);
var mappings = new List<Tuple<string, MediaRange>>
{
{ new Tuple<string, MediaRange>("json", "application/json") }
};
A.CallTo(() => processor.ExtensionMappings).Returns(mappings);
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)
.Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedPath.ShouldEqual("/user");
}
[Fact]
public async Task Should_invoke_route_resolver_with_extension_stripped_only_at_the_end_from_path_when_path_does_contain_file_extension_and_mapped_response_processor_exists()
{
// Given
var requestedPath = string.Empty;
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/directory.jsonfiles/user.json")
};
var processor =
A.Fake<IResponseProcessor>();
this.responseProcessors.Add(processor);
var mappings = new List<Tuple<string, MediaRange>>
{
{ new Tuple<string, MediaRange>("json", "application/json") }
};
A.CallTo(() => processor.ExtensionMappings).Returns(mappings);
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)
.Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedPath.ShouldEqual("/directory.jsonfiles/user");
}
[Fact]
public async Task Should_invoke_route_resolver_with_path_containing_when_path_does_contain_file_extension_and_no_mapped_response_processor_exists()
{
// Given
var requestedPath = string.Empty;
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)
.Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedPath.ShouldEqual("/user.json");
}
[Fact]
public async Task Should_invoke_route_resolver_with_distinct_mapped_media_ranged_when_path_contains_extension_and_mapped_response_processors_exists()
{
// Given
var requestedAcceptHeaders =
new List<Tuple<string, decimal>>();
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var jsonProcessor =
A.Fake<IResponseProcessor>();
var jsonProcessormappings =
new List<Tuple<string, MediaRange>> { { new Tuple<string, MediaRange>("json", "application/json") } };
A.CallTo(() => jsonProcessor.ExtensionMappings).Returns(jsonProcessormappings);
var otherProcessor =
A.Fake<IResponseProcessor>();
var otherProcessormappings =
new List<Tuple<string, MediaRange>>
{
{ new Tuple<string, MediaRange>("json", "application/json") },
{ new Tuple<string, MediaRange>("xml", "application/xml") }
};
A.CallTo(() => otherProcessor.ExtensionMappings).Returns(otherProcessormappings);
this.responseProcessors.Add(jsonProcessor);
this.responseProcessors.Add(otherProcessor);
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())
.Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedAcceptHeaders.ShouldHaveCount(1);
requestedAcceptHeaders[0].Item1.ShouldEqual("application/json");
}
[Fact]
public async Task Should_set_quality_to_high_for_mapped_media_ranges_before_invoking_route_resolver_when_path_contains_extension_and_mapped_response_processors_exists()
{
// Given
var requestedAcceptHeaders =
new List<Tuple<string, decimal>>();
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var jsonProcessor =
A.Fake<IResponseProcessor>();
var jsonProcessormappings =
new List<Tuple<string, MediaRange>> { { new Tuple<string, MediaRange>("json", "application/json") } };
A.CallTo(() => jsonProcessor.ExtensionMappings).Returns(jsonProcessormappings);
this.responseProcessors.Add(jsonProcessor);
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())
.Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedAcceptHeaders.ShouldHaveCount(1);
Assert.True(requestedAcceptHeaders[0].Item2 > 1.0m);
}
[Fact]
public async Task Should_call_route_invoker_with_resolved_route()
{
// Given
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
A.CallTo(() => this.routeInvoker.Invoke(resolvedRoute.Route, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public async Task Should_invoke_route_resolver_with_path_containing_extension_when_mapped_response_processor_existed_but_no_route_match_was_found()
{
// Given
var requestedAcceptHeaders =
new List<Tuple<string, decimal>>();
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var jsonProcessor =
A.Fake<IResponseProcessor>();
var jsonProcessormappings =
new List<Tuple<string, MediaRange>> { { new Tuple<string, MediaRange>("json", "application/json") } };
A.CallTo(() => jsonProcessor.ExtensionMappings).Returns(jsonProcessormappings);
this.responseProcessors.Add(jsonProcessor);
var resolvedRoute = new ResolveResult(
new NotFoundRoute("GET", "/"),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())
.Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>._)).MustHaveHappened(Repeated.Exactly.Twice);
}
[Fact]
public async Task Should_call_route_invoker_with_captured_parameters()
{
// Given
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var parameters = new DynamicDictionary();
var resolvedRoute = new ResolveResult(
new FakeRoute(),
parameters,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, parameters, A<NancyContext>._)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public async Task Should_call_route_invoker_with_context()
{
// Given
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, context)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public async Task Should_invoke_module_onerror_hook_when_module_before_hook_throws_exception()
{
// Given
var capturedExecutionOrder = new List<string>();
var expectedExecutionOrder = new[] { "Prehook", "OnErrorHook" };
var before = new BeforePipeline();
before += ctx =>
{
capturedExecutionOrder.Add("Prehook");
throw new Exception("Prehook");
};
var after = new AfterPipeline();
after += ctx => capturedExecutionOrder.Add("Posthook");
var route = new FakeRoute((parameters, ct) =>
{
capturedExecutionOrder.Add("RouteInvoke");
return CreateResponseTask(null);
});
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => { capturedExecutionOrder.Add("OnErrorHook"); return new Response(); });
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
capturedExecutionOrder.Count().ShouldEqual(2);
capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
}
[Fact]
public async Task Should_invoke_module_onerror_hook_when_route_invoker_throws_exception()
{
// Given
var capturedExecutionOrder = new List<string>();
var expectedExecutionOrder = new[] { "RouteInvoke", "OnErrorHook" };
var route = new FakeRoute
{
Action = (parameters, ct) =>
{
capturedExecutionOrder.Add("RouteInvoke");
return TaskHelpers.GetFaultedTask<dynamic>(new Exception("RouteInvoke"));
}
};
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx => capturedExecutionOrder.Add("Posthook");
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => { capturedExecutionOrder.Add("OnErrorHook"); return new Response(); });
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
capturedExecutionOrder.Count().ShouldEqual(2);
capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
}
[Fact]
public async Task Should_invoke_module_onerror_hook_when_module_after_hook_throws_exception()
{
// Given
var capturedExecutionOrder = new List<string>();
var expectedExecutionOrder = new[] { "Posthook", "OnErrorHook" };
var route = new FakeRoute
{
Action = (parameters, ct) => CreateResponseTask(null)
};
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx =>
{
capturedExecutionOrder.Add("Posthook");
throw new Exception("Posthook");
};
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => { capturedExecutionOrder.Add("OnErrorHook"); return new Response(); });
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
await this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
capturedExecutionOrder.Count().ShouldEqual(2);
capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
}
[Fact]
public async Task Should_rethrow_exception_when_onerror_hook_does_return_response()
{
// Given
var route = new FakeRoute
{
Action = (parameters, ct) => { throw new Exception(); }
};
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx => { };
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => null);
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
//When
var exception = await RecordAsync.Exception(async () => await this.requestDispatcher.Dispatch(context, new CancellationToken()));
// Then
exception.ShouldNotBeNull();
}
[Fact]
public async Task Should_not_rethrow_exception_when_onerror_hook_returns_response()
{
// Given
var route = new FakeRoute
{
Action = (parameters,ct) => TaskHelpers.GetFaultedTask<dynamic>(new Exception())
};
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx => { };
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => new Response());
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
//When
var exception = await RecordAsync.Exception(async () => await this.requestDispatcher.Dispatch(context, new CancellationToken()));
// Then
exception.ShouldBeNull();
}
#if !__MonoCS__
[Fact]
public async Task should_preserve_stacktrace_when_rethrowing_the_excption()
{
// Given
var route = new FakeRoute
{
Action = (o,ct) => BrokenMethod()
};
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx => { };
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => null);
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
var exception = await RecordAsync.Exception(async () => await this.requestDispatcher.Dispatch(context, new CancellationToken()));
exception.StackTrace.ShouldContain("BrokenMethod");
}
#endif
private static Task<dynamic> CreateResponseTask(dynamic response)
{
var tcs =
new TaskCompletionSource<dynamic>();
tcs.SetResult(response);
return tcs.Task;
}
private static Task<dynamic> BrokenMethod()
{
throw new Exception("You called the broken method!");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
namespace Orleans.Runtime.Scheduler
{
[DebuggerDisplay("WorkItemGroup Name={Name} State={state}")]
internal class WorkItemGroup : IWorkItem
{
private static readonly WaitCallback ExecuteWorkItemCallback = obj => ((WorkItemGroup)obj).Execute();
private enum WorkGroupStatus
{
Waiting = 0,
Runnable = 1,
Running = 2
}
private readonly ILogger log;
private readonly OrleansTaskScheduler masterScheduler;
private WorkGroupStatus state;
private readonly object lockable;
private readonly Queue<Task> workItems;
private long totalItemsEnQueued; // equals total items queued, + 1
private long totalItemsProcessed;
private TimeSpan totalQueuingDelay;
private Task currentTask;
private DateTime currentTaskStarted;
private long shutdownSinceTimestamp;
private long lastShutdownWarningTimestamp;
private readonly QueueTrackingStatistic queueTracking;
private readonly long quantumExpirations;
private readonly int workItemGroupStatisticsNumber;
private readonly CancellationToken cancellationToken;
private readonly SchedulerStatisticsGroup schedulerStatistics;
internal ActivationTaskScheduler TaskScheduler { get; private set; }
public DateTime TimeQueued { get; set; }
public TimeSpan TimeSinceQueued
{
get { return Utils.Since(TimeQueued); }
}
public bool IsSystemPriority => this.GrainContext is SystemTarget systemTarget && !systemTarget.IsLowPriority;
internal bool IsSystemGroup => this.GrainContext is ISystemTargetBase;
public string Name => GrainContext?.ToString() ?? "Unknown";
internal int ExternalWorkItemCount
{
get { lock (lockable) { return WorkItemCount; } }
}
private Task CurrentTask
{
get => currentTask;
set
{
currentTask = value;
currentTaskStarted = DateTime.UtcNow;
}
}
private int WorkItemCount
{
get { return workItems.Count; }
}
internal float AverageQueueLength
{
get
{
return 0;
}
}
internal float NumEnqueuedRequests
{
get
{
return 0;
}
}
internal float ArrivalRate
{
get
{
return 0;
}
}
private bool HasWork => this.WorkItemCount != 0;
private bool IsShutdown => this.shutdownSinceTimestamp > 0;
// This is the maximum number of work items to be processed in an activation turn.
// If this is set to zero or a negative number, then the full work queue is drained (MaxTimePerTurn allowing).
private const int MaxWorkItemsPerTurn = 0; // Unlimited
// This is the maximum number of waiting threads (blocked in WaitForResponse) allowed
// per ActivationWorker. An attempt to wait when there are already too many threads waiting
// will result in a TooManyWaitersException being thrown.
//private static readonly int MaxWaitingThreads = 500;
internal WorkItemGroup(
OrleansTaskScheduler sched,
IGrainContext grainContext,
ILogger<WorkItemGroup> logger,
ILogger<ActivationTaskScheduler> activationTaskSchedulerLogger,
CancellationToken ct,
SchedulerStatisticsGroup schedulerStatistics,
IOptions<StatisticsOptions> statisticsOptions)
{
masterScheduler = sched;
GrainContext = grainContext;
cancellationToken = ct;
this.schedulerStatistics = schedulerStatistics;
state = WorkGroupStatus.Waiting;
workItems = new Queue<Task>();
lockable = new object();
totalItemsEnQueued = 0;
totalItemsProcessed = 0;
totalQueuingDelay = TimeSpan.Zero;
quantumExpirations = 0;
TaskScheduler = new ActivationTaskScheduler(this, activationTaskSchedulerLogger);
log = logger;
if (schedulerStatistics.CollectShedulerQueuesStats)
{
queueTracking = new QueueTrackingStatistic("Scheduler." + this.Name, statisticsOptions);
queueTracking.OnStartExecution();
}
if (schedulerStatistics.CollectPerWorkItemStats)
{
workItemGroupStatisticsNumber = schedulerStatistics.RegisterWorkItemGroup(this.Name, this.GrainContext,
() =>
{
var sb = new StringBuilder();
lock (lockable)
{
sb.Append("QueueLength = " + WorkItemCount);
sb.Append(String.Format(", State = {0}", state));
if (state == WorkGroupStatus.Runnable)
sb.Append(String.Format("; oldest item is {0} old", workItems.Count >= 0 ? workItems.Peek().ToString() : "null"));
}
return sb.ToString();
});
}
}
/// <summary>
/// Adds a task to this activation.
/// If we're adding it to the run list and we used to be waiting, now we're runnable.
/// </summary>
/// <param name="task">The work item to add.</param>
public void EnqueueTask(Task task)
{
#if DEBUG
if (log.IsEnabled(LogLevel.Trace))
{
this.log.LogTrace(
"EnqueueWorkItem {Task} into {GrainContext} when TaskScheduler.Current={TaskScheduler}",
task,
this.GrainContext,
System.Threading.Tasks.TaskScheduler.Current);
}
#endif
if (this.IsShutdown)
{
if (this.cancellationToken.IsCancellationRequested)
{
// If the system is shutdown, do not schedule the task.
return;
}
// Log diagnostics and continue to schedule the task.
LogEnqueueOnStoppedScheduler(task);
}
lock (lockable)
{
long thisSequenceNumber = totalItemsEnQueued++;
int count = WorkItemCount;
workItems.Enqueue(task);
int maxPendingItemsLimit = masterScheduler.MaxPendingItemsSoftLimit;
if (maxPendingItemsLimit > 0 && count > maxPendingItemsLimit)
{
log.LogWarning(
(int)ErrorCode.SchedulerTooManyPendingItems,
"{PendingWorkItemCount} pending work items for group {WorkGroupName}, exceeding the warning threshold of {WarningThreshold}",
count,
this.Name,
maxPendingItemsLimit);
}
if (state != WorkGroupStatus.Waiting) return;
state = WorkGroupStatus.Runnable;
#if DEBUG
if (log.IsEnabled(LogLevel.Trace))
{
log.LogTrace(
"Add to RunQueue {Task}, #{SequenceNumber}, onto {GrainContext}",
task,
thisSequenceNumber,
GrainContext);
}
#endif
ScheduleExecution(this);
}
}
/// <summary>
/// For debugger purposes only.
/// </summary>
internal IEnumerable<Task> GetScheduledTasks()
{
foreach (var task in this.workItems)
{
yield return task;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void LogEnqueueOnStoppedScheduler(Task task)
{
var now = ValueStopwatch.GetTimestamp();
LogLevel logLevel;
if (this.lastShutdownWarningTimestamp == 0)
{
logLevel = LogLevel.Debug;
}
else if (ValueStopwatch.FromTimestamp(this.lastShutdownWarningTimestamp, now).Elapsed > this.masterScheduler.StoppedWorkItemGroupWarningInterval)
{
// Upgrade the warning to an error after 1 minute, include a stack trace, and continue to log up to once per minute.
logLevel = LogLevel.Error;
}
else return;
this.log.Log(
logLevel,
(int)ErrorCode.SchedulerEnqueueWorkWhenShutdown,
"Enqueuing task {Task} to a work item group which should have terminated. "
+ "Likely reasons are that the task is not being 'awaited' properly or a TaskScheduler was captured and is being used to schedule tasks "
+ "after a grain has been deactivated.\nWorkItemGroup: {Status}\nTask.AsyncState: {TaskState}\n{Stack}",
OrleansTaskExtentions.ToString(task),
this.DumpStatus(),
DumpAsyncState(task.AsyncState),
Utils.GetStackTrace());
this.lastShutdownWarningTimestamp = now;
}
private static object DumpAsyncState(object o)
{
if (o is Delegate action)
return action.Target is null ? action.Method.DeclaringType + "." + action.Method.Name
: action.Method.DeclaringType.Name + "." + action.Method.Name + ": " + DumpAsyncState(action.Target);
if (o?.GetType() is { Name: "ContinuationWrapper" } wrapper
&& (wrapper.GetField("_continuation", BindingFlags.Instance | BindingFlags.NonPublic)
?? wrapper.GetField("m_continuation", BindingFlags.Instance | BindingFlags.NonPublic)
)?.GetValue(o) is Action continuation)
return DumpAsyncState(continuation);
#if !NETCOREAPP
if (o?.GetType() is { Name: "MoveNextRunner" } runner
&& runner.GetField("m_stateMachine", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(o) is object stateMachine)
return DumpAsyncState(stateMachine);
#endif
return o;
}
/// <summary>
/// Shuts down this work item group so that it will not process any additional work items, even if they
/// have already been queued.
/// </summary>
internal void Stop()
{
lock (lockable)
{
if (this.HasWork)
{
log.LogWarning(
(int)ErrorCode.SchedulerWorkGroupStopping,
"WorkItemGroup is being shutdown while still active. workItemCount = {WorkItemCount}. The likely reason is that the task is not being 'awaited' properly. Status: {Status}",
WorkItemCount,
DumpStatus());
}
if (this.IsShutdown)
{
log.LogWarning(
(int)ErrorCode.SchedulerWorkGroupShuttingDown,
"WorkItemGroup is already shutting down {WorkItemGroup}",
this.ToString());
return;
}
this.shutdownSinceTimestamp = ValueStopwatch.GetTimestamp();
if (this.schedulerStatistics.CollectPerWorkItemStats)
this.schedulerStatistics.UnRegisterWorkItemGroup(workItemGroupStatisticsNumber);
if (this.schedulerStatistics.CollectShedulerQueuesStats)
queueTracking.OnStopExecution();
}
}
public WorkItemType ItemType
{
get { return WorkItemType.WorkItemGroup; }
}
public IGrainContext GrainContext { get; }
// Execute one or more turns for this activation.
// This method is always called in a single-threaded environment -- that is, no more than one
// thread will be in this method at once -- but other asynch threads may still be queueing tasks, etc.
public void Execute()
{
try
{
RuntimeContext.SetExecutionContext(this.GrainContext);
// Process multiple items -- drain the applicationMessageQueue (up to max items) for this physical activation
int count = 0;
var stopwatch = ValueStopwatch.StartNew();
do
{
lock (lockable)
{
state = WorkGroupStatus.Running;
// Check the cancellation token (means that the silo is stopping)
if (cancellationToken.IsCancellationRequested)
{
this.log.LogWarning(
(int)ErrorCode.SchedulerSkipWorkCancelled,
"Thread {Thread} is exiting work loop due to cancellation token. WorkItemGroup: {WorkItemGroup}, Have {WorkItemCount} work items in the queue",
Thread.CurrentThread.ManagedThreadId.ToString(),
this.ToString(),
this.WorkItemCount);
return;
}
}
// Get the first Work Item on the list
Task task;
lock (lockable)
{
if (workItems.Count > 0)
CurrentTask = task = workItems.Dequeue();
else // If the list is empty, then we're done
break;
}
#if DEBUG
if (log.IsEnabled(LogLevel.Trace))
{
log.LogTrace(
"About to execute task {Task} in GrainContext={GrainContext}",
OrleansTaskExtentions.ToString(task),
this.GrainContext);
}
#endif
var taskStart = stopwatch.Elapsed;
try
{
TaskScheduler.RunTask(task);
}
catch (Exception ex)
{
this.log.LogError(
(int)ErrorCode.SchedulerExceptionFromExecute,
ex,
"Worker thread caught an exception thrown from Execute by task {Task}. Exception: {Exception}",
OrleansTaskExtentions.ToString(task),
ex);
throw;
}
finally
{
totalItemsProcessed++;
var taskLength = stopwatch.Elapsed - taskStart;
if (taskLength > OrleansTaskScheduler.TurnWarningLengthThreshold)
{
this.schedulerStatistics.NumLongRunningTurns.Increment();
this.log.LogWarning(
(int)ErrorCode.SchedulerTurnTooLong3,
"Task {Task} in WorkGroup {GrainContext} took elapsed time {Duration} for execution, which is longer than {TurnWarningLengthThreshold}. Running on thread {Thread}",
OrleansTaskExtentions.ToString(task),
this.GrainContext.ToString(),
taskLength.ToString("g"),
OrleansTaskScheduler.TurnWarningLengthThreshold,
Thread.CurrentThread.ManagedThreadId.ToString());
}
CurrentTask = null;
}
count++;
}
while (((MaxWorkItemsPerTurn <= 0) || (count <= MaxWorkItemsPerTurn)) &&
((masterScheduler.SchedulingOptions.ActivationSchedulingQuantum <= TimeSpan.Zero) || (stopwatch.Elapsed < masterScheduler.SchedulingOptions.ActivationSchedulingQuantum)));
}
catch (Exception ex)
{
this.log.LogError(
(int)ErrorCode.Runtime_Error_100032,
ex,
"Worker thread {Thread} caught an exception thrown from IWorkItem.Execute: {Exception}",
Thread.CurrentThread.ManagedThreadId,
ex);
}
finally
{
// Now we're not Running anymore.
// If we left work items on our run list, we're Runnable, and need to go back on the silo run queue;
// If our run list is empty, then we're waiting.
lock (lockable)
{
if (WorkItemCount > 0 && !this.IsShutdown)
{
state = WorkGroupStatus.Runnable;
ScheduleExecution(this);
}
else
{
state = WorkGroupStatus.Waiting;
}
}
RuntimeContext.ResetExecutionContext();
}
}
public override string ToString()
{
return String.Format("{0}WorkItemGroup:Name={1},WorkGroupStatus={2}",
IsSystemGroup ? "System*" : "",
Name,
state);
}
public string DumpStatus()
{
lock (lockable)
{
var sb = new StringBuilder();
sb.Append(this);
sb.AppendFormat(". Currently QueuedWorkItems={0}; Total EnQueued={1}; Total processed={2}; Quantum expirations={3}; ",
WorkItemCount, totalItemsEnQueued, totalItemsProcessed, quantumExpirations);
if (CurrentTask is Task task)
{
sb.AppendFormat(" Executing Task Id={0} Status={1} for {2}.",
task.Id, task.Status, Utils.Since(currentTaskStarted));
}
if (AverageQueueLength > 0)
{
sb.AppendFormat("average queue length at enqueue: {0}; ", AverageQueueLength);
if (!totalQueuingDelay.Equals(TimeSpan.Zero) && totalItemsProcessed > 0)
{
sb.AppendFormat("average queue delay: {0}ms; ", totalQueuingDelay.Divide(totalItemsProcessed).TotalMilliseconds);
}
}
sb.AppendFormat("TaskRunner={0}; ", TaskScheduler);
if (GrainContext != null)
{
var detailedStatus = this.GrainContext switch
{
ActivationData activationData => activationData.ToDetailedString(includeExtraDetails: true),
SystemTarget systemTarget => systemTarget.ToDetailedString(),
object obj => obj.ToString(),
_ => "None"
};
sb.AppendFormat("Detailed context=<{0}>", detailedStatus);
}
return sb.ToString();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ScheduleExecution(WorkItemGroup workItem)
{
#if NETCOREAPP
ThreadPool.UnsafeQueueUserWorkItem(workItem, preferLocal: true);
#else
ThreadPool.UnsafeQueueUserWorkItem(ExecuteWorkItemCallback, workItem);
#endif
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: Dictionary
**
** <OWNER>[....]</OWNER>
**
** Purpose: Generic hash table implementation
**
** #DictionaryVersusHashtableThreadSafety
** Hashtable has multiple reader/single writer (MR/SW) thread safety built into
** certain methods and properties, whereas Dictionary doesn't. If you're
** converting framework code that formerly used Hashtable to Dictionary, it's
** important to consider whether callers may have taken a dependence on MR/SW
** thread safety. If a reader writer lock is available, then that may be used
** with a Dictionary to get the same thread safety guarantee.
**
** Reader writer locks don't exist in silverlight, so we do the following as a
** result of removing non-generic collections from silverlight:
** 1. If the Hashtable was fully synchronized, then we replace it with a
** Dictionary with full locks around reads/writes (same thread safety
** guarantee).
** 2. Otherwise, the Hashtable has the default MR/SW thread safety behavior,
** so we do one of the following on a case-by-case basis:
** a. If the ---- can be addressed by rearranging the code and using a temp
** variable (for example, it's only populated immediately after created)
** then we address the ---- this way and use Dictionary.
** b. If there's concern about degrading performance with the increased
** locking, we ifdef with FEATURE_NONGENERIC_COLLECTIONS so we can at
** least use Hashtable in the desktop build, but Dictionary with full
** locks in silverlight builds. Note that this is heavier locking than
** MR/SW, but this is the only option without rewriting (or adding back)
** the reader writer lock.
** c. If there's no performance concern (e.g. debug-only code) we
** consistently replace Hashtable with Dictionary plus full locks to
** reduce complexity.
** d. Most of serialization is dead code in silverlight. Instead of updating
** those Hashtable occurences in serialization, we carved out references
** to serialization such that this code doesn't need to build in
** silverlight.
===========================================================*/
namespace System.Collections.Generic {
using System;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Security.Permissions;
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.InteropServices.ComVisible(false)]
public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback {
private struct Entry {
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[] buckets;
private Entry[] entries;
private int count;
private int version;
private int freeList;
private int freeCount;
private IEqualityComparer<TKey> comparer;
private KeyCollection keys;
private ValueCollection values;
private Object _syncRoot;
// constants for serialization
private const String VersionName = "Version";
private const String HashSizeName = "HashSize"; // Must save buckets.Length
private const String KeyValuePairsName = "KeyValuePairs";
private const String ComparerName = "Comparer";
public Dictionary(): this(0, null) {}
public Dictionary(int capacity): this(capacity, null) {}
public Dictionary(IEqualityComparer<TKey> comparer): this(0, comparer) {}
public Dictionary(int capacity, IEqualityComparer<TKey> comparer) {
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (capacity > 0) Initialize(capacity);
this.comparer = comparer ?? EqualityComparer<TKey>.Default;
}
public Dictionary(IDictionary<TKey,TValue> dictionary): this(dictionary, null) {}
public Dictionary(IDictionary<TKey,TValue> dictionary, IEqualityComparer<TKey> comparer):
this(dictionary != null? dictionary.Count: 0, comparer) {
if( dictionary == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
foreach (KeyValuePair<TKey,TValue> pair in dictionary) {
Add(pair.Key, pair.Value);
}
}
protected Dictionary(SerializationInfo info, StreamingContext context) {
//We can't do anything with the keys and values until the entire graph has been deserialized
//and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
//we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
public IEqualityComparer<TKey> Comparer {
get {
return comparer;
}
}
public int Count {
get { return count - freeCount; }
}
public KeyCollection Keys {
get {
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys {
get {
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys {
get {
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
public ValueCollection Values {
get {
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (values == null) values = new ValueCollection(this);
return values;
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values {
get {
if (values == null) values = new ValueCollection(this);
return values;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values {
get {
if (values == null) values = new ValueCollection(this);
return values;
}
}
public TValue this[TKey key] {
get {
int i = FindEntry(key);
if (i >= 0) return entries[i].value;
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
set {
Insert(key, value, false);
}
}
public void Add(TKey key, TValue value) {
Insert(key, value, true);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) {
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) {
int i = FindEntry(keyValuePair.Key);
if( i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) {
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) {
int i = FindEntry(keyValuePair.Key);
if( i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) {
Remove(keyValuePair.Key);
return true;
}
return false;
}
public void Clear() {
if (count > 0) {
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
Array.Clear(entries, 0, count);
freeList = -1;
count = 0;
freeCount = 0;
version++;
}
}
public bool ContainsKey(TKey key) {
return FindEntry(key) >= 0;
}
public bool ContainsValue(TValue value) {
if (value == null) {
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0 && entries[i].value == null) return true;
}
}
else {
EqualityComparer<TValue> c = EqualityComparer<TValue>.Default;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0 && c.Equals(entries[i].value, value)) return true;
}
}
return false;
}
private void CopyTo(KeyValuePair<TKey,TValue>[] array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length ) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) {
array[index++] = new KeyValuePair<TKey,TValue>(entries[i].key, entries[i].value);
}
}
}
public Enumerator GetEnumerator() {
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() {
return new Enumerator(this, Enumerator.KeyValuePair);
}
[System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, version);
#if FEATURE_RANDOMIZED_STRING_HASHING
info.AddValue(ComparerName, HashHelpers.GetEqualityComparerForSerialization(comparer), typeof(IEqualityComparer<TKey>));
#else
info.AddValue(ComparerName, comparer, typeof(IEqualityComparer<TKey>));
#endif
info.AddValue(HashSizeName, buckets == null ? 0 : buckets.Length); //This is the length of the bucket array.
if( buckets != null) {
KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[Count];
CopyTo(array, 0);
info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
}
}
private int FindEntry(TKey key) {
if( key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null) {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
private void Initialize(int capacity) {
int size = HashHelpers.GetPrime(capacity);
buckets = new int[size];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[size];
freeList = -1;
}
private void Insert(TKey key, TValue value, bool add) {
if( key == null ) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets == null) Initialize(0);
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int targetBucket = hashCode % buckets.Length;
#if FEATURE_RANDOMIZED_STRING_HASHING
int collisionCount = 0;
#endif
for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
if (add) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
entries[i].value = value;
version++;
return;
}
#if FEATURE_RANDOMIZED_STRING_HASHING
collisionCount++;
#endif
}
int index;
if (freeCount > 0) {
index = freeList;
freeList = entries[index].next;
freeCount--;
}
else {
if (count == entries.Length)
{
Resize();
targetBucket = hashCode % buckets.Length;
}
index = count;
count++;
}
entries[index].hashCode = hashCode;
entries[index].next = buckets[targetBucket];
entries[index].key = key;
entries[index].value = value;
buckets[targetBucket] = index;
version++;
#if FEATURE_RANDOMIZED_STRING_HASHING
if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer))
{
comparer = (IEqualityComparer<TKey>) HashHelpers.GetRandomizedEqualityComparer(comparer);
Resize(entries.Length, true);
}
#endif
}
public virtual void OnDeserialization(Object sender) {
SerializationInfo siInfo;
HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
if (siInfo==null) {
// It might be necessary to call OnDeserialization from a container if the container object also implements
// OnDeserialization. However, remoting will call OnDeserialization again.
// We can return immediately if this function is called twice.
// Note we set remove the serialization info from the table at the end of this method.
return;
}
int realVersion = siInfo.GetInt32(VersionName);
int hashsize = siInfo.GetInt32(HashSizeName);
comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>));
if( hashsize != 0) {
buckets = new int[hashsize];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[hashsize];
freeList = -1;
KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[])
siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
if (array==null) {
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
for (int i=0; i<array.Length; i++) {
if ( array[i].Key == null) {
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
Insert(array[i].Key, array[i].Value, true);
}
}
else {
buckets = null;
}
version = realVersion;
HashHelpers.SerializationInfoTable.Remove(this);
}
private void Resize() {
Resize(HashHelpers.ExpandPrime(count), false);
}
private void Resize(int newSize, bool forceNewHashCodes) {
Contract.Assert(newSize >= entries.Length);
int[] newBuckets = new int[newSize];
for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
Entry[] newEntries = new Entry[newSize];
Array.Copy(entries, 0, newEntries, 0, count);
if(forceNewHashCodes) {
for (int i = 0; i < count; i++) {
if(newEntries[i].hashCode != -1) {
newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF);
}
}
}
for (int i = 0; i < count; i++) {
if (newEntries[i].hashCode >= 0) {
int bucket = newEntries[i].hashCode % newSize;
newEntries[i].next = newBuckets[bucket];
newBuckets[bucket] = i;
}
}
buckets = newBuckets;
entries = newEntries;
}
public bool Remove(TKey key) {
if(key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null) {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
if (last < 0) {
buckets[bucket] = entries[i].next;
}
else {
entries[last].next = entries[i].next;
}
entries[i].hashCode = -1;
entries[i].next = freeList;
entries[i].key = default(TKey);
entries[i].value = default(TValue);
freeList = i;
freeCount++;
version++;
return true;
}
}
}
return false;
}
public bool TryGetValue(TKey key, out TValue value) {
int i = FindEntry(key);
if (i >= 0) {
value = entries[i].value;
return true;
}
value = default(TValue);
return false;
}
// This is a convenience method for the internal callers that were converted from using Hashtable.
// Many were combining key doesn't exist and key exists but null value (for non-value types) checks.
// This allows them to continue getting that behavior with minimal code delta. This is basically
// TryGetValue without the out param
internal TValue GetValueOrDefault(TKey key) {
int i = FindEntry(key);
if (i >= 0) {
return entries[i].value;
}
return default(TValue);
}
bool ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly {
get { return false; }
}
void ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[] array, int index) {
CopyTo(array, index);
}
void ICollection.CopyTo(Array array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey,TValue>[] pairs = array as KeyValuePair<TKey,TValue>[];
if (pairs != null) {
CopyTo(pairs, index);
}
else if( array is DictionaryEntry[]) {
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
Entry[] entries = this.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) {
dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value);
}
}
}
else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
try {
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) {
objects[index++] = new KeyValuePair<TKey,TValue>(entries[i].key, entries[i].value);
}
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(this, Enumerator.KeyValuePair);
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get {
if( _syncRoot == null) {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
bool IDictionary.IsFixedSize {
get { return false; }
}
bool IDictionary.IsReadOnly {
get { return false; }
}
ICollection IDictionary.Keys {
get { return (ICollection)Keys; }
}
ICollection IDictionary.Values {
get { return (ICollection)Values; }
}
object IDictionary.this[object key] {
get {
if( IsCompatibleKey(key)) {
int i = FindEntry((TKey)key);
if (i >= 0) {
return entries[i].value;
}
}
return null;
}
set {
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try {
TKey tempKey = (TKey)key;
try {
this[tempKey] = (TValue)value;
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
}
private static bool IsCompatibleKey(object key) {
if( key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return (key is TKey);
}
void IDictionary.Add(object key, object value) {
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try {
TKey tempKey = (TKey)key;
try {
Add(tempKey, (TValue)value);
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
bool IDictionary.Contains(object key) {
if(IsCompatibleKey(key)) {
return ContainsKey((TKey)key);
}
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator() {
return new Enumerator(this, Enumerator.DictEntry);
}
void IDictionary.Remove(object key) {
if(IsCompatibleKey(key)) {
Remove((TKey)key);
}
}
[Serializable]
public struct Enumerator: IEnumerator<KeyValuePair<TKey,TValue>>,
IDictionaryEnumerator
{
private Dictionary<TKey,TValue> dictionary;
private int version;
private int index;
private KeyValuePair<TKey,TValue> current;
private int getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(Dictionary<TKey,TValue> dictionary, int getEnumeratorRetType) {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
this.getEnumeratorRetType = getEnumeratorRetType;
current = new KeyValuePair<TKey, TValue>();
}
public bool MoveNext() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue
while ((uint)index < (uint)dictionary.count) {
if (dictionary.entries[index].hashCode >= 0) {
current = new KeyValuePair<TKey, TValue>(dictionary.entries[index].key, dictionary.entries[index].value);
index++;
return true;
}
index++;
}
index = dictionary.count + 1;
current = new KeyValuePair<TKey, TValue>();
return false;
}
public KeyValuePair<TKey,TValue> Current {
get { return current; }
}
public void Dispose() {
}
object IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
if (getEnumeratorRetType == DictEntry) {
return new System.Collections.DictionaryEntry(current.Key, current.Value);
} else {
return new KeyValuePair<TKey, TValue>(current.Key, current.Value);
}
}
}
void IEnumerator.Reset() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
index = 0;
current = new KeyValuePair<TKey, TValue>();
}
DictionaryEntry IDictionaryEnumerator.Entry {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(current.Key, current.Value);
}
}
object IDictionaryEnumerator.Key {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return current.Key;
}
}
object IDictionaryEnumerator.Value {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return current.Value;
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class KeyCollection: ICollection<TKey>, ICollection
{
private Dictionary<TKey,TValue> dictionary;
public KeyCollection(Dictionary<TKey,TValue> dictionary) {
if (dictionary == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
public Enumerator GetEnumerator() {
return new Enumerator(dictionary);
}
public void CopyTo(TKey[] array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < dictionary.Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) array[index++] = entries[i].key;
}
}
public int Count {
get { return dictionary.Count; }
}
bool ICollection<TKey>.IsReadOnly {
get { return true; }
}
void ICollection<TKey>.Add(TKey item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
void ICollection<TKey>.Clear(){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
bool ICollection<TKey>.Contains(TKey item){
return dictionary.ContainsKey(item);
}
bool ICollection<TKey>.Remove(TKey item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
return false;
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() {
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index) {
if (array==null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < dictionary.Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
TKey[] keys = array as TKey[];
if (keys != null) {
CopyTo(keys, index);
}
else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try {
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) objects[index++] = entries[i].key;
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
}
bool ICollection.IsSynchronized {
get { return false; }
}
Object ICollection.SyncRoot {
get { return ((ICollection)dictionary).SyncRoot; }
}
[Serializable]
public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int index;
private int version;
private TKey currentKey;
internal Enumerator(Dictionary<TKey, TValue> dictionary) {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentKey = default(TKey);
}
public void Dispose() {
}
public bool MoveNext() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
while ((uint)index < (uint)dictionary.count) {
if (dictionary.entries[index].hashCode >= 0) {
currentKey = dictionary.entries[index].key;
index++;
return true;
}
index++;
}
index = dictionary.count + 1;
currentKey = default(TKey);
return false;
}
public TKey Current {
get {
return currentKey;
}
}
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return currentKey;
}
}
void System.Collections.IEnumerator.Reset() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
index = 0;
currentKey = default(TKey);
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class ValueCollection: ICollection<TValue>, ICollection
{
private Dictionary<TKey,TValue> dictionary;
public ValueCollection(Dictionary<TKey,TValue> dictionary) {
if (dictionary == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
public Enumerator GetEnumerator() {
return new Enumerator(dictionary);
}
public void CopyTo(TValue[] array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < dictionary.Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) array[index++] = entries[i].value;
}
}
public int Count {
get { return dictionary.Count; }
}
bool ICollection<TValue>.IsReadOnly {
get { return true; }
}
void ICollection<TValue>.Add(TValue item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Remove(TValue item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
return false;
}
void ICollection<TValue>.Clear(){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Contains(TValue item){
return dictionary.ContainsValue(item);
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() {
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
TValue[] values = array as TValue[];
if (values != null) {
CopyTo(values, index);
}
else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try {
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) objects[index++] = entries[i].value;
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
}
bool ICollection.IsSynchronized {
get { return false; }
}
Object ICollection.SyncRoot {
get { return ((ICollection)dictionary).SyncRoot; }
}
[Serializable]
public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int index;
private int version;
private TValue currentValue;
internal Enumerator(Dictionary<TKey, TValue> dictionary) {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentValue = default(TValue);
}
public void Dispose() {
}
public bool MoveNext() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
while ((uint)index < (uint)dictionary.count) {
if (dictionary.entries[index].hashCode >= 0) {
currentValue = dictionary.entries[index].value;
index++;
return true;
}
index++;
}
index = dictionary.count + 1;
currentValue = default(TValue);
return false;
}
public TValue Current {
get {
return currentValue;
}
}
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return currentValue;
}
}
void System.Collections.IEnumerator.Reset() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
index = 0;
currentValue = default(TValue);
}
}
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kodestruct.Steel.AISC.UFM
{
public class UFMCaseNoMomentsAtInterfaces: UFMCase
{
public UFMCaseNoMomentsAtInterfaces(double d_b, double d_c, double theta,
double alpha, double beta, double P_u, double R_beam, bool IncludeDistortionalMomentForces,
double M_d, double A_ub )
:base(d_b,d_c,theta)
{
this.alpha = alpha;
this.beta = beta;
this.P_u = P_u;
this.R_beam = R_beam;
this.IncludeDistortionalMomentForces=IncludeDistortionalMomentForces;
this.M_d =M_d ;
this.A_ub = A_ub;
}
public double R_beam { get; set; }
public double P_u {get; set;}
public double alpha {get; set;}
public double beta { get; set; }
bool IncludeDistortionalMomentForces {get; set;}
double M_d {get; set;}
double A_ub { get; set; }
private void CalculateBasicParameters()
{
_r = Math.Sqrt(Math.Pow((alpha + e_c), 2) + Math.Pow((beta + e_b), 2));
//Distortional forces
CalculateDistortionalParameters();
double SignedH_d = P_u >= 0 ? _H_d : -H_d;
double SignedV_d = P_u >= 0 ? _V_d : -V_d;
double H_b_ND = alpha * ((P_u) / (_r)); //without effect of distortional forces
double V_b_ND = e_b * ((P_u) / (_r)) ; //without effect of distortional forces
double H_c_ND = e_c * ((P_u) / (_r)) ; //without effect of distortional forces
double V_c_ND = beta * ((P_u) / (_r)) ; //without effect of distortional forces
_H_b = H_b_ND - SignedH_d; //with effect of distortional forces
_V_b = V_b_ND + SignedV_d; //with effect of distortional forces
_H_c = H_c_ND - SignedH_d; //with effect of distortional forces
_V_c = V_c_ND + SignedV_d; //with effect of distortional forces
//beam interface
//per discussion in AISC Design guide 29 page 69 Example 5.1
//The Vub and Vab force is reversible as the brace force goes from tension to compression, but the gravity beam
//shear always remains in the same direction. Therefore, Vub and the reaction should always be added even if shown in
//opposite directions
if (_V_b >= 0)
{
_V_bc = V_b_ND + R_beam + SignedV_d;
}
else
{
_V_bc = -V_b_ND + R_beam - SignedV_d;
}
double SignedA_ub = P_u >= 0 ? A_ub : -A_ub;
//_H_bc = H_c_ND + SignedA_ub - SignedH_d;
_H_bc = _H_c + SignedA_ub;
BasicPropertiesAreCalculated = true;
}
bool BasicPropertiesAreCalculated;
private double _r;
public double r
{
get {
if (BasicPropertiesAreCalculated == false)
{
CalculateBasicParameters();
}
return _r; }
}
private double _H_b;
/// <summary>
/// Horizontal force at beam-gusset interface
/// </summary>
public double H_b
{
get {
if (BasicPropertiesAreCalculated ==false)
{
CalculateBasicParameters();
}
return _H_b; }
}
/// <summary>
/// Vertical force at beam-gusset interface
/// </summary>
private double _V_b;
public double V_b
{
get {
if (BasicPropertiesAreCalculated == false)
{
CalculateBasicParameters();
}
return _V_b; }
}
/// <summary>
/// Horizontal force at column-gusset interface
/// </summary>
private double _H_c;
public double H_c
{
get {
if (BasicPropertiesAreCalculated == false)
{
CalculateBasicParameters();
}
return _H_c; }
}
private double _V_c;
/// <summary>
/// Vertical force at column-gusset interface
/// </summary>
public double V_c
{
get {
if (BasicPropertiesAreCalculated == false)
{
CalculateBasicParameters();
}
return _V_c; }
}
/// <summary>
/// Horizontal force at beam-column interface
/// </summary>
private double _H_bc;
public double H_bc
{
get
{
if (BasicPropertiesAreCalculated == false)
{
CalculateBasicParameters();
}
return _H_bc;
}
}
private double _V_bc;
/// <summary>
/// Vertical force at beam-column interface
/// </summary>
public double V_bc
{
get
{
if (BasicPropertiesAreCalculated == false)
{
CalculateBasicParameters();
}
return _V_bc;
}
}
//Distortional forces
/// <summary>
/// Horizontal distortional force at gusset
/// </summary>
protected double _H_d;
public double H_d
{
get
{
if (BasicPropertiesAreCalculated == false)
{
CalculateDistortionalParameters();
}
return _H_d;
}
}
protected double _V_d;
/// <summary>
/// Vertical distortional force at gusset
/// </summary>
public double V_d
{
get
{
if (BasicPropertiesAreCalculated == false)
{
CalculateDistortionalParameters();
}
return _V_d;
}
}
protected virtual void CalculateDistortionalParameters()
{
if (IncludeDistortionalMomentForces ==true)
{
_H_d = Math.Abs(M_d) / (beta + e_b);
_V_d = beta / alpha * _H_d;
}
else
{
_H_d = 0.0;
_V_d = 0.0;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Custom_Scenery.Compression;
using MiniJSON;
using UnityEngine;
using Random = UnityEngine.Random;
namespace Custom_Scenery.CustomScenery
{
public class BillBoard : Deco
{
[Serialized]
public bool Pn = false;
[Serialized]
public string Image;
public string ImageSource;
public string Path { get; set; }
public string BannerPath { get; set; }
public string Size { get; set; }
private readonly List<Banner> _banners = new List<Banner>();
// GUI
private Vector2 _scrollPosition = Vector2.zero;
private GUISkin _skin;
private bool _show;
private Rect _windowPosition = new Rect(20, 20, 350, 320);
public override void Start()
{
base.Start();
BannerPath = FilePaths.getFolderPath("Banners");
// ReSharper disable once PossibleNullReferenceException
Path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(Main)).Location).Replace("bin", ""), "");
if (!Directory.Exists(BannerPath))
{
char dsc = System.IO.Path.DirectorySeparatorChar;
Directory.CreateDirectory(BannerPath);
Directory.CreateDirectory(BannerPath + dsc + "long");
Directory.CreateDirectory(BannerPath + dsc + "wide");
Directory.CreateDirectory(BannerPath + dsc + "square");
File.Copy(Path + dsc + "Banners" + dsc + "long" + dsc + "long.png", BannerPath + dsc + "long" + dsc + "long.png");
File.Copy(Path + dsc + "Banners" + dsc + "wide" + dsc + "wide.png", BannerPath + dsc + "wide" + dsc + "wide.png");
File.Copy(Path + dsc + "Banners" + dsc + "square" + dsc + "square.png", BannerPath + dsc + "square" + dsc + "square.png");
}
Size = gameObject.name.Split(' ').Last().Split('(').First();
if (string.IsNullOrEmpty(Image))
{
StartCoroutine(LoadRandomBanner());
}
else
{
Texture2D tex = new Texture2D(1, 1);
byte[] image = Decompress(Convert.FromBase64String(Image));
tex.LoadImage(image);
SetTexture(tex);
}
StartCoroutine(LoadGUISkin());
StartCoroutine(ReloadLocalBanners());
}
private IEnumerator LoadGUISkin()
{
char dsc = System.IO.Path.DirectorySeparatorChar;
using (WWW www = new WWW("file://" + Path + dsc + "assetbundle" + dsc + "guiskin"))
{
yield return www;
_skin = www.assetBundle.LoadAsset<GUISkin>("ParkitectGUISkin");
www.assetBundle.Unload(false);
}
}
public IEnumerator LoadRandomBanner()
{
if (Pn)
{
WWW www = new WWW("https://parkitectnexus.com/api/screenshots");
yield return www;
if (www.error == null)
{
Dictionary<string, object> dict = Json.Deserialize(www.text) as Dictionary<string, object>;
Dictionary<string, object> meta = dict["meta"] as Dictionary<string, object>;
Dictionary<string, object> pagination = meta["pagination"] as Dictionary<string, object>;
long total = (long)pagination["total"];
long perPage = (long)pagination["per_page"];
int pages = Mathf.CeilToInt(total / perPage);
www = new WWW("https://parkitectnexus.com/api/screenshots?page=" + Mathf.RoundToInt(Random.value * pages));
yield return www;
dict = Json.Deserialize(www.text) as Dictionary<string, object>;
List<object> screenshots = dict["data"] as List<object>;
Dictionary<string, object> screenshot = screenshots[Mathf.CeilToInt(Random.value * screenshots.Count - 1)] as Dictionary<string, object>;
Dictionary<string, object> resource = screenshot["image"] as Dictionary<string, object>;
ImageSource = resource["url"] as string;
}
else
{
Debug.Log(www.error);
}
}
else
{
ImageSource = LoadRandomFromDir(System.IO.Path.Combine(BannerPath, Size));
}
StartCoroutine(LoadImage());
}
private IEnumerator LoadImage()
{
if (Pn)
{
WWW www = new WWW(ImageSource);
yield return www;
Texture2D tex = new Texture2D(1, 1);
tex.LoadImage(www.bytes);
Image = Convert.ToBase64String(Compress(www.bytes));
SetTexture(tex);
}
else
{
SetTexture(LoadFromImage(ImageSource));
}
}
private IEnumerator ReloadLocalBanners()
{
_banners.Clear();
string[] files = Directory.GetFiles(System.IO.Path.Combine(BannerPath, Size));
foreach (string file in files)
{
Texture2D tex = LoadFromImage(file);
yield return null;
_banners.Add(new Banner { Source = file, Texture = tex });
}
}
private void OnMouseDown()
{
if (!GetComponent<BuildableObject>().isPreview && !UIUtility.isMouseOverUIElement())
_show = true;
}
private void OnGUI()
{
GUI.skin = _skin;
if (_show)
{
_windowPosition = GUI.Window(Mathf.RoundToInt(transform.position.x * transform.position.z), _windowPosition, BillboardWindow, "Billboard");
if (Input.GetKeyUp(KeyCode.Escape))
{
_show = false;
}
}
}
private void BillboardWindow(int windowID)
{
GUI.DragWindow(new Rect(0, 0, 310, 30));
if (GUI.Button(new Rect(320, 5, 20, 20), "x"))
{
_show = false;
}
bool orgPn = Pn;
Pn = GUI.Toggle(new Rect(10, 35, 300, 20), Pn, "Random screenshots from ParkitectNexus.com");
Pn = !GUI.Toggle(new Rect(10, 55, 300, 20), !Pn, "Local images");
if (GUI.Button(new Rect(10, 75, 130, 20), "New random banner") || Pn != orgPn)
{
StartCoroutine(LoadRandomBanner());
}
GUI.Label(new Rect(10, 100, 350, 20), "Banner images are located in:");
GUI.Label(new Rect(10, 120, 300, 20), BannerPath, new GUIStyle() { fontSize = 10, wordWrap = true });
if (!Pn)
{
_scrollPosition = GUI.BeginScrollView(new Rect(10, 145, 330, 170), _scrollPosition, new Rect(0, 0, 310, (_banners.Count / 5 + 1) * 60));
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < _banners.Count + 1; y++)
{
if (_banners.ElementAtOrDefault(x + y * 5) == null)
break;
if (GUI.Button(new Rect(x * 60, y * 60, 50, 50), _banners[x + y * 5].Texture, new GUIStyle() { padding = new RectOffset(0, 0, 0, 0), border = new RectOffset(0, 0, 0, 0) }))
{
ImageSource = _banners[x + y * 5].Source;
SetTexture(LoadFromImage(ImageSource));
}
}
}
GUI.EndScrollView();
}
}
private void SetTexture(Texture2D tex)
{
foreach (Renderer renderer in GetComponentsInChildren<Renderer>())
{
if (renderer.gameObject.name.StartsWith("Board"))
{
renderer.material.mainTexture = tex;
}
}
}
public string LoadRandomFromDir(string dir)
{
string[] files = Directory.GetFiles(dir);
int i = Mathf.Max(0, Mathf.RoundToInt(Random.value * files.Count() - 1));
string file = files[i];
return file;
}
public Texture2D LoadFromImage(string path)
{
Texture2D tex = null;
byte[] fileData;
if (File.Exists(path))
{
fileData = File.ReadAllBytes(path);
tex = new Texture2D(2, 2);
tex.LoadImage(fileData);
Image = Convert.ToBase64String(Compress(fileData));
}
return tex;
}
public byte[] Compress(byte[] data)
{
Texture2D tex = new Texture2D(1, 1);
tex.LoadImage(data);
switch (Size)
{
case "Long":
TextureScale.Bilinear(tex, 1000, 200);
break;
case "Wide":
TextureScale.Bilinear(tex, 500, 200);
break;
case "Square":
TextureScale.Bilinear(tex, 200, 200);
break;
}
data = tex.EncodeToJPG();
using (MemoryStream outStream = new MemoryStream())
{
using (GZipStream gzipStream = new GZipStream(outStream, CompressionMode.Compress))
using (MemoryStream srcStream = new MemoryStream(data))
{
CopyTo(srcStream, gzipStream);
//srcStream.CopyTo(gzipStream);
}
return outStream.ToArray();
}
}
public byte[] Decompress(byte[] compressed)
{
using (MemoryStream inStream = new MemoryStream(compressed))
using (GZipStream gzipStream = new GZipStream(inStream, CompressionMode.Decompress))
using (MemoryStream outStream = new MemoryStream())
{
CopyTo(gzipStream, outStream);
//gzipStream.CopyTo(outStream);
return outStream.ToArray();
}
}
public void CopyTo(Stream input, Stream output)
{
byte[] buffer = new byte[4 * 1024];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
}
| |
// 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 Xunit;
namespace System.IO.Tests
{
public static partial class PathTests
{
private static readonly char s_separator = Path.DirectorySeparatorChar;
public static IEnumerable<object[]> Combine_Basic_TestData()
{
yield return new object[] { new string[0] };
yield return new object[] { new string[] { "abc" } };
yield return new object[] { new string[] { "abc", "def" } };
yield return new object[] { new string[] { "abc", "def", "ghi", "jkl", "mno" } };
yield return new object[] { new string[] { "abc" + s_separator + "def", "def", "ghi", "jkl", "mno" } };
// All paths are empty
yield return new object[] { new string[] { "" } };
yield return new object[] { new string[] { "", "" } };
yield return new object[] { new string[] { "", "", "" } };
yield return new object[] { new string[] { "", "", "", "" } };
yield return new object[] { new string[] { "", "", "", "", "" } };
// Elements are all separated
yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator } };
yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator } };
yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator, "jkl" + s_separator } };
yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator, "jkl" + s_separator, "mno" + s_separator } };
}
public static IEnumerable<string> Combine_CommonCases_Input_TestData()
{
// Any path is rooted (starts with \, \\, A:)
yield return s_separator + "abc";
yield return s_separator + s_separator + "abc";
// Any path is empty (skipped)
yield return "";
// Any path is single element
yield return "abc";
yield return "abc" + s_separator;
// Any path is multiple element
yield return Path.Combine("abc", Path.Combine("def", "ghi"));
// Wildcard characters
yield return "*";
yield return "?";
// Obscure wildcard characters
yield return "\"";
yield return "<";
yield return ">";
}
public static IEnumerable<object[]> Combine_CommonCases_TestData()
{
foreach (string testPath in Combine_CommonCases_Input_TestData())
{
yield return new object[] { new string[] { testPath } };
yield return new object[] { new string[] { "abc", testPath } };
yield return new object[] { new string[] { testPath, "abc" } };
yield return new object[] { new string[] { "abc", "def", testPath } };
yield return new object[] { new string[] { "abc", testPath, "def" } };
yield return new object[] { new string[] { testPath, "abc", "def" } };
yield return new object[] { new string[] { "abc", "def", "ghi", testPath } };
yield return new object[] { new string[] { "abc", "def", testPath, "ghi" } };
yield return new object[] { new string[] { "abc", testPath, "def", "ghi" } };
yield return new object[] { new string[] { testPath, "abc", "def", "ghi" } };
yield return new object[] { new string[] { "abc", "def", "ghi", "jkl", testPath } };
yield return new object[] { new string[] { "abc", "def", "ghi", testPath, "jkl" } };
yield return new object[] { new string[] { "abc", "def", testPath, "ghi", "jkl" } };
yield return new object[] { new string[] { "abc", testPath, "def", "ghi", "jkl" } };
yield return new object[] { new string[] { testPath, "abc", "def", "ghi", "jkl" } };
}
}
[Theory]
[MemberData(nameof(Combine_Basic_TestData))]
[MemberData(nameof(Combine_CommonCases_TestData))]
public static void Combine(string[] paths)
{
string expected = string.Empty;
if (paths.Length > 0) expected = paths[0];
for (int i = 1; i < paths.Length; i++)
{
expected = Path.Combine(expected, paths[i]);
}
// Combine(string[])
Assert.Equal(expected, Path.Combine(paths));
// Verify special cases
switch (paths.Length)
{
case 2:
// Combine(string, string)
Assert.Equal(expected, Path.Combine(paths[0], paths[1]));
break;
case 3:
// Combine(string, string, string)
Assert.Equal(expected, Path.Combine(paths[0], paths[1], paths[2]));
break;
case 4:
// Combine(string, string, string, string)
Assert.Equal(expected, Path.Combine(paths[0], paths[1], paths[2], paths[3]));
break;
}
}
[Fact]
public static void PathIsNull()
{
VerifyException<ArgumentNullException>(null);
}
[Fact]
public static void PathIsNullWihtoutRootedAfterArgumentNull()
{
//any path is null without rooted after (ANE)
CommonCasesException<ArgumentNullException>(null);
}
[Fact]
public static void ContainsInvalidCharWithoutRootedAfterArgumentNull()
{
//any path contains invalid character without rooted after (AE)
CommonCasesException<ArgumentException>("ab\0cd");
}
[Fact]
[PlatformSpecific(Xunit.PlatformID.Windows)]
public static void ContainsInvalidCharWithoutRootedAfterArgumentNull_Windows()
{
//any path contains invalid character without rooted after (AE)
CommonCasesException<ArgumentException>("ab|cd");
CommonCasesException<ArgumentException>("ab\bcd");
CommonCasesException<ArgumentException>("ab\0cd");
CommonCasesException<ArgumentException>("ab\tcd");
}
[Fact]
public static void ContainsInvalidCharWithRootedAfterArgumentNull()
{
//any path contains invalid character with rooted after (AE)
CommonCasesException<ArgumentException>("ab\0cd", s_separator + "abc");
}
[Fact]
[PlatformSpecific(Xunit.PlatformID.Windows)]
public static void ContainsInvalidCharWithRootedAfterArgumentNull_Windows()
{
//any path contains invalid character with rooted after (AE)
CommonCasesException<ArgumentException>("ab|cd", s_separator + "abc");
CommonCasesException<ArgumentException>("ab\bcd", s_separator + "abc");
CommonCasesException<ArgumentException>("ab\tcd", s_separator + "abc");
}
private static void VerifyException<T>(string[] paths) where T : Exception
{
Assert.Throws<T>(() => Path.Combine(paths));
//verify passed as elements case
if (paths != null)
{
Assert.InRange(paths.Length, 1, 5);
Assert.Throws<T>(() =>
{
switch (paths.Length)
{
case 0:
Path.Combine();
break;
case 1:
Path.Combine(paths[0]);
break;
case 2:
Path.Combine(paths[0], paths[1]);
break;
case 3:
Path.Combine(paths[0], paths[1], paths[2]);
break;
case 4:
Path.Combine(paths[0], paths[1], paths[2], paths[3]);
break;
case 5:
Path.Combine(paths[0], paths[1], paths[2], paths[3], paths[4]);
break;
}
});
}
}
private static void CommonCasesException<T>(string testing) where T : Exception
{
VerifyException<T>(new string[] { testing });
VerifyException<T>(new string[] { "abc", testing });
VerifyException<T>(new string[] { testing, "abc" });
VerifyException<T>(new string[] { "abc", "def", testing });
VerifyException<T>(new string[] { "abc", testing, "def" });
VerifyException<T>(new string[] { testing, "abc", "def" });
VerifyException<T>(new string[] { "abc", "def", "ghi", testing });
VerifyException<T>(new string[] { "abc", "def", testing, "ghi" });
VerifyException<T>(new string[] { "abc", testing, "def", "ghi" });
VerifyException<T>(new string[] { testing, "abc", "def", "ghi" });
VerifyException<T>(new string[] { "abc", "def", "ghi", "jkl", testing });
VerifyException<T>(new string[] { "abc", "def", "ghi", testing, "jkl" });
VerifyException<T>(new string[] { "abc", "def", testing, "ghi", "jkl" });
VerifyException<T>(new string[] { "abc", testing, "def", "ghi", "jkl" });
VerifyException<T>(new string[] { testing, "abc", "def", "ghi", "jkl" });
}
private static void CommonCasesException<T>(string testing, string testing2) where T : Exception
{
VerifyException<T>(new string[] { testing, testing2 });
VerifyException<T>(new string[] { "abc", testing, testing2 });
VerifyException<T>(new string[] { testing, "abc", testing2 });
VerifyException<T>(new string[] { testing, testing2, "def" });
VerifyException<T>(new string[] { "abc", "def", testing, testing2 });
VerifyException<T>(new string[] { "abc", testing, "def", testing2 });
VerifyException<T>(new string[] { "abc", testing, testing2, "ghi" });
VerifyException<T>(new string[] { testing, "abc", "def", testing2 });
VerifyException<T>(new string[] { testing, "abc", testing2, "ghi" });
VerifyException<T>(new string[] { testing, testing2, "def", "ghi" });
VerifyException<T>(new string[] { "abc", "def", "ghi", testing, testing2 });
VerifyException<T>(new string[] { "abc", "def", testing, "ghi", testing2 });
VerifyException<T>(new string[] { "abc", "def", testing, testing2, "jkl" });
VerifyException<T>(new string[] { "abc", testing, "def", "ghi", testing2 });
VerifyException<T>(new string[] { "abc", testing, "def", testing2, "jkl" });
VerifyException<T>(new string[] { "abc", testing, testing2, "ghi", "jkl" });
VerifyException<T>(new string[] { testing, "abc", "def", "ghi", testing2 });
VerifyException<T>(new string[] { testing, "abc", "def", testing2, "jkl" });
VerifyException<T>(new string[] { testing, "abc", testing2, "ghi", "jkl" });
VerifyException<T>(new string[] { testing, testing2, "def", "ghi", "jkl" });
}
}
}
| |
/*
* ClrMethod.cs - Implementation of the
* "System.Reflection.ClrMethod" class.
*
* Copyright (C) 2001 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.Reflection
{
#if CONFIG_REFLECTION
using System;
using System.Globalization;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
internal sealed class ClrMethod : MethodInfo, IClrProgramItem
#if CONFIG_SERIALIZATION
, ISerializable
#endif
{
// Private data used by the runtime engine. This must be the first field.
private IntPtr privateData;
// Cached copy of the parameters.
private ParameterInfo[] parameters;
// Implement the IClrProgramItem interface.
public IntPtr ClrHandle
{
get
{
return privateData;
}
}
// Get the custom attributes attached to this method.
public override Object[] GetCustomAttributes(bool inherit)
{
return ClrHelpers.GetCustomAttributes(this, inherit);
}
public override Object[] GetCustomAttributes(Type type, bool inherit)
{
return ClrHelpers.GetCustomAttributes(this, type, inherit);
}
// Determine if custom attributes are defined for this method.
public override bool IsDefined(Type type, bool inherit)
{
return ClrHelpers.IsDefined(this, type, inherit);
}
// Get the parameters for this method.
public override ParameterInfo[] GetParameters()
{
if(parameters != null)
{
return parameters;
}
int numParams = ClrHelpers.GetNumParameters(privateData);
int param;
parameters = new ParameterInfo [numParams];
for(param = 0; param < numParams; ++param)
{
parameters[param] =
ClrHelpers.GetParameterInfo(this, this, param + 1);
}
return parameters;
}
// Invoke this method.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public override Object Invoke
(Object obj, BindingFlags invokeAttr, Binder binder,
Object[] parameters, CultureInfo culture);
// Get the method attributes.
public override MethodAttributes Attributes
{
get
{
return (MethodAttributes)
ClrHelpers.GetMemberAttrs(privateData);
}
}
// Override inherited properties.
public override Type DeclaringType
{
get
{
return ClrHelpers.GetDeclaringType(this);
}
}
public override Type ReflectedType
{
get
{
return ClrHelpers.GetDeclaringType(this);
}
}
public override String Name
{
get
{
return ClrHelpers.GetName(this);
}
}
public override Type ReturnType
{
get
{
return ClrHelpers.GetParameterType(privateData, 0);
}
}
// Get the base definition for this method.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public override MethodInfo GetBaseDefinition();
// Get the runtime method handle associated with this method.
#if ECMA_COMPAT
internal
#else
public
#endif
override RuntimeMethodHandle MethodHandle
{
get
{
return new RuntimeMethodHandle(privateData);
}
}
#if !ECMA_COMPAT
// Get the custom attribute provider for the return type.
public override ICustomAttributeProvider
ReturnTypeCustomAttributes
{
get
{
return ClrHelpers.GetParameterInfo(this, this, 0);
}
}
// Get the calling conventions for this method.
public override CallingConventions CallingConvention
{
get
{
return ClrHelpers.GetCallConv(privateData);
}
}
// Get the method implementation flags.
public override MethodImplAttributes GetMethodImplementationFlags()
{
return ClrHelpers.GetImplAttrs(privateData);
}
#endif // !ECMA_COMPAT
// Convert the method name into a string.
public override String ToString()
{
StringBuilder builder = new StringBuilder();
int numParams = ClrHelpers.GetNumParameters(privateData);
int param;
ParameterInfo paramInfo;
builder.Append(ReturnType.Name);
builder.Append(' ');
builder.Append(Name);
builder.Append('(');
for(param = 0; param < numParams; ++param)
{
if(param > 0)
{
builder.Append(", ");
}
paramInfo = ClrHelpers.GetParameterInfo
(this, this, param + 1);
builder.Append(paramInfo.ParameterType.Name);
}
builder.Append(')');
return builder.ToString();
}
// Determine if this method has generic arguments.
[MethodImpl(MethodImplOptions.InternalCall)]
extern protected override bool HasGenericArgumentsImpl();
// Determine if this method has uninstantiated generic parameters.
[MethodImpl(MethodImplOptions.InternalCall)]
extern protected override bool HasGenericParametersImpl();
// Get the arguments for this generic method instantiation.
[MethodImpl(MethodImplOptions.InternalCall)]
extern private Type[] GetGenericArgumentsImpl();
public override Type[] GetGenericArguments()
{
if(!HasGenericArgumentsImpl())
{
return new Type [0];
}
else
{
return GetGenericArgumentsImpl();
}
}
// Get the generic base method upon this instantiation was based.
[MethodImpl(MethodImplOptions.InternalCall)]
extern private ClrMethod GetGenericMethodDefinitionImpl();
public override MethodInfo GetGenericMethodDefinition()
{
if(HasGenericArgumentsImpl())
{
return GetGenericMethodDefinitionImpl();
}
else if(HasGenericParametersImpl())
{
// Not instantiated, so the base method is itself.
return this;
}
else
{
return null;
}
}
// Get the arity of an uninstantiated generic method.
[MethodImpl(MethodImplOptions.InternalCall)]
extern private int GetArity();
// Bind arguments to this generic method to instantiate it.
[MethodImpl(MethodImplOptions.InternalCall)]
extern private MethodInfo BindGenericParametersImpl(Type[] typeArgs);
public override MethodInfo BindGenericParameters(Type[] typeArgs)
{
if(typeArgs == null)
{
throw new ArgumentNullException("typeArgs");
}
ClrMethod method = this;
if(HasGenericArgumentsImpl())
{
// Use the base method, not the instantiated form.
method = GetGenericMethodDefinitionImpl();
}
if(!method.HasGenericParametersImpl())
{
throw new ArgumentException
(_("Arg_NotGenericMethod"));
}
else if(method.GetArity() != typeArgs.Length)
{
throw new ArgumentException
(_("Arg_GenericParameterCount"));
}
else
{
return method.BindGenericParametersImpl(typeArgs);
}
}
#if CONFIG_SERIALIZATION
// Get the serialization data for this method.
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if(info == null)
{
throw new ArgumentNullException("info");
}
MemberInfoSerializationHolder.Serialize
(info, MemberTypes.Method, Name, ToString(), ReflectedType);
}
#endif
}; // class ClrMethod
#endif // CONFIG_REFLECTION
}; // namespace System.Reflection
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text;
using fyiReporting.RDL;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for DialogDataSourceRef.
/// </summary>
public class DialogDataSourceRef : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbPassword;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox tbFilename;
private System.Windows.Forms.Button bGetFilename;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox cbDataProvider;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox tbConnection;
private System.Windows.Forms.CheckBox ckbIntSecurity;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox tbPrompt;
private System.Windows.Forms.Button bOK;
private System.Windows.Forms.Button bCancel;
private System.Windows.Forms.TextBox tbPassword2;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Button bTestConnection;
private System.Windows.Forms.ComboBox cbOdbcNames;
private System.Windows.Forms.Label lODBC;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public DialogDataSourceRef()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
string[] items = RdlEngineConfig.GetProviders();
cbDataProvider.Items.AddRange(items);
this.cbDataProvider.SelectedIndex = 0;
this.bOK.Enabled = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.tbPassword = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.tbFilename = new System.Windows.Forms.TextBox();
this.bGetFilename = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.cbDataProvider = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.tbConnection = new System.Windows.Forms.TextBox();
this.ckbIntSecurity = new System.Windows.Forms.CheckBox();
this.label5 = new System.Windows.Forms.Label();
this.tbPrompt = new System.Windows.Forms.TextBox();
this.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.tbPassword2 = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.bTestConnection = new System.Windows.Forms.Button();
this.cbOdbcNames = new System.Windows.Forms.ComboBox();
this.lODBC = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(440, 32);
this.label1.TabIndex = 0;
this.label1.Text = "Enter (twice) a pass phrase used to encrypt the data source reference file. You" +
" should use the same password you\'ve used to create previous files, as only one " +
"can be used.";
//
// tbPassword
//
this.tbPassword.Location = new System.Drawing.Point(16, 56);
this.tbPassword.Name = "tbPassword";
this.tbPassword.PasswordChar = '*';
this.tbPassword.Size = new System.Drawing.Size(184, 20);
this.tbPassword.TabIndex = 0;
this.tbPassword.Text = "";
this.tbPassword.TextChanged += new System.EventHandler(this.validate_TextChanged);
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 88);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(408, 16);
this.label2.TabIndex = 4;
this.label2.Text = "Enter the file name that will hold the encrypted data source information";
//
// tbFilename
//
this.tbFilename.Location = new System.Drawing.Point(16, 112);
this.tbFilename.Name = "tbFilename";
this.tbFilename.Size = new System.Drawing.Size(392, 20);
this.tbFilename.TabIndex = 2;
this.tbFilename.Text = "";
this.tbFilename.TextChanged += new System.EventHandler(this.validate_TextChanged);
//
// bGetFilename
//
this.bGetFilename.Location = new System.Drawing.Point(424, 112);
this.bGetFilename.Name = "bGetFilename";
this.bGetFilename.Size = new System.Drawing.Size(24, 23);
this.bGetFilename.TabIndex = 3;
this.bGetFilename.Text = "...";
this.bGetFilename.Click += new System.EventHandler(this.bGetFilename_Click);
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 152);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(80, 23);
this.label3.TabIndex = 7;
this.label3.Text = "Data provider";
//
// cbDataProvider
//
this.cbDataProvider.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDataProvider.Location = new System.Drawing.Point(80, 152);
this.cbDataProvider.Name = "cbDataProvider";
this.cbDataProvider.Size = new System.Drawing.Size(104, 21);
this.cbDataProvider.TabIndex = 4;
this.cbDataProvider.SelectedIndexChanged += new System.EventHandler(this.cbDataProvider_SelectedIndexChanged);
//
// label4
//
this.label4.Location = new System.Drawing.Point(8, 192);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(100, 16);
this.label4.TabIndex = 10;
this.label4.Text = "Connection string";
//
// tbConnection
//
this.tbConnection.Location = new System.Drawing.Point(16, 216);
this.tbConnection.Multiline = true;
this.tbConnection.Name = "tbConnection";
this.tbConnection.Size = new System.Drawing.Size(424, 40);
this.tbConnection.TabIndex = 7;
this.tbConnection.Text = "";
this.tbConnection.TextChanged += new System.EventHandler(this.validate_TextChanged);
//
// ckbIntSecurity
//
this.ckbIntSecurity.Location = new System.Drawing.Point(296, 184);
this.ckbIntSecurity.Name = "ckbIntSecurity";
this.ckbIntSecurity.Size = new System.Drawing.Size(144, 24);
this.ckbIntSecurity.TabIndex = 6;
this.ckbIntSecurity.Text = "Use integrated security";
//
// label5
//
this.label5.Location = new System.Drawing.Point(8, 272);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(432, 16);
this.label5.TabIndex = 12;
this.label5.Text = "(Optional) Enter the prompt displayed when asking for database credentials ";
//
// tbPrompt
//
this.tbPrompt.Location = new System.Drawing.Point(16, 296);
this.tbPrompt.Name = "tbPrompt";
this.tbPrompt.Size = new System.Drawing.Size(424, 20);
this.tbPrompt.TabIndex = 8;
this.tbPrompt.Text = "";
//
// bOK
//
this.bOK.Location = new System.Drawing.Point(272, 344);
this.bOK.Name = "bOK";
this.bOK.TabIndex = 10;
this.bOK.Text = "OK";
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(368, 344);
this.bCancel.Name = "bCancel";
this.bCancel.TabIndex = 11;
this.bCancel.Text = "Cancel";
//
// tbPassword2
//
this.tbPassword2.Location = new System.Drawing.Point(256, 56);
this.tbPassword2.Name = "tbPassword2";
this.tbPassword2.PasswordChar = '*';
this.tbPassword2.Size = new System.Drawing.Size(184, 20);
this.tbPassword2.TabIndex = 1;
this.tbPassword2.Text = "";
this.tbPassword2.TextChanged += new System.EventHandler(this.validate_TextChanged);
//
// label6
//
this.label6.Location = new System.Drawing.Point(208, 64);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(48, 23);
this.label6.TabIndex = 2;
this.label6.Text = "Repeat";
//
// bTestConnection
//
this.bTestConnection.Location = new System.Drawing.Point(16, 344);
this.bTestConnection.Name = "bTestConnection";
this.bTestConnection.Size = new System.Drawing.Size(96, 23);
this.bTestConnection.TabIndex = 9;
this.bTestConnection.Text = "Test Connection";
this.bTestConnection.Click += new System.EventHandler(this.bTestConnection_Click);
//
// cbOdbcNames
//
this.cbOdbcNames.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbOdbcNames.Location = new System.Drawing.Point(296, 152);
this.cbOdbcNames.Name = "cbOdbcNames";
this.cbOdbcNames.Size = new System.Drawing.Size(152, 21);
this.cbOdbcNames.Sorted = true;
this.cbOdbcNames.TabIndex = 5;
this.cbOdbcNames.SelectedIndexChanged += new System.EventHandler(this.cbOdbcNames_SelectedIndexChanged);
//
// lODBC
//
this.lODBC.Location = new System.Drawing.Point(184, 152);
this.lODBC.Name = "lODBC";
this.lODBC.Size = new System.Drawing.Size(112, 23);
this.lODBC.TabIndex = 17;
this.lODBC.Text = "ODBC Data Sources";
//
// DialogDataSourceRef
//
this.AcceptButton = this.bOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(456, 374);
this.Controls.Add(this.cbOdbcNames);
this.Controls.Add(this.lODBC);
this.Controls.Add(this.bTestConnection);
this.Controls.Add(this.label6);
this.Controls.Add(this.tbPassword2);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.bOK);
this.Controls.Add(this.tbPrompt);
this.Controls.Add(this.label5);
this.Controls.Add(this.ckbIntSecurity);
this.Controls.Add(this.tbConnection);
this.Controls.Add(this.label4);
this.Controls.Add(this.cbDataProvider);
this.Controls.Add(this.label3);
this.Controls.Add(this.bGetFilename);
this.Controls.Add(this.tbFilename);
this.Controls.Add(this.label2);
this.Controls.Add(this.tbPassword);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogDataSourceRef";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Create Data Source Reference File";
this.ResumeLayout(false);
}
#endregion
private void bGetFilename_Click(object sender, System.EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Data source reference files (*.dsr)|*.dsr" +
"|All files (*.*)|*.*";
sfd.FilterIndex = 1;
if (tbFilename.Text.Length > 0)
sfd.FileName = tbFilename.Text;
else
sfd.FileName = "*.dsr";
sfd.Title = "Specify Data Source Reference File Name";
sfd.OverwritePrompt = true;
sfd.DefaultExt = "dsr";
sfd.AddExtension = true;
try
{
if (sfd.ShowDialog() == DialogResult.OK)
tbFilename.Text = sfd.FileName;
}
finally
{
sfd.Dispose();
}
}
private void validate_TextChanged(object sender, System.EventArgs e)
{
if (this.tbFilename.Text.Length > 0 &&
this.tbPassword.Text.Length > 0 &&
this.tbPassword.Text == this.tbPassword2.Text &&
this.tbConnection.Text.Length > 0)
bOK.Enabled = true;
else
bOK.Enabled = false;
return;
}
private void bOK_Click(object sender, System.EventArgs e)
{
// Build the ConnectionProperties XML
StringBuilder sb = new StringBuilder();
sb.Append("<ConnectionProperties>");
sb.AppendFormat("<DataProvider>{0}</DataProvider>",
this.cbDataProvider.Text);
sb.AppendFormat("<ConnectString>{0}</ConnectString>",
this.tbConnection.Text.Replace("<", "<"));
sb.AppendFormat("<IntegratedSecurity>{0}</IntegratedSecurity>",
this.ckbIntSecurity.Checked? "true": "false");
if (this.tbPrompt.Text.Length > 0)
sb.AppendFormat("<Prompt>{0}</Prompt>",
this.tbPrompt.Text.Replace("<", "<"));
sb.Append("</ConnectionProperties>");
try
{
RDL.DataSourceReference.Create(tbFilename.Text, sb.ToString(), tbPassword.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Unable to create data source reference file");
return;
}
DialogResult = DialogResult.OK;
}
private void bTestConnection_Click(object sender, System.EventArgs e)
{
if (DesignerUtility.TestConnection(this.cbDataProvider.Text, tbConnection.Text))
MessageBox.Show("Connection succeeded!", "Test Connection");
}
private void cbDataProvider_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (cbDataProvider.Text == "ODBC")
{
lODBC.Visible = cbOdbcNames.Visible = true;
DesignerUtility.FillOdbcNames(cbOdbcNames);
}
else
{
lODBC.Visible = cbOdbcNames.Visible = false;
}
}
private void cbOdbcNames_SelectedIndexChanged(object sender, System.EventArgs e)
{
tbConnection.Text = "dsn=" + cbOdbcNames.Text + ";";
}
}
}
| |
//
// PKCS8.cs: PKCS #8 - Private-Key Information Syntax Standard
// ftp://ftp.rsasecurity.com/pub/pkcs/doc/pkcs-8.doc
//
// Author:
// Sebastien Pouliot <sebastien@xamarin.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
// Copyright 2013 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Security.Cryptography;
using Mono.Security.X509;
namespace Mono.Security.Cryptography {
internal sealed class PKCS8 {
public enum KeyInfo {
PrivateKey,
EncryptedPrivateKey,
Unknown
}
private PKCS8 ()
{
}
static public KeyInfo GetType (byte[] data)
{
if (data == null)
throw new ArgumentNullException ("data");
KeyInfo ki = KeyInfo.Unknown;
try {
ASN1 top = new ASN1 (data);
if ((top.Tag == 0x30) && (top.Count > 0)) {
ASN1 firstLevel = top [0];
switch (firstLevel.Tag) {
case 0x02:
ki = KeyInfo.PrivateKey;
break;
case 0x30:
ki = KeyInfo.EncryptedPrivateKey;
break;
}
}
}
catch {
throw new CryptographicException ("invalid ASN.1 data");
}
return ki;
}
/*
* PrivateKeyInfo ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey,
* attributes [0] IMPLICIT Attributes OPTIONAL
* }
*
* Version ::= INTEGER
*
* PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
*
* PrivateKey ::= OCTET STRING
*
* Attributes ::= SET OF Attribute
*/
public class PrivateKeyInfo {
private int _version;
private string _algorithm;
private byte[] _key;
private ArrayList _list;
public PrivateKeyInfo ()
{
_version = 0;
_list = new ArrayList ();
}
public PrivateKeyInfo (byte[] data) : this ()
{
Decode (data);
}
// properties
public string Algorithm {
get { return _algorithm; }
set { _algorithm = value; }
}
public ArrayList Attributes {
get { return _list; }
}
public byte[] PrivateKey {
get {
if (_key == null)
return null;
return (byte[]) _key.Clone ();
}
set {
if (value == null)
throw new ArgumentNullException ("PrivateKey");
_key = (byte[]) value.Clone ();
}
}
public int Version {
get { return _version; }
set {
if (value < 0)
throw new ArgumentOutOfRangeException ("negative version");
_version = value;
}
}
// methods
private void Decode (byte[] data)
{
ASN1 privateKeyInfo = new ASN1 (data);
if (privateKeyInfo.Tag != 0x30)
throw new CryptographicException ("invalid PrivateKeyInfo");
ASN1 version = privateKeyInfo [0];
if (version.Tag != 0x02)
throw new CryptographicException ("invalid version");
_version = version.Value [0];
ASN1 privateKeyAlgorithm = privateKeyInfo [1];
if (privateKeyAlgorithm.Tag != 0x30)
throw new CryptographicException ("invalid algorithm");
ASN1 algorithm = privateKeyAlgorithm [0];
if (algorithm.Tag != 0x06)
throw new CryptographicException ("missing algorithm OID");
_algorithm = ASN1Convert.ToOid (algorithm);
ASN1 privateKey = privateKeyInfo [2];
_key = privateKey.Value;
// attributes [0] IMPLICIT Attributes OPTIONAL
if (privateKeyInfo.Count > 3) {
ASN1 attributes = privateKeyInfo [3];
for (int i=0; i < attributes.Count; i++) {
_list.Add (attributes [i]);
}
}
}
public byte[] GetBytes ()
{
ASN1 privateKeyAlgorithm = new ASN1 (0x30);
privateKeyAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
privateKeyAlgorithm.Add (new ASN1 (0x05)); // ASN.1 NULL
ASN1 pki = new ASN1 (0x30);
pki.Add (new ASN1 (0x02, new byte [1] { (byte) _version }));
pki.Add (privateKeyAlgorithm);
pki.Add (new ASN1 (0x04, _key));
if (_list.Count > 0) {
ASN1 attributes = new ASN1 (0xA0);
foreach (ASN1 attribute in _list) {
attributes.Add (attribute);
}
pki.Add (attributes);
}
return pki.GetBytes ();
}
// static methods
static private byte[] RemoveLeadingZero (byte[] bigInt)
{
int start = 0;
int length = bigInt.Length;
if (bigInt [0] == 0x00) {
start = 1;
length--;
}
byte[] bi = new byte [length];
Buffer.BlockCopy (bigInt, start, bi, 0, length);
return bi;
}
static private byte[] Normalize (byte[] bigInt, int length)
{
if (bigInt.Length == length)
return bigInt;
else if (bigInt.Length > length)
return RemoveLeadingZero (bigInt);
else {
// pad with 0
byte[] bi = new byte [length];
Buffer.BlockCopy (bigInt, 0, bi, (length - bigInt.Length), bigInt.Length);
return bi;
}
}
/*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER, -- (inverse of q) mod p
* otherPrimeInfos OtherPrimeInfos OPTIONAL
* }
*/
static public RSA DecodeRSA (byte[] keypair)
{
ASN1 privateKey = new ASN1 (keypair);
if (privateKey.Tag != 0x30)
throw new CryptographicException ("invalid private key format");
ASN1 version = privateKey [0];
if (version.Tag != 0x02)
throw new CryptographicException ("missing version");
if (privateKey.Count < 9)
throw new CryptographicException ("not enough key parameters");
RSAParameters param = new RSAParameters ();
// note: MUST remove leading 0 - else MS wont import the key
param.Modulus = RemoveLeadingZero (privateKey [1].Value);
int keysize = param.Modulus.Length;
int keysize2 = (keysize >> 1); // half-size
// size must be normalized - else MS wont import the key
param.D = Normalize (privateKey [3].Value, keysize);
param.DP = Normalize (privateKey [6].Value, keysize2);
param.DQ = Normalize (privateKey [7].Value, keysize2);
param.Exponent = RemoveLeadingZero (privateKey [2].Value);
param.InverseQ = Normalize (privateKey [8].Value, keysize2);
param.P = Normalize (privateKey [4].Value, keysize2);
param.Q = Normalize (privateKey [5].Value, keysize2);
RSA rsa = null;
try {
rsa = RSA.Create ();
rsa.ImportParameters (param);
}
catch (CryptographicException) {
#if MONOTOUCH
// there's no machine-wide store available for iOS so we can drop the dependency on
// CspParameters (which drops other things, like XML key persistance, unless used elsewhere)
throw;
#else
// this may cause problem when this code is run under
// the SYSTEM identity on Windows (e.g. ASP.NET). See
// http://bugzilla.ximian.com/show_bug.cgi?id=77559
CspParameters csp = new CspParameters ();
csp.Flags = CspProviderFlags.UseMachineKeyStore;
rsa = new RSACryptoServiceProvider (csp);
rsa.ImportParameters (param);
#endif
}
return rsa;
}
/*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER, -- (inverse of q) mod p
* otherPrimeInfos OtherPrimeInfos OPTIONAL
* }
*/
static public byte[] Encode (RSA rsa)
{
RSAParameters param = rsa.ExportParameters (true);
ASN1 rsaPrivateKey = new ASN1 (0x30);
rsaPrivateKey.Add (new ASN1 (0x02, new byte [1] { 0x00 }));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Modulus));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Exponent));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.D));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.P));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Q));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DP));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DQ));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.InverseQ));
return rsaPrivateKey.GetBytes ();
}
// DSA only encode it's X private key inside an ASN.1 INTEGER (Hint: Tag == 0x02)
// which isn't enough for rebuilding the keypair. The other parameters
// can be found (98% of the time) in the X.509 certificate associated
// with the private key or (2% of the time) the parameters are in it's
// issuer X.509 certificate (not supported in the .NET framework).
static public DSA DecodeDSA (byte[] privateKey, DSAParameters dsaParameters)
{
ASN1 pvk = new ASN1 (privateKey);
if (pvk.Tag != 0x02)
throw new CryptographicException ("invalid private key format");
// X is ALWAYS 20 bytes (no matter if the key length is 512 or 1024 bits)
dsaParameters.X = Normalize (pvk.Value, 20);
DSA dsa = DSA.Create ();
dsa.ImportParameters (dsaParameters);
return dsa;
}
static public byte[] Encode (DSA dsa)
{
DSAParameters param = dsa.ExportParameters (true);
return ASN1Convert.FromUnsignedBigInteger (param.X).GetBytes ();
}
static public byte[] Encode (AsymmetricAlgorithm aa)
{
if (aa is RSA)
return Encode ((RSA)aa);
else if (aa is DSA)
return Encode ((DSA)aa);
else
throw new CryptographicException ("Unknown asymmetric algorithm {0}", aa.ToString ());
}
}
/*
* EncryptedPrivateKeyInfo ::= SEQUENCE {
* encryptionAlgorithm EncryptionAlgorithmIdentifier,
* encryptedData EncryptedData
* }
*
* EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
*
* EncryptedData ::= OCTET STRING
*
* --
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
*
* -- from PKCS#5
* PBEParameter ::= SEQUENCE {
* salt OCTET STRING SIZE(8),
* iterationCount INTEGER
* }
*/
public class EncryptedPrivateKeyInfo {
private string _algorithm;
private byte[] _salt;
private int _iterations;
private byte[] _data;
public EncryptedPrivateKeyInfo () {}
public EncryptedPrivateKeyInfo (byte[] data) : this ()
{
Decode (data);
}
// properties
public string Algorithm {
get { return _algorithm; }
set { _algorithm = value; }
}
public byte[] EncryptedData {
get { return (_data == null) ? null : (byte[]) _data.Clone (); }
set { _data = (value == null) ? null : (byte[]) value.Clone (); }
}
public byte[] Salt {
get {
if (_salt == null) {
RandomNumberGenerator rng = RandomNumberGenerator.Create ();
_salt = new byte [8];
rng.GetBytes (_salt);
}
return (byte[]) _salt.Clone ();
}
set { _salt = (byte[]) value.Clone (); }
}
public int IterationCount {
get { return _iterations; }
set {
if (value < 0)
throw new ArgumentOutOfRangeException ("IterationCount", "Negative");
_iterations = value;
}
}
// methods
private void Decode (byte[] data)
{
ASN1 encryptedPrivateKeyInfo = new ASN1 (data);
if (encryptedPrivateKeyInfo.Tag != 0x30)
throw new CryptographicException ("invalid EncryptedPrivateKeyInfo");
ASN1 encryptionAlgorithm = encryptedPrivateKeyInfo [0];
if (encryptionAlgorithm.Tag != 0x30)
throw new CryptographicException ("invalid encryptionAlgorithm");
ASN1 algorithm = encryptionAlgorithm [0];
if (algorithm.Tag != 0x06)
throw new CryptographicException ("invalid algorithm");
_algorithm = ASN1Convert.ToOid (algorithm);
// parameters ANY DEFINED BY algorithm OPTIONAL
if (encryptionAlgorithm.Count > 1) {
ASN1 parameters = encryptionAlgorithm [1];
if (parameters.Tag != 0x30)
throw new CryptographicException ("invalid parameters");
ASN1 salt = parameters [0];
if (salt.Tag != 0x04)
throw new CryptographicException ("invalid salt");
_salt = salt.Value;
ASN1 iterationCount = parameters [1];
if (iterationCount.Tag != 0x02)
throw new CryptographicException ("invalid iterationCount");
_iterations = ASN1Convert.ToInt32 (iterationCount);
}
ASN1 encryptedData = encryptedPrivateKeyInfo [1];
if (encryptedData.Tag != 0x04)
throw new CryptographicException ("invalid EncryptedData");
_data = encryptedData.Value;
}
// Note: PKCS#8 doesn't define how to generate the key required for encryption
// so you're on your own. Just don't try to copy the big guys too much ;)
// Netscape: http://www.cs.auckland.ac.nz/~pgut001/pubs/netscape.txt
// Microsoft: http://www.cs.auckland.ac.nz/~pgut001/pubs/breakms.txt
public byte[] GetBytes ()
{
if (_algorithm == null)
throw new CryptographicException ("No algorithm OID specified");
ASN1 encryptionAlgorithm = new ASN1 (0x30);
encryptionAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
// parameters ANY DEFINED BY algorithm OPTIONAL
if ((_iterations > 0) || (_salt != null)) {
ASN1 salt = new ASN1 (0x04, _salt);
ASN1 iterations = ASN1Convert.FromInt32 (_iterations);
ASN1 parameters = new ASN1 (0x30);
parameters.Add (salt);
parameters.Add (iterations);
encryptionAlgorithm.Add (parameters);
}
// encapsulates EncryptedData into an OCTET STRING
ASN1 encryptedData = new ASN1 (0x04, _data);
ASN1 encryptedPrivateKeyInfo = new ASN1 (0x30);
encryptedPrivateKeyInfo.Add (encryptionAlgorithm);
encryptedPrivateKeyInfo.Add (encryptedData);
return encryptedPrivateKeyInfo.GetBytes ();
}
}
}
}
| |
namespace Admin.UnitTest.ViewModels
{
using System.Collections.Generic;
using System.Linq;
using Admin.UnitTest.Framework;
using Common.EventAggregator;
using Common.Events;
using Common.Extensions;
using Common.Services;
using EnergyTrading.Contracts.Search;
using Microsoft.Practices.Prism.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Shell.ViewModels;
[TestClass]
public class when_performing_an_empty_name_search : SearchViewModelTestBase
{
[TestMethod]
public void search_should_contain_no_criteria()
{
Assert.AreEqual(0, this.search.SearchFields.Criterias.Count);
}
[TestMethod]
public void search_should_not_be_null()
{
Assert.IsNotNull(this.search);
}
protected override void Because_of()
{
this.Sut.IsMappingSearch = false;
this.Sut.NameSearch = null;
this.Sut.Search();
}
}
[TestClass]
public class when_performing_a_name_search_with_value : SearchViewModelTestBase
{
[TestMethod]
public void search_should_contain_single_criteria()
{
Assert.AreEqual(1, this.search.SearchFields.Criterias.Count);
}
[TestMethod]
public void search_should_match_on_entity_key()
{
var criteria = this.search.SearchFields.Criterias[0];
AssertSingleSearchCriteria("Name", SearchCondition.Contains, "Value", criteria);
}
[TestMethod]
public void search_should_not_be_null()
{
Assert.IsNotNull(this.search);
}
protected override void Because_of()
{
this.Sut.IsMappingSearch = false;
this.Sut.NameSearch = "Value";
this.Sut.Search();
}
protected override void Establish_context()
{
base.Establish_context();
this.Sut.SelectedMenuItem.SearchKey = "Name";
}
}
[TestClass]
public class when_performing_an_empty_mapping_search : SearchViewModelTestBase
{
[TestMethod]
public void search_should_contain_single_criteria()
{
Assert.AreEqual(1, this.search.SearchFields.Criterias.Count);
}
[TestMethod]
public void search_should_match_on_mapping_value()
{
var criteria = this.search.SearchFields.Criterias[0];
AssertSingleSearchCriteria("MappingValue", SearchCondition.Contains, null, criteria);
}
[TestMethod]
public void search_should_not_be_null()
{
Assert.IsNotNull(this.search);
}
protected override void Because_of()
{
this.Sut.IsMappingSearch = true;
this.Sut.NameSearch = null;
this.Sut.Search();
}
}
[TestClass]
public class when_performing_a_mapping_search_with_non_numeric_value : SearchViewModelTestBase
{
[TestMethod]
public void search_should_contain_single_criteria()
{
Assert.AreEqual(1, this.search.SearchFields.Criterias.Count);
}
[TestMethod]
public void search_should_match_on_mapping_value()
{
var criteria = this.search.SearchFields.Criterias[0];
AssertSingleSearchCriteria("MappingValue", SearchCondition.Contains, "abc", criteria);
}
[TestMethod]
public void search_should_not_be_null()
{
Assert.IsNotNull(this.search);
}
protected override void Because_of()
{
this.Sut.IsMappingSearch = true;
this.Sut.NameSearch = "abc";
this.Sut.Search();
}
}
[TestClass]
public class when_performing_a_mapping_search_with_numeric_value : SearchViewModelTestBase
{
[TestMethod]
public void search_should_contain_a_mapping_value_criteria()
{
var criteria = this.search.SearchFields.Criterias.FirstOrDefault(x => x.Criteria[0].Field == "MappingValue");
AssertSingleSearchCriteria("MappingValue", SearchCondition.Contains, "123", criteria);
}
[TestMethod]
public void search_should_contain_a_nexus_id_criteria()
{
var criteria =
this.search.SearchFields.Criterias.FirstOrDefault(x => x.Criteria[0].Field == "MainEntityName.Id");
AssertSingleSearchCriteria("MainEntityName.Id", SearchCondition.NumericEquals, "123", criteria);
}
[TestMethod]
public void search_should_contain_two_criteria()
{
Assert.AreEqual(2, this.search.SearchFields.Criterias.Count);
}
[TestMethod]
public void search_should_not_be_null()
{
Assert.IsNotNull(this.search);
}
protected override void Because_of()
{
this.Sut.IsMappingSearch = true;
this.Sut.NameSearch = "123";
this.Sut.Search();
}
}
[TestClass]
public class when_performing_a_mapping_search_with_numeric_value_and_nexus_source_system : SearchViewModelTestBase
{
[TestMethod]
public void search_should_contain_a_nexus_id_criteria()
{
var criteria =
this.search.SearchFields.Criterias.FirstOrDefault(x => x.Criteria[0].Field == "MainEntityName.Id");
AssertSingleSearchCriteria("MainEntityName.Id", SearchCondition.NumericEquals, "123", criteria);
}
[TestMethod]
public void search_should_contain_single_criteria()
{
Assert.AreEqual(1, this.search.SearchFields.Criterias.Count);
}
[TestMethod]
public void search_should_not_be_null()
{
Assert.IsNotNull(this.search);
}
protected override void Because_of()
{
this.Sut.IsMappingSearch = true;
this.Sut.SourceSystem = "Nexus";
this.Sut.NameSearch = "123";
this.Sut.Search();
}
}
[TestClass]
public class when_performing_a_mapping_search_with_non_nexus_source_system : SearchViewModelTestBase
{
[TestMethod]
public void criteria_should_contain_two_sub_criteria()
{
Assert.AreEqual(2, this.search.SearchFields.Criterias[0].Criteria.Count);
}
[TestMethod]
public void search_should_contain_single_criteria()
{
Assert.AreEqual(1, this.search.SearchFields.Criterias.Count);
}
[TestMethod]
public void search_should_match_on_mapping_value()
{
var criteria = this.search.SearchFields.Criterias[0].Criteria.FirstOrDefault(x => x.Field == "MappingValue");
AssertCriteria("MappingValue", SearchCondition.Contains, "123", criteria);
}
[TestMethod]
public void search_should_match_on_source_system()
{
var criteria = this.search.SearchFields.Criterias[0].Criteria.FirstOrDefault(x => x.Field == "System.Name");
AssertCriteria("System.Name", SearchCondition.Equals, "AnotherSystem", criteria);
}
[TestMethod]
public void search_should_not_be_null()
{
Assert.IsNotNull(this.search);
}
protected override void Because_of()
{
this.Sut.IsMappingSearch = true;
this.Sut.SourceSystem = "AnotherSystem";
this.Sut.NameSearch = "123";
this.Sut.Search();
}
}
[TestClass]
public class when_performing_a_nexus_id_search_for_derived_class : SearchViewModelTestBase
{
[TestMethod]
public void search_should_contain_a_nexus_id_criteria_for_base_class()
{
var criteria =
this.search.SearchFields.Criterias.FirstOrDefault(x => x.Criteria[0].Field == "BaseEntityName.Id");
AssertSingleSearchCriteria("BaseEntityName.Id", SearchCondition.NumericEquals, "123", criteria);
}
[TestMethod]
public void search_should_contain_single_criteria()
{
Assert.AreEqual(1, this.search.SearchFields.Criterias.Count);
}
[TestMethod]
public void search_should_not_be_null()
{
Assert.IsNotNull(this.search);
}
protected override void Because_of()
{
this.Sut.IsMappingSearch = true;
this.Sut.SourceSystem = "Nexus";
this.Sut.NameSearch = "123";
this.Sut.SelectedMenuItem.BaseEntityName = "BaseEntityName";
this.Sut.Search();
}
}
public class SearchViewModelTestBase : TestBase<SearchViewModel>
{
protected Search search;
protected static void AssertCriteria(
string mappingvalue,
SearchCondition searchCondition,
string comparisonValue,
Criteria criteria)
{
Assert.IsNotNull(criteria);
Assert.AreEqual(mappingvalue, criteria.Field);
Assert.AreEqual(searchCondition, criteria.Condition);
Assert.AreEqual(comparisonValue, criteria.ComparisonValue);
}
protected static void AssertSingleSearchCriteria(
string mappingvalue,
SearchCondition searchCondition,
string comparisonValue,
SearchCriteria searchCriteria)
{
Assert.IsNotNull(searchCriteria);
var criteria = searchCriteria.Criteria[0];
AssertCriteria(mappingvalue, searchCondition, comparisonValue, criteria);
}
protected override void Establish_context()
{
// explict mapping service mock
var mappingService = this.RegisterMock<IMappingService>();
mappingService.Setup(x => x.GetSourceSystemNames()).Returns(new List<string>());
// explict event publisher mock
var eventAggregatorExtensionsProvider = this.RegisterMock<IEventAggregatorExtensionsProvider>();
EventAggregatorExtensions.SetProvider(eventAggregatorExtensionsProvider.Object);
eventAggregatorExtensionsProvider.Setup(
x =>
x.Publish(
It.IsAny<IEventAggregator>(),
It.Is<SearchRequestEvent>(y => y.EntityName == "MainEntityName")))
.Callback<IEventAggregator, SearchRequestEvent>((a, b) => this.search = b.Search);
// create Sut
base.Establish_context();
var menuItemViewModel = this.Concrete<MenuItemViewModel>();
menuItemViewModel.Name = "MainEntityName";
this.Sut.SelectedMenuItem = menuItemViewModel;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
using UnityEditor.VersionControl;
using UnityEngine.Assertions;
namespace Framework.Editor
{
#region SYF
public class BeginNode : GraphNode
{
private UnityEditorInternal.ReorderableList DrawerList;
private ActionGraph Graph;
private float PreferredWidth;
private ActionGraphPresenter Presenter;
private List<int> ProxyList;
private List<float> _positions = new List<float>();
private List<float> Positions
{
get
{
//_positions.Resize(Graph.Inputs.Count + 1);
return _positions;
}
}
private float FirstPos;
void RecreateDrawer()
{
VariantUtils.SetDrawersForKnownTypes();
/*ProxyList = new List<int>(Graph.Inputs.Count);
DrawerList = new UnityEditorInternal.ReorderableList
(
ProxyList, typeof(ActionGraph.EntryPoint),
true, false, true, true
);
DrawerList.drawHeaderCallback += rect =>
{
rect.x += ParamListDrawer.ReorderableListOffset;
rect.width -= ParamListDrawer.ReorderableListOffset;
var original = rect;
rect.width *= 0.5f;
GUI.Label(rect, "Name");
rect.x = original.x + VariantUtils.LabelWidth * 1.35f;
rect.width = VariantUtils.FieldWidth;
GUI.Label(rect, "Input value");
};
DrawerList.onAddCallback += OnAddInput;
DrawerList.drawElementCallback += OnDrawParameter;
DrawerList.onCanAddCallback += list => Graph.InputType != null && Graph.InputType.Type != null;
DrawerList.onRemoveCallback += list =>
{
Presenter.OnRemoveInputAtIndex(list.index);
};
DrawerList.onReorderCallbackWithDetails += (list, index, newIndex) =>
{
float pos = Positions[index];
_positions.RemoveAt(index);
_positions.Insert(newIndex, pos);
Presenter.OnReorderInputAtIndex(index, newIndex);
};*/
}
public BeginNode(ActionGraph graph, ActionGraphPresenter presenter)
{
Graph = graph;
RecreateDrawer();
Size = new Vector2(400,300);
WindowTitle = GUIContent.none;
WindowStyle = SpaceEditorStyles.GraphNodeBackground;
PreferredWidth = drawRect.width;
Presenter = presenter;
Position = Graph.BeginEditorPos;
}
private void OnAddInput(UnityEditorInternal.ReorderableList list)
{
/*string typename = Variant.GetDisplayedName(Graph.InputType.Type);
string paramName = StringUtils.MakeUnique($"New {typename}", Graph.Inputs.Select(p => p.Input.Name));
ProxyList.Add(1);
Graph.Inputs.Add
(
new ActionGraph.EntryPoint()
{
Input = new Variant(Graph.InputType)
{
Name = paramName
}
}
);*/
}
private void OnDrawParameter(Rect rect, int index, bool active, bool focused)
{
/*var parameter = Graph.Inputs[index];
if (index == 0)
FirstPos = rect.y;
Positions[index] = rect.y - FirstPos;
rect.height = VariantUtils.FieldHeight;
rect.y += 2;
VariantUtils.DrawParameter(rect, parameter.Input);*/
}
protected override void OnSelected(bool value)
{
Selection.activeObject = Graph;
}
private void OnTypeChanged(SerializedType type)
{
// ToDo: Move to presenter
/*if (Graph.InputType != null && Graph.InputType == type)
return;
if (Graph.Inputs != null && Graph.Inputs.Any()
&& !EditorUtility.DisplayDialog("Warning!",
"This will erase existing input entries. Are you sure?",
"Ok",
"Cancel"))
{
return;
}
Graph.Inputs?.Clear();
Graph.InputType = type;*/
}
protected override void OnGUI()
{
drawRect.width = PreferredWidth;
if (Selected)
GUI.color = SpaceEditorStyles.ActiveColor;
GUI.Box(drawRect, GUIContent.none, WindowStyle);
DrawConnectDots(drawRect);
GUI.color = Color.white;
Graph.BeginEditorPos = Position;
}
Rect DrawNodeHeader()
{
drawRect.height = VariantUtils.FieldHeight * 2 + 6;
GUI.color = Selected ? SpaceEditorStyles.ActiveColor : Color.white;
GUI.Box(drawRect, GUIContent.none, Selected
? SpaceEditorStyles.GraphNodeBackgroundSelected
: SpaceEditorStyles.GraphNodeBackground);
GUI.color = Color.white;
// Padding for content
drawRect.y += 4;
drawRect.x += 4;
drawRect.width -= 8;
var old_rect = drawRect;
drawRect.x += 4;
drawRect.height = VariantUtils.FieldHeight * 1.5f;
GUI.Label(drawRect, "Inputs", EditorStyles.whiteLargeLabel);
return old_rect;
}
public override void GetChildConnectPositions(GraphNode child, IList<Vector2> pos)
{
/*float yPos = drawRect.yMin + ConnectorSize.y + 74;
var node = child as ActionGraphEditorNode;
if (node != null)
{
for (int i = 0; i < Graph.Inputs.Count; i++)
{
var input = Graph.Inputs[i];
if (input.Nodes.Contains(node.ActionNode))
{
pos.Add(new Vector2(drawRect.xMax, yPos + Positions[i]));
}
}
}*/
}
protected override bool CanConnectTo(Slot targetSlot, Slot childSlot)
{
return base.CanConnectTo(targetSlot, childSlot);
}
protected override void OnConnectToParent(Connection eventSource)
{
Assert.IsTrue(false, "Not supported!");
}
protected override void OnConnectToChild(Connection eventTarget)
{
/*if (eventTarget.From.Owner is ActionGraphEditorNode asGraph)
{
Presenter.OnConnectInputNode(asGraph);
}*/
}
protected override void OnParentDisconnected(Connection node)
{
}
void DrawConnectDots(Rect dotRect)
{
/*var inputsCount = Graph.Inputs.Count;
var yPos = FirstPos;
var xPos = drawRect.xMax - ConnectorSize.x * 0.5f;
GUI.color = Color.white;
if (inputsCount > 0)
{
for (int i = 0; i < inputsCount; i++)
{
var input = Graph.Inputs[i];
var rect = new Rect(xPos, yPos + Positions[i], ConnectorSize.x, ConnectorSize.y);
GUI.Box
(
rect, GUIContent.none, SpaceEditorStyles.DotFlowTarget
);
if (input.Nodes.Any())
{
GUI.color = Selected ? SpaceEditorStyles.ActiveColor : Color.white;
GUI.Box
(
rect, GUIContent.none, SpaceEditorStyles.DotFlowTargetFill
);
GUI.color = Color.white;
}
if (rect.Contains(Event.current.mousePosition)
&& Event.current.type == EventType.MouseDown
&& Event.current.button == 0)
{
// TODO pass actual slot
Presenter.OnInputDotClicked(null, i, rect.center);
}
}
}*/
}
protected override void OnDrawContent()
{
/*ProxyList.Resize(Graph.Inputs.Count);
EditorGUI.BeginChangeCheck();
{
var old_rect = DrawNodeHeader();
drawRect.y += VariantUtils.FieldHeight + 2;
drawRect.width = drawRect.width - 20;
drawRect.y += 20;
drawRect.height = VariantUtils.FieldHeight;
string content = Graph.InputType.ToString();
if (GUI.Button(drawRect, content, EditorStyles.objectField))
{
KnownTypeUtils.ShowAddParameterMenu(OnTypeChanged);
}
drawRect.x = old_rect.x;
drawRect.width = old_rect.width;
drawRect.y += VariantUtils.FieldHeight + 4;
drawRect.height = old_rect.height - drawRect.y;
var base_y = drawRect.y - old_rect.y;
if (DrawerList != null)
{
DrawerList.DoList(drawRect);
Size = new Vector2(Size.x, base_y + DrawerList.GetHeight() + 8);
}
}
if (EditorGUI.EndChangeCheck())
{
AssetDatabase.SaveAssets();
}*/
}
}
#endregion SYF
public class ActionGraphView : EditorView<ActionGraphView, ActionGraphPresenter>
{
private readonly GraphNodeEditor Nodes = new GraphNodeEditor();
private Dictionary<ActionGraphNodeBase, ActionGraphEditorNode> NodeLookup;
private List<System.Type> NodeEditors = new List<System.Type>();
[MenuItem("Framework/Action Graph Editor", false, 1)]
public static void MenuShowEditor()
{
FocusOrCreate();
}
public ActionGraphView()
{
Presenter = new ActionGraphPresenter(this);
Nodes.OnRightClick.Reassign(data =>
{
var node = Nodes.AllNodes.FirstOrDefault
(
n => n.PhysicalRect.Contains(
(data.MousePos * Nodes.ZoomLevel)
)) as ActionGraphEditorNode;
if (node != null)
Presenter.OnNodeRightClick(node, data.MousePos);
else
Presenter.OnRightClick(data.MousePos);
return true;
});
Nodes.OnLeftClick.Reassign(data =>
{
Presenter.OnLeftClick(data.MousePos);
return true;
});
Nodes.OnConnection.Reassign((data =>
{
if (data.Target != null)
{
if (GraphNode.CanMakeConnection(data.Source, data.Target))
{
Presenter.OnConnectChildNode(GraphNode.MakeConnection(data.Source, data.Target));
return true;
}
}
return false;
}));
Nodes.OnConnection.AddPost(data =>
{
if (data.Target == null)
{
Presenter.OnDropFailed(data.Source, data.MousePos);
}
});
Nodes.OnDeleteNode.AddPost(data =>
{
Presenter.OnNodeDeleted(data.Node as ActionGraphEditorNode);
Nodes.AllNodes.Remove(data.Node);
});
Nodes.OnSlotClicked.Reassign(data =>
{
Presenter.OnNodeConnectorClicked(data.Source, data.Source.Owner.GetSlotPosition(data.Source));
return true;
});
}
protected override void OnCreated()
{
}
void OnEnable()
{
name = " Action Graph ";
titleContent.image = SpaceEditorStyles.DotFlowTarget.normal.background;
titleContent.text = name;
Presenter.OnEnable();
}
private System.Type FindNodeEditor(ActionGraphNodeBase node)
{
return NodeEditors.FirstOrDefault(t => t.CustomAttributes.Any(
a =>
{
if (a.AttributeType == typeof(CustomActionEditor)
&& a.ConstructorArguments.Count >= 1)
{
return a.ConstructorArguments[0].Value == node.GetType();
}
return false;
}));
}
private ActionGraphEditorNode CreateNodeEditor(ActionGraphNodeBase node, ActionGraph graph)
{
var editorNodeType = FindNodeEditor(node);
ActionGraphEditorNode editorNode = null;
if (editorNodeType != null)
{
editorNode = Activator.CreateInstance(editorNodeType, graph, node, Presenter)
as ActionGraphEditorNode;
}
else
{
editorNode = new ActionGraphEditorNode(graph, node, Presenter);
}
NodeLookup[node] = editorNode;
Nodes.AddNode(editorNode);
return editorNode;
}
public void RecreateNodes(ActionGraph asset)
{
using (new GraphNode.NodeRecreationContext())
{
if (NodeLookup != null)
NodeLookup.Clear();
else
NodeLookup = new Dictionary<ActionGraphNodeBase, ActionGraphEditorNode>();
ActionGraphEditorNode.WindowStyle = SpaceEditorStyles.GraphNodeBackground;
Nodes.ClearNodes();
if (asset)
{
Nodes.ScrollPos = asset.EditorPos;
NodeEditors = ReferenceTypePicker.BuildTypeList(string.Empty,
t => t.IsSubclassOf(typeof(ActionGraphEditorNode))
).ToList();
if (asset.AnyEntryNode)
{
CreateNodeEditor(asset.AnyEntryNode, asset);
}
foreach (var entry in asset.NamedEventEntries)
{
CreateNodeEditor(entry, asset);
}
foreach (ActionGraphNode node in asset.Nodes)
{
CreateNodeEditor(node, asset);
}
foreach (GraphNode graphNode in Nodes.AllNodes.Where(t => t is ActionGraphEditorNode))
{
var asGraph = (ActionGraphEditorNode) graphNode;
asGraph.RebuildConnections(LookupEditorNode);
}
}
}
}
private bool showParams;
private float ParamsWidth = 300;
private Splitter Split = new Splitter();
public void OnDraw(ActionGraph graph, string assetPath)
{
GUILayout.BeginVertical();
{
GUILayout.BeginHorizontal();
{
DrawNodeGraph();
if (showParams)
{
Split.Layout();
DrawParameters(graph);
}
}
GUILayout.EndHorizontal();
DrawFooter(graph, assetPath);
HandleEvents();
}
GUILayout.EndVertical();
}
private void HandleEvents()
{
var (wantsRepaint, paramWidthDelta) = Split.HandleWidth();
ParamsWidth -= paramWidthDelta;
ParamsWidth = Mathf.Clamp(ParamsWidth, 100, EditorSize.x * 0.9f);
Nodes.WantsRepaint = wantsRepaint;
Nodes.HandleEvents(this);
}
public void OnUpdate()
{
if (Nodes.WantsRepaint)
Repaint();
}
private Rect NodeGraphRect = new Rect();
private void DrawNodeGraph()
{
GUILayout.BeginVertical(SpaceEditorStyles.GraphNodeEditorBackground);
{
// Reserve space for graph
var targetRect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true));
NodeGraphRect.Set(0, 16 + 21, targetRect.width, position.height - 21 - 16);
Nodes.Draw(this, NodeGraphRect);
}
GUILayout.EndVertical();
}
private ParamListDrawer _drawer;
private ParamListDrawer GetDrawer(ActionGraph graph)
{
if (_drawer == null)
{
_drawer = new ParamListDrawer();
_drawer.Init(graph.Parameters);
_drawer.Recreate();
}
return _drawer;
}
private void DrawParameters(ActionGraph graph)
{
GUILayout.BeginVertical(GUILayout.Width(ParamsWidth));
{
var drawer = GetDrawer(graph);
EditorGUI.BeginChangeCheck();
{
drawer.DrawerList.DoLayoutList();
}
if (EditorGUI.EndChangeCheck())
{
graph.Parameters = drawer.GetParameters();
AssetDatabase.SaveAssets();
}
}
GUILayout.EndVertical();
}
private void DrawFooter(ActionGraph graph, string assetPath)
{
EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); // GUI.skin.box,
{
if (GUILayout.Button(assetPath, EditorStyles.label))
{
Selection.activeObject = graph;
EditorGUIUtility.PingObject(graph);
}
GUILayout.FlexibleSpace();
//GUILayout.Label($"<<{(Nodes.CurrentMouseMode != null ? Nodes.CurrentMouseMode.GetType().Name : "null")}>>");
//GUILayout.Label($"{Nodes.ScrollPos} :: {Event.current.mousePosition} :: ");
GUILayout.Label($"{Nodes.ZoomLevel * 100:##.##}%");
Nodes.ZoomLevel = GUILayout.HorizontalSlider(Nodes.ZoomLevel, Nodes.MinZoom, Nodes.MaxZoom, GUILayout.Width(64));
showParams = GUILayout.Toggle(showParams, "Params", EditorStyles.toolbarButton);
}
EditorGUILayout.EndHorizontal();
}
internal void DrawCreationButton()
{
GUI.Label(new Rect(EditorSize.x * 0.5f - 175, EditorSize.y * 0.5f - 15, 350, 30), "Select Action Graph in project tab to edit, or create new ");
if (GUI.Button(new Rect(EditorSize.x * 0.5f - 50, EditorSize.y * 0.5f + 15, 100, 20), "Create"))
{
Presenter.OnCreateNewAsset();
}
}
public Vector2 GetScrollPos()
{
return Nodes.ScrollPos;
}
ActionGraphEditorNode LookupEditorNode(object obj)
{
return NodeLookup[obj as ActionGraphNodeBase
?? throw new Exception($"Cannot cast {obj} to ActionGraphNode!")];
}
public GraphNode OnNodeAdded(ActionGraph asset, ActionGraphNodeBase node)
{
var editorNode = CreateNodeEditor(node, asset);
editorNode.RebuildConnections(LookupEditorNode);
return editorNode;
}
public void TryBeginConnection(Slot slot, Vector2 pos)
{
Nodes.StartConnection(slot, pos);
}
// public void OnRemoveInput(ActionGraph.EntryPoint input)
// {
// foreach (var node in input.Nodes)
// {
// Begin.RemoveConnection(NodeLookup[node]);
// }
// }
public void DisconnectNodes(Connection connection)
{
connection.From.Owner.RemoveConnection(connection);
}
[Obsolete("Do not use this! Remove nodes by connection!")]
public void DisconnectNodes(ActionGraphNode parent, ActionGraphNode node)
{
throw new Exception("Removing connection by node itself is no longer supported!");
var editorParent = NodeLookup[parent];
var editorNode = NodeLookup[node];
//editorParent.RemoveConnection(editorNode);
// Presenter.OnNodeDisconnected(editorParent, editorNode);
}
[Obsolete("Do not use this! Remove nodes by connection!")]
public void DisconnectNodes(GraphNode node, ActionGraphEditorNode child)
{
throw new Exception("Removing connection by node itself is no longer supported!");
/*node.RemoveConnection(child);
if (node == Begin)
{
Presenter.OnInputDisconnected(child);
}
else
{
Presenter.OnNodeDisconnected(node as ActionGraphEditorNode, child);
}*/
}
public void DeleteNode(ActionGraphEditorNode node)
{
Nodes.OnDeleteNode.Post().Node = node;
}
public void OnSelectionChanged()
{
Nodes.DeselectNodes();
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IdentityModel.Claims;
using System.IdentityModel.Tokens;
using System.IdentityModel.Policy;
using System.Security.Principal;
using System.Security;
public class SamlSecurityTokenAuthenticator : SecurityTokenAuthenticator
{
List<SecurityTokenAuthenticator> supportingAuthenticators;
Collection<string> allowedAudienceUris;
AudienceUriMode audienceUriMode;
TimeSpan maxClockSkew;
public SamlSecurityTokenAuthenticator(IList<SecurityTokenAuthenticator> supportingAuthenticators)
: this(supportingAuthenticators, TimeSpan.Zero)
{ }
public SamlSecurityTokenAuthenticator(IList<SecurityTokenAuthenticator> supportingAuthenticators, TimeSpan maxClockSkew)
{
if (supportingAuthenticators == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("supportingAuthenticators");
this.supportingAuthenticators = new List<SecurityTokenAuthenticator>(supportingAuthenticators.Count);
for (int i = 0; i < supportingAuthenticators.Count; ++i)
{
this.supportingAuthenticators.Add(supportingAuthenticators[i]);
}
this.maxClockSkew = maxClockSkew;
this.audienceUriMode = AudienceUriMode.Always;
this.allowedAudienceUris = new Collection<string>();
}
public AudienceUriMode AudienceUriMode
{
get { return this.audienceUriMode; }
set
{
AudienceUriModeValidationHelper.Validate(audienceUriMode);
this.audienceUriMode = value;
}
}
public IList<string> AllowedAudienceUris
{
get { return this.allowedAudienceUris; }
}
protected override bool CanValidateTokenCore(SecurityToken token)
{
return token is SamlSecurityToken;
}
protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
{
if (token == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
SamlSecurityToken samlToken = token as SamlSecurityToken;
if (samlToken == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlTokenAuthenticatorCanOnlyProcessSamlTokens, token.GetType().ToString())));
if (samlToken.Assertion.Signature == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlTokenMissingSignature)));
if (!this.IsCurrentlyTimeEffective(samlToken))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLTokenTimeInvalid, DateTime.UtcNow.ToUniversalTime(), samlToken.ValidFrom.ToString(), samlToken.ValidTo.ToString())));
if (samlToken.Assertion.SigningToken == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlSigningTokenMissing)));
// Build the Issuer ClaimSet for this Saml token.
ClaimSet issuer = null;
bool canBeValidated = false;
for (int i = 0; i < this.supportingAuthenticators.Count; ++i)
{
canBeValidated = this.supportingAuthenticators[i].CanValidateToken(samlToken.Assertion.SigningToken);
if (canBeValidated)
break;
}
if (!canBeValidated)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlInvalidSigningToken)));
issuer = ResolveClaimSet(samlToken.Assertion.SigningToken) ?? ClaimSet.Anonymous;
List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();
for (int i = 0; i < samlToken.Assertion.Statements.Count; ++i)
{
policies.Add(samlToken.Assertion.Statements[i].CreatePolicy(issuer, this));
}
// Check AudienceUri if required
// AudienceUriMode != Never - don't need to check can only be one of three
// AudienceUriMode == Always
// AudienceUriMode == BearerKey and there are no proof keys
//
if ((this.audienceUriMode == AudienceUriMode.Always)
|| (this.audienceUriMode == AudienceUriMode.BearerKeyOnly) && (samlToken.SecurityKeys.Count < 1))
{
// throws if not found.
bool foundAudienceCondition = false;
if (this.allowedAudienceUris == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAudienceUrisNotFound)));
}
for (int i = 0; i < samlToken.Assertion.Conditions.Conditions.Count; i++)
{
SamlAudienceRestrictionCondition audienceCondition = samlToken.Assertion.Conditions.Conditions[i] as SamlAudienceRestrictionCondition;
if (audienceCondition == null)
continue;
foundAudienceCondition = true;
if (!ValidateAudienceRestriction(audienceCondition))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAudienceUriValidationFailed)));
}
}
if (!foundAudienceCondition)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAudienceUriValidationFailed)));
}
return policies.AsReadOnly();
}
protected virtual bool ValidateAudienceRestriction(SamlAudienceRestrictionCondition audienceRestrictionCondition)
{
for (int i = 0; i < audienceRestrictionCondition.Audiences.Count; i++)
{
if (audienceRestrictionCondition.Audiences[i] == null)
continue;
for (int j = 0; j < this.allowedAudienceUris.Count; j++)
{
if (StringComparer.Ordinal.Compare(audienceRestrictionCondition.Audiences[i].AbsoluteUri, this.allowedAudienceUris[j]) == 0)
return true;
else if (Uri.IsWellFormedUriString(this.allowedAudienceUris[j], UriKind.Absolute))
{
Uri uri = new Uri(this.allowedAudienceUris[j]);
if (audienceRestrictionCondition.Audiences[i].Equals(uri))
return true;
}
}
}
return false;
}
public virtual ClaimSet ResolveClaimSet(SecurityToken token)
{
if (token == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
for (int i = 0; i < this.supportingAuthenticators.Count; ++i)
{
if (this.supportingAuthenticators[i].CanValidateToken(token))
{
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = this.supportingAuthenticators[i].ValidateToken(token);
AuthorizationContext authContext = AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies);
if (authContext.ClaimSets.Count > 0)
{
return authContext.ClaimSets[0];
}
}
}
return null;
}
public virtual ClaimSet ResolveClaimSet(SecurityKeyIdentifier keyIdentifier)
{
if (keyIdentifier == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier");
RsaKeyIdentifierClause rsaKeyIdentifierClause;
EncryptedKeyIdentifierClause encryptedKeyIdentifierClause;
if (keyIdentifier.TryFind<RsaKeyIdentifierClause>(out rsaKeyIdentifierClause))
{
return new DefaultClaimSet(new Claim(ClaimTypes.Rsa, rsaKeyIdentifierClause.Rsa, Rights.PossessProperty));
}
else if (keyIdentifier.TryFind<EncryptedKeyIdentifierClause>(out encryptedKeyIdentifierClause))
{
return new DefaultClaimSet(Claim.CreateHashClaim(encryptedKeyIdentifierClause.GetBuffer()));
}
return null;
}
public virtual IIdentity ResolveIdentity(SecurityToken token)
{
if (token == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
for (int i = 0; i < this.supportingAuthenticators.Count; ++i)
{
if (this.supportingAuthenticators[i].CanValidateToken(token))
{
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = this.supportingAuthenticators[i].ValidateToken(token);
if (authorizationPolicies != null && authorizationPolicies.Count != 0)
{
for (int j = 0; j < authorizationPolicies.Count; ++j)
{
IAuthorizationPolicy policy = authorizationPolicies[j];
if (policy is UnconditionalPolicy)
{
return ((UnconditionalPolicy)policy).PrimaryIdentity;
}
}
}
}
}
return null;
}
public virtual IIdentity ResolveIdentity(SecurityKeyIdentifier keyIdentifier)
{
if (keyIdentifier == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier");
RsaKeyIdentifierClause rsaKeyIdentifierClause;
if (keyIdentifier.TryFind<RsaKeyIdentifierClause>(out rsaKeyIdentifierClause))
{
return SecurityUtils.CreateIdentity(rsaKeyIdentifierClause.Rsa.ToXmlString(false), this.GetType().Name);
}
return null;
}
bool IsCurrentlyTimeEffective(SamlSecurityToken token)
{
if (token.Assertion.Conditions != null)
{
return SecurityUtils.IsCurrentlyTimeEffective(token.Assertion.Conditions.NotBefore, token.Assertion.Conditions.NotOnOrAfter, this.maxClockSkew);
}
// If SAML Condition is not present then the assertion is valid at any given time.
return true;
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Linq;
using System.Abstract;
using System.Collections.Generic;
using Hiro.Containers;
using System.Reflection;
namespace Hiro.Abstract
{
/// <summary>
/// IHiroServiceLocator
/// </summary>
public interface IHiroServiceLocator : IServiceLocator
{
/// <summary>
/// Gets the builder.
/// </summary>
DependencyMap Builder { get; }
/// <summary>
/// Gets the container.
/// </summary>
IMicroContainer Container { get; }
}
/// <summary>
/// HiroServiceLocator
/// </summary>
[Serializable]
public class HiroServiceLocator : IHiroServiceLocator, IDisposable, ServiceLocatorManager.ISetupRegistration
{
IMicroContainer _container;
HiroServiceRegistrar _registrar;
Func<IMicroContainer> _containerBuilder;
static HiroServiceLocator() { ServiceLocatorManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="HiroServiceLocator"/> class.
/// </summary>
public HiroServiceLocator()
: this(new DependencyMap()) { }
/// <summary>
/// Initializes a new instance of the <see cref="HiroServiceLocator"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public HiroServiceLocator(object builder)
{
if (builder == null)
throw new ArgumentNullException("builder");
Builder = (builder as DependencyMap);
if (Builder == null)
throw new ArgumentOutOfRangeException("builder", "Must be of type Hiro.DependencyMap");
_registrar = new HiroServiceRegistrar(this, Builder, out _containerBuilder);
}
//public HiroServiceLocator(IMicroContainer container)
//{
// if (container == null)
// throw new ArgumentNullException("container");
// Container = container;
//}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (_container != null)
{
_container = null;
_registrar = null;
_containerBuilder = null;
}
}
Action<IServiceLocator, string> ServiceLocatorManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceLocatorManager.RegisterInstance<IHiroServiceLocator>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.-or- null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { return Resolve(serviceType); }
/// <summary>
/// Creates the child.
/// </summary>
/// <returns></returns>
public IServiceLocator CreateChild(object tag) { throw new NotSupportedException(); }
/// <summary>
/// Gets the underlying container.
/// </summary>
/// <typeparam name="TContainer">The type of the container.</typeparam>
/// <returns></returns>
public TContainer GetUnderlyingContainer<TContainer>()
where TContainer : class { return (_container as TContainer); }
// registrar
/// <summary>
/// Gets the registrar.
/// </summary>
public IServiceRegistrar Registrar
{
get { return _registrar; }
}
// resolve
/// <summary>
/// Resolves this instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns></returns>
public TService Resolve<TService>()
where TService : class
{
try { return (Builder.Contains(typeof(TService)) ? Container.GetInstance<TService>() : Activator.CreateInstance<TService>()); }
catch (ReflectionTypeLoadException) { throw; }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves the specified name.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="name">The name.</param>
/// <returns></returns>
public TService Resolve<TService>(string name)
where TService : class
{
if (!Builder.Contains(typeof(TService), name))
throw new ServiceLocatorResolutionException(typeof(TService), string.Format("Unregistered '{0}'", name));
try { return Container.GetInstance<TService>(name); }
catch (ReflectionTypeLoadException) { throw; }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public object Resolve(Type serviceType)
{
try { return (Builder.Contains(serviceType) ? Container.GetInstance(serviceType, null) : Activator.CreateInstance(serviceType)); }
catch (ReflectionTypeLoadException) { throw; }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
/// <summary>
/// Resolves the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public object Resolve(Type serviceType, string name)
{
if (!Builder.Contains(serviceType, name))
throw new ServiceLocatorResolutionException(serviceType, string.Format("Unregistered '{0}'", name));
try { return Container.GetInstance(serviceType, name); }
catch (ReflectionTypeLoadException) { throw; }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
//
/// <summary>
/// Resolves all.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns></returns>
public IEnumerable<TService> ResolveAll<TService>()
where TService : class
{
try { return new List<TService>(Container.GetAllInstances(typeof(TService)).Cast<TService>()); }
catch (ReflectionTypeLoadException) { throw; }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves all.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public IEnumerable<object> ResolveAll(Type serviceType)
{
try { return new List<object>(Container.GetAllInstances(serviceType)); }
catch (ReflectionTypeLoadException) { throw; }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
// inject
/// <summary>
/// Injects the specified instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
/// <returns></returns>
public TService Inject<TService>(TService instance)
where TService : class { return null; }
// release and teardown
/// <summary>
/// Releases the specified instance.
/// </summary>
/// <param name="instance">The instance.</param>
public void Release(object instance) { throw new NotSupportedException(); }
/// <summary>
/// Tears down.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
public void TearDown<TService>(TService instance)
where TService : class { throw new NotSupportedException(); }
#region Domain specific
/// <summary>
/// Gets the builder.
/// </summary>
public DependencyMap Builder { get; private set; }
/// <summary>
/// Gets the container.
/// </summary>
public IMicroContainer Container
{
get
{
if (_container == null)
_container = _containerBuilder();
return _container;
}
private set { _container = value; }
}
#endregion
}
}
| |
namespace IdSharp.Tagging.Harness.WinForms.UserControls
{
partial class ID3v1UserControl
{
/// <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()
{
this.txtFilename = new System.Windows.Forms.TextBox();
this.lblArtist = new System.Windows.Forms.Label();
this.txtArtist = new System.Windows.Forms.TextBox();
this.txtTitle = new System.Windows.Forms.TextBox();
this.txtAlbum = new System.Windows.Forms.TextBox();
this.txtYear = new System.Windows.Forms.TextBox();
this.lblTitle = new System.Windows.Forms.Label();
this.lblAlbum = new System.Windows.Forms.Label();
this.lblTrack = new System.Windows.Forms.Label();
this.lblGenre = new System.Windows.Forms.Label();
this.txtTrackNumber = new System.Windows.Forms.TextBox();
this.lblYear = new System.Windows.Forms.Label();
this.cmbID3v1 = new System.Windows.Forms.ComboBox();
this.lblFilename = new System.Windows.Forms.Label();
this.lblID3v1 = new System.Windows.Forms.Label();
this.cmbGenre = new System.Windows.Forms.ComboBox();
this.txtComment = new System.Windows.Forms.TextBox();
this.lblComment = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// txtFilename
//
this.txtFilename.Location = new System.Drawing.Point(98, 9);
this.txtFilename.Name = "txtFilename";
this.txtFilename.ReadOnly = true;
this.txtFilename.Size = new System.Drawing.Size(300, 20);
this.txtFilename.TabIndex = 101;
this.txtFilename.TabStop = false;
//
// lblArtist
//
this.lblArtist.AutoSize = true;
this.lblArtist.Location = new System.Drawing.Point(10, 65);
this.lblArtist.Name = "lblArtist";
this.lblArtist.Size = new System.Drawing.Size(30, 13);
this.lblArtist.TabIndex = 106;
this.lblArtist.Text = "Artist";
//
// txtArtist
//
this.txtArtist.Location = new System.Drawing.Point(98, 62);
this.txtArtist.MaxLength = 30;
this.txtArtist.Name = "txtArtist";
this.txtArtist.Size = new System.Drawing.Size(300, 20);
this.txtArtist.TabIndex = 104;
//
// txtTitle
//
this.txtTitle.Location = new System.Drawing.Point(98, 88);
this.txtTitle.MaxLength = 30;
this.txtTitle.Name = "txtTitle";
this.txtTitle.Size = new System.Drawing.Size(300, 20);
this.txtTitle.TabIndex = 105;
//
// txtAlbum
//
this.txtAlbum.Location = new System.Drawing.Point(98, 114);
this.txtAlbum.MaxLength = 30;
this.txtAlbum.Name = "txtAlbum";
this.txtAlbum.Size = new System.Drawing.Size(300, 20);
this.txtAlbum.TabIndex = 107;
//
// txtYear
//
this.txtYear.Location = new System.Drawing.Point(98, 166);
this.txtYear.MaxLength = 4;
this.txtYear.Name = "txtYear";
this.txtYear.Size = new System.Drawing.Size(75, 20);
this.txtYear.TabIndex = 114;
//
// lblTitle
//
this.lblTitle.AutoSize = true;
this.lblTitle.Location = new System.Drawing.Point(10, 91);
this.lblTitle.Name = "lblTitle";
this.lblTitle.Size = new System.Drawing.Size(27, 13);
this.lblTitle.TabIndex = 108;
this.lblTitle.Text = "Title";
//
// lblAlbum
//
this.lblAlbum.AutoSize = true;
this.lblAlbum.Location = new System.Drawing.Point(10, 117);
this.lblAlbum.Name = "lblAlbum";
this.lblAlbum.Size = new System.Drawing.Size(36, 13);
this.lblAlbum.TabIndex = 109;
this.lblAlbum.Text = "Album";
//
// lblTrack
//
this.lblTrack.AutoSize = true;
this.lblTrack.Location = new System.Drawing.Point(10, 195);
this.lblTrack.Name = "lblTrack";
this.lblTrack.Size = new System.Drawing.Size(35, 13);
this.lblTrack.TabIndex = 122;
this.lblTrack.Text = "Track";
//
// lblGenre
//
this.lblGenre.AutoSize = true;
this.lblGenre.Location = new System.Drawing.Point(10, 143);
this.lblGenre.Name = "lblGenre";
this.lblGenre.Size = new System.Drawing.Size(36, 13);
this.lblGenre.TabIndex = 110;
this.lblGenre.Text = "Genre";
//
// txtTrackNumber
//
this.txtTrackNumber.Location = new System.Drawing.Point(98, 192);
this.txtTrackNumber.MaxLength = 3;
this.txtTrackNumber.Name = "txtTrackNumber";
this.txtTrackNumber.Size = new System.Drawing.Size(75, 20);
this.txtTrackNumber.TabIndex = 115;
//
// lblYear
//
this.lblYear.AutoSize = true;
this.lblYear.Location = new System.Drawing.Point(10, 169);
this.lblYear.Name = "lblYear";
this.lblYear.Size = new System.Drawing.Size(29, 13);
this.lblYear.TabIndex = 112;
this.lblYear.Text = "Year";
//
// cmbID3v1
//
this.cmbID3v1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbID3v1.FormattingEnabled = true;
this.cmbID3v1.Items.AddRange(new object[] {
"ID3v1.0",
"ID3v1.1"});
this.cmbID3v1.Location = new System.Drawing.Point(98, 35);
this.cmbID3v1.Name = "cmbID3v1";
this.cmbID3v1.Size = new System.Drawing.Size(75, 21);
this.cmbID3v1.TabIndex = 103;
this.cmbID3v1.SelectedIndexChanged += new System.EventHandler(this.cmbID3v1_SelectedIndexChanged);
//
// lblFilename
//
this.lblFilename.AutoSize = true;
this.lblFilename.Location = new System.Drawing.Point(10, 12);
this.lblFilename.Name = "lblFilename";
this.lblFilename.Size = new System.Drawing.Size(52, 13);
this.lblFilename.TabIndex = 113;
this.lblFilename.Text = "File name";
//
// lblID3v1
//
this.lblID3v1.AutoSize = true;
this.lblID3v1.Location = new System.Drawing.Point(10, 38);
this.lblID3v1.Name = "lblID3v1";
this.lblID3v1.Size = new System.Drawing.Size(36, 13);
this.lblID3v1.TabIndex = 121;
this.lblID3v1.Text = "ID3v1";
//
// cmbGenre
//
this.cmbGenre.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbGenre.FormattingEnabled = true;
this.cmbGenre.Location = new System.Drawing.Point(98, 140);
this.cmbGenre.Name = "cmbGenre";
this.cmbGenre.Size = new System.Drawing.Size(146, 21);
this.cmbGenre.TabIndex = 111;
//
// txtComment
//
this.txtComment.Location = new System.Drawing.Point(98, 218);
this.txtComment.Name = "txtComment";
this.txtComment.Size = new System.Drawing.Size(300, 20);
this.txtComment.TabIndex = 123;
//
// lblComment
//
this.lblComment.AutoSize = true;
this.lblComment.Location = new System.Drawing.Point(10, 221);
this.lblComment.Name = "lblComment";
this.lblComment.Size = new System.Drawing.Size(51, 13);
this.lblComment.TabIndex = 124;
this.lblComment.Text = "Comment";
//
// ID3v1UserControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.txtComment);
this.Controls.Add(this.lblComment);
this.Controls.Add(this.txtFilename);
this.Controls.Add(this.lblArtist);
this.Controls.Add(this.txtArtist);
this.Controls.Add(this.txtTitle);
this.Controls.Add(this.txtAlbum);
this.Controls.Add(this.txtYear);
this.Controls.Add(this.lblTitle);
this.Controls.Add(this.lblAlbum);
this.Controls.Add(this.lblTrack);
this.Controls.Add(this.lblGenre);
this.Controls.Add(this.txtTrackNumber);
this.Controls.Add(this.lblYear);
this.Controls.Add(this.cmbID3v1);
this.Controls.Add(this.lblFilename);
this.Controls.Add(this.lblID3v1);
this.Controls.Add(this.cmbGenre);
this.Name = "ID3v1UserControl";
this.Size = new System.Drawing.Size(704, 333);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtFilename;
private System.Windows.Forms.Label lblArtist;
private System.Windows.Forms.TextBox txtArtist;
private System.Windows.Forms.TextBox txtTitle;
private System.Windows.Forms.TextBox txtAlbum;
private System.Windows.Forms.TextBox txtYear;
private System.Windows.Forms.Label lblTitle;
private System.Windows.Forms.Label lblAlbum;
private System.Windows.Forms.Label lblTrack;
private System.Windows.Forms.Label lblGenre;
private System.Windows.Forms.TextBox txtTrackNumber;
private System.Windows.Forms.Label lblYear;
private System.Windows.Forms.ComboBox cmbID3v1;
private System.Windows.Forms.Label lblFilename;
private System.Windows.Forms.Label lblID3v1;
private System.Windows.Forms.ComboBox cmbGenre;
private System.Windows.Forms.TextBox txtComment;
private System.Windows.Forms.Label lblComment;
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Xunit.ConsoleClient
{
public class Program
{
volatile static bool cancel;
static bool failed;
static readonly ConcurrentDictionary<string, ExecutionSummary> completionMessages = new ConcurrentDictionary<string, ExecutionSummary>();
[STAThread]
public static int Main(string[] args)
{
try
{
Console.ForegroundColor = ConsoleColor.White;
#if !NETCORE
var netVersion = Environment.Version;
#else
var netVersion = "Core";
#endif
Console.WriteLine("xUnit.net console test runner ({0}-bit .NET {1})", IntPtr.Size * 8, netVersion);
Console.WriteLine("Copyright (C) 2014 Outercurve Foundation.");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
if (args.Length == 0 || args[0] == "-?")
{
PrintUsage();
return 1;
}
#if !NETCORE
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
#endif
Console.CancelKeyPress += (sender, e) =>
{
if (!cancel)
{
Console.WriteLine("Canceling... (Press Ctrl+C again to terminate)");
cancel = true;
e.Cancel = true;
}
};
var defaultDirectory = Directory.GetCurrentDirectory();
if (!defaultDirectory.EndsWith(new String(new[] { Path.DirectorySeparatorChar })))
defaultDirectory += Path.DirectorySeparatorChar;
var commandLine = CommandLine.Parse(args);
var failCount = RunProject(defaultDirectory, commandLine.Project, commandLine.TeamCity, commandLine.AppVeyor,
commandLine.ParallelizeAssemblies, commandLine.ParallelizeTestCollections,
commandLine.MaxParallelThreads);
if (commandLine.Wait)
{
Console.WriteLine();
Console.Write("Press enter key to continue...");
Console.ReadLine();
Console.WriteLine();
}
return failCount;
}
catch (ArgumentException ex)
{
Console.WriteLine("error: {0}", ex.Message);
return 1;
}
catch (BadImageFormatException ex)
{
Console.WriteLine("{0}", ex.Message);
return 1;
}
finally
{
Console.ResetColor();
}
}
#if !NETCORE
static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception;
if (ex != null)
Console.WriteLine(ex.ToString());
else
Console.WriteLine("Error of unknown type thrown in application domain");
Environment.Exit(1);
}
#endif
static void PrintUsage()
{
#if !NETCORE
var executableName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().GetLocalCodeBase());
#else
var executableName = "xunit.console.netcore";
#endif
Console.WriteLine("usage: {0} <assemblyFile> [configFile] [assemblyFile [configFile]...] [options]", executableName);
Console.WriteLine();
Console.WriteLine("Note: Configuration files must end in .config");
Console.WriteLine();
Console.WriteLine("Valid options:");
Console.WriteLine(" -parallel option : set parallelization based on option");
Console.WriteLine(" : none - turn off all parallelization");
Console.WriteLine(" : collections - only parallelize collections");
Console.WriteLine(" : assemblies - only parallelize assemblies");
Console.WriteLine(" : all - parallelize assemblies & collections");
Console.WriteLine(" -maxthreads count : maximum thread count for collection parallelization");
Console.WriteLine(" : 0 - run with unbounded thread count");
Console.WriteLine(" : >0 - limit task thread pool size to 'count'");
Console.WriteLine(" -noshadow : do not shadow copy assemblies");
#if !NETCORE
Console.WriteLine(" -teamcity : forces TeamCity mode (normally auto-detected)");
Console.WriteLine(" -appveyor : forces AppVeyor CI mode (normally auto-detected)");
#endif
Console.WriteLine(" -wait : wait for input after completion");
Console.WriteLine(" -trait \"name=value\" : only run tests with matching name/value traits");
Console.WriteLine(" : if specified more than once, acts as an OR operation");
Console.WriteLine(" -notrait \"name=value\" : do not run tests with matching name/value traits");
Console.WriteLine(" : if specified more than once, acts as an AND operation");
Console.WriteLine(" -method \"name\" : run a given test method (should be fully specified;");
Console.WriteLine(" : i.e., 'MyNamespace.MyClass.MyTestMethod')");
Console.WriteLine(" : if specified more than once, acts as an OR operation");
Console.WriteLine(" -class \"name\" : run all methods in a given test class (should be fully");
Console.WriteLine(" : specified; i.e., 'MyNamespace.MyClass')");
Console.WriteLine(" : if specified more than once, acts as an OR operation");
TransformFactory.AvailableTransforms.ForEach(
transform => Console.WriteLine(" {0} : {1}",
String.Format("-{0} <filename>", transform.CommandLine).PadRight(22).Substring(0, 22),
transform.Description)
);
}
static int RunProject(string defaultDirectory, XunitProject project, bool teamcity, bool appVeyor, bool? parallelizeAssemblies, bool? parallelizeTestCollections, int? maxThreadCount)
{
XElement assembliesElement = null;
var xmlTransformers = TransformFactory.GetXmlTransformers(project);
var needsXml = xmlTransformers.Count > 0;
var consoleLock = new object();
if (!parallelizeAssemblies.HasValue)
parallelizeAssemblies = project.All(assembly => assembly.Configuration.ParallelizeAssembly ?? false);
if (needsXml)
assembliesElement = new XElement("assemblies");
var originalWorkingFolder = Directory.GetCurrentDirectory();
using (AssemblyHelper.SubscribeResolve())
{
var clockTime = Stopwatch.StartNew();
if (parallelizeAssemblies.GetValueOrDefault())
{
var tasks = project.Assemblies.Select(assembly => Task.Run(() => ExecuteAssembly(consoleLock, defaultDirectory, assembly, needsXml, teamcity, appVeyor, parallelizeTestCollections, maxThreadCount, project.Filters)));
var results = Task.WhenAll(tasks).GetAwaiter().GetResult();
foreach (var assemblyElement in results.Where(result => result != null))
assembliesElement.Add(assemblyElement);
}
else
{
foreach (var assembly in project.Assemblies)
{
var assemblyElement = ExecuteAssembly(consoleLock, defaultDirectory, assembly, needsXml, teamcity, appVeyor, parallelizeTestCollections, maxThreadCount, project.Filters);
if (assemblyElement != null)
assembliesElement.Add(assemblyElement);
}
}
clockTime.Stop();
if (completionMessages.Count > 0)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine();
Console.WriteLine("=== TEST EXECUTION SUMMARY ===");
Console.ForegroundColor = ConsoleColor.Gray;
var totalTestsRun = completionMessages.Values.Sum(summary => summary.Total);
var totalTestsFailed = completionMessages.Values.Sum(summary => summary.Failed);
var totalTestsSkipped = completionMessages.Values.Sum(summary => summary.Skipped);
var totalTime = completionMessages.Values.Sum(summary => summary.Time).ToString("0.000s");
var totalErrors = completionMessages.Values.Sum(summary => summary.Errors);
var longestAssemblyName = completionMessages.Keys.Max(key => key.Length);
var longestTotal = totalTestsRun.ToString().Length;
var longestFailed = totalTestsFailed.ToString().Length;
var longestSkipped = totalTestsSkipped.ToString().Length;
var longestTime = totalTime.Length;
var longestErrors = totalErrors.ToString().Length;
foreach (var message in completionMessages.OrderBy(m => m.Key))
Console.WriteLine(" {0} Total: {1}, Errors: {2}, Failed: {3}, Skipped: {4}, Time: {5}",
message.Key.PadRight(longestAssemblyName),
message.Value.Total.ToString().PadLeft(longestTotal),
message.Value.Errors.ToString().PadLeft(longestErrors),
message.Value.Failed.ToString().PadLeft(longestFailed),
message.Value.Skipped.ToString().PadLeft(longestSkipped),
message.Value.Time.ToString("0.000s").PadLeft(longestTime));
if (completionMessages.Count > 1)
Console.WriteLine(" {0} {1} {2} {3} {4} {5}" + Environment.NewLine +
" {6} {7} {8} {9} {10} {11} ({12})",
" ".PadRight(longestAssemblyName),
"-".PadRight(longestTotal, '-'),
"-".PadRight(longestErrors, '-'),
"-".PadRight(longestFailed, '-'),
"-".PadRight(longestSkipped, '-'),
"-".PadRight(longestTime, '-'),
"GRAND TOTAL:".PadLeft(longestAssemblyName),
totalTestsRun,
totalErrors,
totalTestsFailed,
totalTestsSkipped,
totalTime,
clockTime.Elapsed.TotalSeconds.ToString("0.000s"));
}
}
Directory.SetCurrentDirectory(originalWorkingFolder);
xmlTransformers.ForEach(transformer => transformer(assembliesElement));
return failed ? 1 : completionMessages.Values.Sum(summary => summary.Failed);
}
static XmlTestExecutionVisitor CreateVisitor(object consoleLock, string defaultDirectory, XElement assemblyElement, bool teamCity, bool appVeyor)
{
#if !NETCORE
if (teamCity)
return new TeamCityVisitor(assemblyElement, () => cancel);
else if (appVeyor)
return new AppVeyorVisitor(consoleLock, defaultDirectory, assemblyElement, () => cancel, completionMessages);
#endif
return new StandardOutputVisitor(consoleLock, defaultDirectory, assemblyElement, () => cancel, completionMessages);
}
static XElement ExecuteAssembly(object consoleLock, string defaultDirectory, XunitProjectAssembly assembly, bool needsXml, bool teamCity, bool appVeyor, bool? parallelizeTestCollections, int? maxThreadCount, XunitFilters filters)
{
if (cancel)
return null;
var assemblyElement = needsXml ? new XElement("assembly") : null;
try
{
if (!ValidateFileExists(consoleLock, assembly.AssemblyFilename) || !ValidateFileExists(consoleLock, assembly.ConfigFilename))
return null;
// Turn off pre-enumeration of theories, since there is no theory selection UI in this runner
assembly.Configuration.PreEnumerateTheories = false;
var discoveryOptions = TestFrameworkOptions.ForDiscovery(assembly.Configuration);
var executionOptions = TestFrameworkOptions.ForExecution(assembly.Configuration);
if (maxThreadCount.HasValue)
executionOptions.SetMaxParallelThreads(maxThreadCount.GetValueOrDefault());
if (parallelizeTestCollections.HasValue)
executionOptions.SetDisableParallelization(!parallelizeTestCollections.GetValueOrDefault());
lock (consoleLock)
{
if (assembly.Configuration.DiagnosticMessages ?? false)
Console.WriteLine("Discovering: {0} (method display = {1}, parallel test collections = {2}, max threads = {3})",
Path.GetFileNameWithoutExtension(assembly.AssemblyFilename),
discoveryOptions.GetMethodDisplay(),
!executionOptions.GetDisableParallelization(),
executionOptions.GetMaxParallelThreads());
else
Console.WriteLine("Discovering: {0}", Path.GetFileNameWithoutExtension(assembly.AssemblyFilename));
}
using (var controller = new XunitFrontController(assembly.AssemblyFilename, assembly.ConfigFilename, assembly.ShadowCopy))
using (var discoveryVisitor = new TestDiscoveryVisitor())
{
controller.Find(includeSourceInformation: false, messageSink: discoveryVisitor, discoveryOptions: discoveryOptions);
discoveryVisitor.Finished.WaitOne();
lock (consoleLock)
Console.WriteLine("Discovered: {0}", Path.GetFileNameWithoutExtension(assembly.AssemblyFilename));
var resultsVisitor = CreateVisitor(consoleLock, defaultDirectory, assemblyElement, teamCity, appVeyor);
var filteredTestCases = discoveryVisitor.TestCases.Where(filters.Filter).ToList();
if (filteredTestCases.Count == 0)
{
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Warning: {0} has no tests to run", Path.GetFileNameWithoutExtension(assembly.AssemblyFilename));
Console.ForegroundColor = ConsoleColor.Gray;
}
}
else
{
controller.RunTests(filteredTestCases, resultsVisitor, executionOptions);
resultsVisitor.Finished.WaitOne();
}
}
}
catch (Exception ex)
{
Console.WriteLine("{0}: {1}", ex.GetType().FullName, ex.Message);
failed = true;
}
return assemblyElement;
}
static bool ValidateFileExists(object consoleLock, string fileName)
{
if (String.IsNullOrWhiteSpace(fileName) || File.Exists(fileName))
return true;
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("File not found: {0}", fileName);
Console.ForegroundColor = ConsoleColor.Gray;
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using EPiServer;
using EPiServer.Configuration;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Filters;
using EPiServer.Logging;
using EPiServer.ServiceLocation;
using EPiServer.Web;
namespace SampleAlloy.Business.ContentProviders
{
/// <summary>
/// Used to clone a part of the page tree
/// </summary>
/// <remarks>The current implementation only supports cloning of <see cref="PageData"/> content</remarks>
/// <code>
/// // Example of programmatically registering a cloned content provider
///
/// var rootPageOfContentToClone = new PageReference(10);
///
/// var pageWhereClonedContentShouldAppear = new PageReference(20);
///
/// var provider = new ClonedContentProvider(rootPageOfContentToClone, pageWhereClonedContentShouldAppear);
///
/// var providerManager = ServiceLocator.Current.GetInstance<IContentProviderManager>();
///
/// providerManager.ProviderMap.AddProvider(provider);
/// </code>
public class ClonedContentProvider : ContentProvider, IPageCriteriaQueryService
{
private static readonly ILogger Logger = LogManager.GetLogger();
private readonly NameValueCollection _parameters = new NameValueCollection(1);
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot) : this(cloneRoot, entryRoot, null) { }
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot, CategoryList categoryFilter)
{
if (cloneRoot.CompareToIgnoreWorkID(entryRoot))
{
throw new NotSupportedException("Entry root and clone root cannot be set to the same content reference");
}
if (ServiceLocator.Current.GetInstance<IContentLoader>().GetChildren<IContent>(entryRoot).Any())
{
throw new NotSupportedException("Unable to create ClonedContentProvider, the EntryRoot property must point to leaf content (without children)");
}
CloneRoot = cloneRoot;
EntryRoot = entryRoot;
Category = categoryFilter;
// Set the entry point parameter
Parameters.Add(ContentProviderElement.EntryPointString, EntryRoot.ID.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Clones a page to make it appear to come from where the content provider is attached
/// </summary>
private PageData ClonePage(PageData originalPage)
{
if (originalPage == null)
{
throw new ArgumentNullException("originalPage", "No page to clone specified");
}
Logger.Debug("Cloning page {0}...", originalPage.PageLink);
var clone = originalPage.CreateWritableClone();
// If original page was under the clone root, we make it appear to be under the entry root instead
if (originalPage.ParentLink.CompareToIgnoreWorkID(CloneRoot))
{
clone.ParentLink = EntryRoot;
}
// All pages but the entry root should appear to come from this content provider
if (!clone.PageLink.CompareToIgnoreWorkID(EntryRoot))
{
clone.ContentLink.ProviderName = ProviderKey;
}
// Unless the parent is the entry root, it should appear to come from this content provider
if (!clone.ParentLink.CompareToIgnoreWorkID(EntryRoot))
{
var parentLinkClone = clone.ParentLink.CreateWritableClone();
parentLinkClone.ProviderName = ProviderKey;
clone.ParentLink = parentLinkClone;
}
// This is integral to map the cloned page to this content provider
clone.LinkURL = ConstructContentUri(originalPage.PageTypeID, clone.ContentLink, clone.ContentGuid).ToString();
return clone;
}
/// <summary>
/// Filters out content references to content that does not match current category filters, if any
/// </summary>
/// <param name="contentReferences"></param>
/// <returns></returns>
private IList<T> FilterByCategory<T>(IEnumerable<T> contentReferences)
{
if (Category == null || !Category.Any())
{
return contentReferences.ToList();
}
// Filter by category if a category filter has been set
var filteredChildren = new List<T>();
foreach (var contentReference in contentReferences)
{
ICategorizable content = null;
if (contentReference is ContentReference)
{
content = (contentReference as ContentReference).Get<IContent>() as ICategorizable;
} else if (typeof(T) == typeof(GetChildrenReferenceResult))
{
content = (contentReference as GetChildrenReferenceResult).ContentLink.Get<IContent>() as ICategorizable;
}
if (content != null)
{
var atLeastOneMatchingCategory = content.Category.Any(c => Category.Contains(c));
if (atLeastOneMatchingCategory)
{
filteredChildren.Add(contentReference);
}
}
else // Non-categorizable content will also be included
{
filteredChildren.Add(contentReference);
}
}
return filteredChildren;
}
protected override IContent LoadContent(ContentReference contentLink, ILanguageSelector languageSelector)
{
if (ContentReference.IsNullOrEmpty(contentLink) || contentLink.ID == 0)
{
throw new ArgumentNullException("contentLink");
}
if (contentLink.WorkID > 0)
{
return ContentStore.LoadVersion(contentLink, -1);
}
var languageBranchRepository = ServiceLocator.Current.GetInstance<ILanguageBranchRepository>();
LanguageBranch langBr = null;
if (languageSelector.Language != null)
{
langBr = languageBranchRepository.Load(languageSelector.Language);
}
if (contentLink.GetPublishedOrLatest)
{
return ContentStore.LoadVersion(contentLink, langBr != null ? langBr.ID : -1);
}
// Get published version of Content
var originalContent = ContentStore.Load(contentLink, langBr != null ? langBr.ID : -1);
var page = originalContent as PageData;
if (page == null)
{
throw new NotSupportedException("Only cloning of pages is supported");
}
return ClonePage(page);
}
protected override ContentResolveResult ResolveContent(ContentReference contentLink)
{
var contentData = ContentCoreDataLoader.Service.Load(contentLink.ID);
// All pages but the entry root should appear to come from this content provider
if (!contentLink.CompareToIgnoreWorkID(EntryRoot))
{
contentData.ContentReference.ProviderName = ProviderKey;
}
var result = CreateContentResolveResult(contentData);
if (!result.ContentLink.CompareToIgnoreWorkID(EntryRoot))
{
result.ContentLink.ProviderName = ProviderKey;
}
return result;
}
protected override Uri ConstructContentUri(int contentTypeId, ContentReference contentLink, Guid contentGuid)
{
if (!contentLink.CompareToIgnoreWorkID(EntryRoot))
{
contentLink.ProviderName = ProviderKey;
}
return base.ConstructContentUri(contentTypeId, contentLink, contentGuid);
}
protected override IList<GetChildrenReferenceResult> LoadChildrenReferencesAndTypes(ContentReference contentLink, string languageID, out bool languageSpecific)
{
// If retrieving children for the entry point, we retrieve pages from the clone root
contentLink = contentLink.CompareToIgnoreWorkID(EntryRoot) ? CloneRoot : contentLink;
FilterSortOrder sortOrder;
var children = ContentStore.LoadChildrenReferencesAndTypes(contentLink.ID, languageID, out sortOrder);
languageSpecific = sortOrder == FilterSortOrder.Alphabetical;
foreach (var contentReference in children.Where(contentReference => !contentReference.ContentLink.CompareToIgnoreWorkID(EntryRoot)))
{
contentReference.ContentLink.ProviderName = ProviderKey;
}
return FilterByCategory <GetChildrenReferenceResult>(children);
}
protected override IEnumerable<IContent> LoadContents(IList<ContentReference> contentReferences, ILanguageSelector selector)
{
return contentReferences
.Select(contentReference => ClonePage(ContentLoader.Get<PageData>(contentReference.ToReferenceWithoutVersion())))
.Cast<IContent>()
.ToList();
}
protected override void SetCacheSettings(IContent content, CacheSettings cacheSettings)
{
// Make the cache of this content provider depend on the original content
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(content.ContentLink.ID)));
}
protected override void SetCacheSettings(ContentReference contentReference, IEnumerable<GetChildrenReferenceResult> children, CacheSettings cacheSettings)
{
// Make the cache of this content provider depend on the original content
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(contentReference.ID)));
foreach (var child in children)
{
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(child.ContentLink.ID)));
}
}
public override IList<ContentReference> GetDescendentReferences(ContentReference contentLink)
{
// If retrieving children for the entry point, we retrieve pages from the clone root
contentLink = contentLink.CompareToIgnoreWorkID(EntryRoot) ? CloneRoot : contentLink;
var descendents = ContentStore.ListAll(contentLink);
foreach (var contentReference in descendents.Where(contentReference => !contentReference.CompareToIgnoreWorkID(EntryRoot)))
{
contentReference.ProviderName = ProviderKey;
}
return FilterByCategory<ContentReference>(descendents);
}
public PageDataCollection FindAllPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
{
// Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
if (pageLink.CompareToIgnoreWorkID(EntryRoot))
{
pageLink = CloneRoot;
}
else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
{
pageLink = new PageReference(pageLink.ID);
}
var pages = PageQueryService.FindAllPagesWithCriteria(pageLink, criterias, languageBranch, selector);
// Return cloned search result set
return new PageDataCollection(pages.Select(ClonePage));
}
public PageDataCollection FindPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
{
// Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
if (pageLink.CompareToIgnoreWorkID(EntryRoot))
{
pageLink = CloneRoot;
}
else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
{
pageLink = new PageReference(pageLink.ID);
}
var pages = PageQueryService.FindPagesWithCriteria(pageLink, criterias, languageBranch, selector);
// Return cloned search result set
return new PageDataCollection(pages.Select(ClonePage));
}
/// <summary>
/// Gets the content store used to get original content
/// </summary>
protected virtual ContentStore ContentStore
{
get { return ServiceLocator.Current.GetInstance<ContentStore>(); }
}
/// <summary>
/// Gets the content loader used to get content
/// </summary>
protected virtual IContentLoader ContentLoader
{
get { return ServiceLocator.Current.GetInstance<IContentLoader>(); }
}
/// <summary>
/// Gets the service used to query for pages using criterias
/// </summary>
protected virtual IPageCriteriaQueryService PageQueryService
{
get { return ServiceLocator.Current.GetInstance<IPageCriteriaQueryService>(); }
}
/// <summary>
/// Content that should be cloned at the entry point
/// </summary>
public PageReference CloneRoot { get; protected set; }
/// <summary>
/// Gets the page where the cloned content will appear
/// </summary>
public PageReference EntryRoot { get; protected set; }
/// <summary>
/// Gets the category filters used for this content provider
/// </summary>
/// <remarks>If set, pages not matching at least one of these categories will be excluded from this content provider</remarks>
public CategoryList Category { get; protected set; }
/// <summary>
/// Gets a unique key for this content provider instance
/// </summary>
public override string ProviderKey
{
get
{
return string.Format("ClonedContent-{0}-{1}", CloneRoot.ID, EntryRoot.ID);
}
}
/// <summary>
/// Gets capabilities indicating no content editing can be performed through this provider
/// </summary>
public override ContentProviderCapabilities ProviderCapabilities { get { return ContentProviderCapabilities.Search; } }
/// <summary>
/// Gets configuration parameters for this content provider instance
/// </summary>
public override NameValueCollection Parameters { get { return _parameters; } }
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using NLog.Common;
using NLog.Internal;
using NLog.Layouts;
using NLog.MessageTemplates;
using NLog.Time;
/// <summary>
/// Represents the logging event.
/// </summary>
public class LogEventInfo
{
/// <summary>
/// Gets the date of the first log event created.
/// </summary>
public static readonly DateTime ZeroDate = DateTime.UtcNow;
internal static readonly LogMessageFormatter StringFormatMessageFormatter = GetStringFormatMessageFormatter;
internal static LogMessageFormatter DefaultMessageFormatter { get; private set; } = LogMessageTemplateFormatter.DefaultAuto.MessageFormatter;
private static int globalSequenceId;
/// <summary>
/// The formatted log message.
/// </summary>
private string _formattedMessage;
/// <summary>
/// The log message including any parameter placeholders
/// </summary>
private string _message;
private object[] _parameters;
private IFormatProvider _formatProvider;
private LogMessageFormatter _messageFormatter = DefaultMessageFormatter;
private IDictionary<Layout, object> _layoutCache;
private PropertiesDictionary _properties;
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
public LogEventInfo()
{
TimeStamp = TimeSource.Current.Time;
SequenceID = Interlocked.Increment(ref globalSequenceId);
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="message">Log message including parameter placeholders.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message)
: this(level, loggerName, null, message, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="messageTemplateParameters">Log message including parameter placeholders.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IList<MessageTemplateParameter> messageTemplateParameters)
: this(level, loggerName, null, message, null, null)
{
if (messageTemplateParameters != null && messageTemplateParameters.Count > 0)
{
_properties = new PropertiesDictionary(messageTemplateParameters);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
: this(level, loggerName, formatProvider, message, parameters, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
/// <param name="exception">Exception information.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception): this()
{
Level = level;
LoggerName = loggerName;
Message = message;
Parameters = parameters;
FormatProvider = formatProvider;
Exception = exception;
if (NeedToPreformatMessage(parameters))
{
CalcFormattedMessage();
}
}
/// <summary>
/// Gets the unique identifier of log event which is automatically generated
/// and monotonously increasing.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID", Justification = "Backwards compatibility")]
// ReSharper disable once InconsistentNaming
public int SequenceID { get; private set; }
/// <summary>
/// Gets or sets the timestamp of the logging event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp", Justification = "Backwards compatibility.")]
public DateTime TimeStamp { get; set; }
/// <summary>
/// Gets or sets the level of the logging event.
/// </summary>
public LogLevel Level { get; set; }
internal CallSiteInformation CallSiteInformation { get; private set; }
internal CallSiteInformation GetCallSiteInformationInternal() { return CallSiteInformation ?? (CallSiteInformation = new CallSiteInformation()); }
/// <summary>
/// Gets a value indicating whether stack trace has been set for this event.
/// </summary>
public bool HasStackTrace => CallSiteInformation?.StackTrace != null;
/// <summary>
/// Gets the stack frame of the method that did the logging.
/// </summary>
public StackFrame UserStackFrame => CallSiteInformation?.UserStackFrame;
/// <summary>
/// Gets the number index of the stack frame that represents the user
/// code (not the NLog code).
/// </summary>
public int UserStackFrameNumber => CallSiteInformation?.UserStackFrameNumberLegacy ?? CallSiteInformation?.UserStackFrameNumber ?? 0;
/// <summary>
/// Gets the entire stack trace.
/// </summary>
public StackTrace StackTrace => CallSiteInformation?.StackTrace;
/// <summary>
/// Gets the callsite class name
/// </summary>
public string CallerClassName => CallSiteInformation?.GetCallerClassName(null, true, true, true);
/// <summary>
/// Gets the callsite member function name
/// </summary>
public string CallerMemberName => CallSiteInformation?.GetCallerMemberName(null, false, true, true);
/// <summary>
/// Gets the callsite source file path
/// </summary>
public string CallerFilePath => CallSiteInformation?.GetCallerFilePath(0);
/// <summary>
/// Gets the callsite source file line number
/// </summary>
public int CallerLineNumber => CallSiteInformation?.GetCallerLineNumber(0) ?? 0;
/// <summary>
/// Gets or sets the exception information.
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Gets or sets the logger name.
/// </summary>
public string LoggerName { get; set; }
/// <summary>
/// Gets the logger short name.
/// </summary>
/// <remarks>This property was marked as obsolete on NLog 2.0 and it may be removed in a future release.</remarks>
[Obsolete("This property should not be used. Marked obsolete on NLog 2.0")]
public string LoggerShortName
{
// NOTE: This property is not referenced by NLog code anymore.
get
{
int lastDot = LoggerName.LastIndexOf('.');
if (lastDot >= 0)
{
return LoggerName.Substring(lastDot + 1);
}
return LoggerName;
}
}
/// <summary>
/// Gets or sets the log message including any parameter placeholders.
/// </summary>
public string Message
{
get => _message;
set
{
bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters();
_message = value;
ResetFormattedMessage(rebuildMessageTemplateParameters);
}
}
/// <summary>
/// Gets or sets the parameter values or null if no parameters have been specified.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "For backwards compatibility.")]
public object[] Parameters
{
get => _parameters;
set
{
bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters();
_parameters = value;
ResetFormattedMessage(rebuildMessageTemplateParameters);
}
}
/// <summary>
/// Gets or sets the format provider that was provided while logging or <see langword="null" />
/// when no formatProvider was specified.
/// </summary>
public IFormatProvider FormatProvider
{
get => _formatProvider;
set
{
if (_formatProvider != value)
{
_formatProvider = value;
ResetFormattedMessage(false);
}
}
}
/// <summary>
/// Gets or sets the message formatter for generating <see cref="LogEventInfo.FormattedMessage"/>
/// Uses string.Format(...) when nothing else has been configured.
/// </summary>
public LogMessageFormatter MessageFormatter
{
get => _messageFormatter;
set
{
_messageFormatter = value ?? StringFormatMessageFormatter;
ResetFormattedMessage(false);
}
}
/// <summary>
/// Gets the formatted message.
/// </summary>
public string FormattedMessage
{
get
{
if (_formattedMessage == null)
{
CalcFormattedMessage();
}
return _formattedMessage;
}
}
/// <summary>
/// Checks if any per-event properties (Without allocation)
/// </summary>
public bool HasProperties
{
get
{
if (_properties != null)
{
return _properties.Count > 0;
}
else
{
return CreateOrUpdatePropertiesInternal(false)?.Count > 0;
}
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
public IDictionary<object, object> Properties => CreateOrUpdatePropertiesInternal();
/// <summary>
/// Gets the dictionary of per-event context properties.
/// Internal helper for the PropertiesDictionary type.
/// </summary>
/// <param name="forceCreate">Create the event-properties dictionary, even if no initial template parameters</param>
/// <param name="templateParameters">Provided when having parsed the message template and capture template parameters (else null)</param>
/// <returns></returns>
internal PropertiesDictionary CreateOrUpdatePropertiesInternal(bool forceCreate = true, IList<MessageTemplateParameter> templateParameters = null)
{
var properties = _properties;
if (properties == null)
{
if (forceCreate || templateParameters?.Count > 0 || (templateParameters == null && HasMessageTemplateParameters))
{
properties = new PropertiesDictionary(templateParameters);
Interlocked.CompareExchange(ref _properties, properties, null);
if (templateParameters == null && (!forceCreate || HasMessageTemplateParameters))
{
// Trigger capture of MessageTemplateParameters from logevent-message
CalcFormattedMessage();
}
}
}
else if (templateParameters != null)
{
properties.MessageProperties = templateParameters;
}
return _properties;
}
internal bool HasMessageTemplateParameters
{
get
{
// Have not yet parsed/rendered the FormattedMessage, so check with ILogMessageFormatter
if (_formattedMessage == null)
{
var logMessageFormatter = _messageFormatter?.Target as ILogMessageFormatter;
return logMessageFormatter?.HasProperties(this) ?? false;
}
return false;
}
}
/// <summary>
/// Gets the named parameters extracted from parsing <see cref="Message"/> as MessageTemplate
/// </summary>
public MessageTemplateParameters MessageTemplateParameters
{
get
{
if (_properties != null && _properties.MessageProperties.Count > 0)
{
return new MessageTemplateParameters(_properties.MessageProperties, _message, _parameters);
}
else
{
return new MessageTemplateParameters(_message, _parameters);
}
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
/// <remarks>This property was marked as obsolete on NLog 2.0 and it may be removed in a future release.</remarks>
[Obsolete("Use LogEventInfo.Properties instead. Marked obsolete on NLog 2.0", true)]
public IDictionary Context => CreateOrUpdatePropertiesInternal().EventContext;
/// <summary>
/// Creates the null event.
/// </summary>
/// <returns>Null log event.</returns>
public static LogEventInfo CreateNullEvent()
{
return new LogEventInfo(LogLevel.Off, string.Empty, string.Empty);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message)
{
return new LogEventInfo(logLevel, loggerName, null, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message)
{
Exception exception = message as Exception;
if (exception == null && message is LogEventInfo logEvent)
{
logEvent.LoggerName = loggerName;
logEvent.Level = logLevel;
logEvent.FormatProvider = formatProvider ?? logEvent.FormatProvider;
return logEvent;
}
return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new[] { message }, exception);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
/// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("use Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, string message) instead. Marked obsolete before v4.3.11")]
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message, Exception exception)
{
return new LogEventInfo(logLevel, loggerName, null, message, null, exception);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message)
{
return Create(logLevel, loggerName, exception, formatProvider, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName,formatProvider, message, parameters, exception);
}
/// <summary>
/// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns>
public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation)
{
return new AsyncLogEventInfo(this, asyncContinuation);
}
/// <summary>
/// Returns a string representation of this log event.
/// </summary>
/// <returns>String representation of the log event.</returns>
public override string ToString()
{
return $"Log Event: Logger='{LoggerName}' Level={Level} Message='{FormattedMessage}' SequenceID={SequenceID}";
}
/// <summary>
/// Sets the stack trace for the event info.
/// </summary>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param>
public void SetStackTrace(StackTrace stackTrace, int userStackFrame)
{
GetCallSiteInformationInternal().SetStackTrace(stackTrace, userStackFrame, null);
}
/// <summary>
/// Sets the details retrieved from the Caller Information Attributes
/// </summary>
/// <param name="callerClassName"></param>
/// <param name="callerMemberName"></param>
/// <param name="callerFilePath"></param>
/// <param name="callerLineNumber"></param>
public void SetCallerInfo(string callerClassName, string callerMemberName, string callerFilePath, int callerLineNumber)
{
GetCallSiteInformationInternal().SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber);
}
internal void AddCachedLayoutValue(Layout layout, object value)
{
if (_layoutCache == null)
{
Interlocked.CompareExchange(ref _layoutCache, new Dictionary<Layout, object>(), null);
}
lock (_layoutCache)
{
_layoutCache[layout] = value;
}
}
internal bool TryGetCachedLayoutValue(Layout layout, out object value)
{
if (_layoutCache == null)
{
// We don't need lock to see if dictionary has been created
value = null;
return false;
}
lock (_layoutCache)
{
if (_layoutCache.Count == 0)
{
value = null;
return false;
}
return _layoutCache.TryGetValue(layout, out value);
}
}
private static bool NeedToPreformatMessage(object[] parameters)
{
// we need to preformat message if it contains any parameters which could possibly
// do logging in their ToString()
if (parameters == null || parameters.Length == 0)
{
return false;
}
if (parameters.Length > 5)
{
// too many parameters, too costly to check
return true;
}
for (int i = 0; i < parameters.Length; ++i)
{
if (!IsSafeToDeferFormatting(parameters[i]))
return true;
}
return false;
}
private static bool IsSafeToDeferFormatting(object value)
{
return Convert.GetTypeCode(value) != TypeCode.Object;
}
internal bool IsLogEventMutableSafe()
{
if (Exception != null || _formattedMessage != null)
return false;
var properties = CreateOrUpdatePropertiesInternal(false);
if (properties == null || properties.Count == 0)
return true; // No mutable state, no need to precalculate
if (properties.Count > 5)
return false; // too many properties, too costly to check
if (properties.Count == _parameters?.Length && properties.Count == properties.MessageProperties.Count)
return true; // Already checked formatted message, no need to do it twice
return HasImmutableProperties(properties);
}
private static bool HasImmutableProperties(PropertiesDictionary properties)
{
if (properties.Count == properties.MessageProperties.Count)
{
// Skip enumerator allocation when all properties comes from the message-template
for (int i = 0; i < properties.MessageProperties.Count; ++i)
{
var property = properties.MessageProperties[i];
if (!IsSafeToDeferFormatting(property.Value))
return false;
}
}
else
{
// Already spent the time on allocating a Dictionary, also have time for an enumerator
foreach (var property in properties)
{
if (!IsSafeToDeferFormatting(property.Value))
return false;
}
}
return true;
}
internal bool CanLogEventDeferMessageFormat()
{
if (_formattedMessage != null)
return false; // Already formatted, cannot be deferred
if (_parameters == null || _parameters.Length == 0)
return false; // No parameters to format
if (_message?.Length < 256 && ReferenceEquals(MessageFormatter, LogMessageTemplateFormatter.DefaultAuto.MessageFormatter))
return true; // Not too expensive to scan for properties
else
return false;
}
private static string GetStringFormatMessageFormatter(LogEventInfo logEvent)
{
if (logEvent.Parameters == null || logEvent.Parameters.Length == 0)
{
return logEvent.Message;
}
else
{
return string.Format(logEvent.FormatProvider ?? CultureInfo.CurrentCulture, logEvent.Message, logEvent.Parameters);
}
}
private void CalcFormattedMessage()
{
try
{
_formattedMessage = _messageFormatter(this);
}
catch (Exception exception)
{
_formattedMessage = Message;
InternalLogger.Warn(exception, "Error when formatting a message.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
internal void AppendFormattedMessage(ILogMessageFormatter messageFormatter, System.Text.StringBuilder builder)
{
if (_formattedMessage != null)
{
builder.Append(_formattedMessage);
}
else
{
int originalLength = builder.Length;
try
{
messageFormatter.AppendFormattedMessage(this, builder);
}
catch (Exception ex)
{
builder.Length = originalLength;
builder.Append(_message ?? string.Empty);
InternalLogger.Warn(ex, "Error when formatting a message.");
if (ex.MustBeRethrown())
{
throw;
}
}
}
}
private void ResetFormattedMessage(bool rebuildMessageTemplateParameters)
{
_formattedMessage = null;
if (rebuildMessageTemplateParameters && HasMessageTemplateParameters)
{
CalcFormattedMessage();
}
}
private bool ResetMessageTemplateParameters()
{
if (_properties != null && HasMessageTemplateParameters)
{
_properties.MessageProperties = null;
return true;
}
return false;
}
/// <summary>
/// Set the <see cref="DefaultMessageFormatter"/>
/// </summary>
/// <param name="mode">true = Always, false = Never, null = Auto Detect</param>
internal static void SetDefaultMessageFormatter(bool? mode)
{
if (mode == true)
{
InternalLogger.Info("Message Template Format always enabled");
DefaultMessageFormatter = LogMessageTemplateFormatter.Default.MessageFormatter;
}
else if (mode == false)
{
InternalLogger.Info("Message Template String Format always enabled");
DefaultMessageFormatter = StringFormatMessageFormatter;
}
else
{
//null = auto
InternalLogger.Info("Message Template Auto Format enabled");
DefaultMessageFormatter = LogMessageTemplateFormatter.DefaultAuto.MessageFormatter;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Streams;
using Orleans.TestingHost.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
namespace Orleans.TestingHost
{
/// <summary>
/// A host class for local testing with Orleans using in-process silos.
/// Runs a Primary and optionally secondary silos in separate app domains, and client in the main app domain.
/// Additional silos can also be started in-process on demand if required for particular test cases.
/// </summary>
/// <remarks>
/// Make sure that your test project references your test grains and test grain interfaces
/// projects, and has CopyLocal=True set on those references [which should be the default].
/// </remarks>
public class TestCluster
{
private readonly List<SiloHandle> additionalSilos = new List<SiloHandle>();
private readonly TestClusterOptions options;
private readonly StringBuilder log = new StringBuilder();
private int startedInstances;
/// <summary>
/// Primary silo handle, if applicable.
/// </summary>
/// <remarks>This handle is valid only when using Grain-based membership.</remarks>
public SiloHandle Primary { get; private set; }
/// <summary>
/// List of handles to the secondary silos.
/// </summary>
public IReadOnlyList<SiloHandle> SecondarySilos => this.additionalSilos;
/// <summary>
/// Collection of all known silos.
/// </summary>
public ReadOnlyCollection<SiloHandle> Silos
{
get
{
var result = new List<SiloHandle>();
if (this.Primary != null)
{
result.Add(this.Primary);
}
result.AddRange(this.additionalSilos);
return result.AsReadOnly();
}
}
/// <summary>
/// Options used to configure the test cluster.
/// </summary>
/// <remarks>This is the options you configured your test cluster with, or the default one.
/// If the cluster is being configured via ClusterConfiguration, then this object may not reflect the true settings.
/// </remarks>
public TestClusterOptions Options => this.options;
/// <summary>
/// The internal client interface.
/// </summary>
internal IInternalClusterClient InternalClient { get; private set; }
/// <summary>
/// The client.
/// </summary>
public IClusterClient Client => this.InternalClient;
/// <summary>
/// GrainFactory to use in the tests
/// </summary>
public IGrainFactory GrainFactory => this.Client;
/// <summary>
/// GrainFactory to use in the tests
/// </summary>
internal IInternalGrainFactory InternalGrainFactory => this.InternalClient;
/// <summary>
/// Client-side <see cref="IServiceProvider"/> to use in the tests.
/// </summary>
public IServiceProvider ServiceProvider => this.Client.ServiceProvider;
/// <summary>
/// SerializationManager to use in the tests
/// </summary>
public SerializationManager SerializationManager { get; private set; }
/// <summary>
/// Configures the test cluster plus client in-process.
/// </summary>
public TestCluster(TestClusterOptions options, IReadOnlyList<IConfigurationSource> configurationSources)
{
this.options = options;
this.ConfigurationSources = configurationSources.ToArray();
}
/// <summary>
/// Deploys the cluster using the specified configuration and starts the client in-process.
/// It will start the number of silos defined in <see cref="TestClusterOptions.InitialSilosCount"/>.
/// </summary>
public void Deploy()
{
this.DeployAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Deploys the cluster using the specified configuration and starts the client in-process.
/// </summary>
public async Task DeployAsync()
{
if (this.Primary != null || this.additionalSilos.Count > 0) throw new InvalidOperationException("Cluster host already deployed.");
AppDomain.CurrentDomain.UnhandledException += ReportUnobservedException;
try
{
string startMsg = "----------------------------- STARTING NEW UNIT TEST SILO HOST: " + GetType().FullName + " -------------------------------------";
WriteLog(startMsg);
await InitializeAsync();
}
catch (TimeoutException te)
{
FlushLogToConsole();
throw new TimeoutException("Timeout during test initialization", te);
}
catch (Exception ex)
{
StopAllSilos();
Exception baseExc = ex.GetBaseException();
FlushLogToConsole();
if (baseExc is TimeoutException)
{
throw new TimeoutException("Timeout during test initialization", ex);
}
// IMPORTANT:
// Do NOT re-throw the original exception here, also not as an internal exception inside AggregateException
// Due to the way MS tests works, if the original exception is an Orleans exception,
// it's assembly might not be loaded yet in this phase of the test.
// As a result, we will get "MSTest: Unit Test Adapter threw exception: Type is not resolved for member XXX"
// and will loose the original exception. This makes debugging tests super hard!
// The root cause has to do with us initializing our tests from Test constructor and not from TestInitialize method.
// More details: http://dobrzanski.net/2010/09/20/mstest-unit-test-adapter-threw-exception-type-is-not-resolved-for-member/
//throw new Exception(
// string.Format("Exception during test initialization: {0}",
// LogFormatter.PrintException(baseExc)));
throw;
}
}
/// <summary>
/// Get the list of current active silos.
/// </summary>
/// <returns>List of current silos.</returns>
public IEnumerable<SiloHandle> GetActiveSilos()
{
WriteLog("GetActiveSilos: Primary={0} + {1} Additional={2}",
Primary, additionalSilos.Count, Runtime.Utils.EnumerableToString(additionalSilos));
if (Primary?.IsActive == true) yield return Primary;
if (additionalSilos.Count > 0)
foreach (var s in additionalSilos)
if (s?.IsActive == true)
yield return s;
}
/// <summary>
/// Find the silo handle for the specified silo address.
/// </summary>
/// <param name="siloAddress">Silo address to be found.</param>
/// <returns>SiloHandle of the appropriate silo, or <c>null</c> if not found.</returns>
public SiloHandle GetSiloForAddress(SiloAddress siloAddress)
{
var activeSilos = GetActiveSilos().ToList();
var ret = activeSilos.FirstOrDefault(s => s.SiloAddress.Equals(siloAddress));
return ret;
}
/// <summary>
/// Wait for the silo liveness sub-system to detect and act on any recent cluster membership changes.
/// </summary>
/// <param name="didKill">Whether recent membership changes we done by graceful Stop.</param>
public async Task WaitForLivenessToStabilizeAsync(bool didKill = false)
{
// TODO: read from the cluster
var globalConfiguration = new GlobalConfiguration(); //this.ClusterConfiguration.Globals
TimeSpan stabilizationTime = GetLivenessStabilizationTime(globalConfiguration, didKill);
WriteLog(Environment.NewLine + Environment.NewLine + "WaitForLivenessToStabilize is about to sleep for {0}", stabilizationTime);
await Task.Delay(stabilizationTime);
WriteLog("WaitForLivenessToStabilize is done sleeping");
}
/// <summary>
/// Get the timeout value to use to wait for the silo liveness sub-system to detect and act on any recent cluster membership changes.
/// <seealso cref="WaitForLivenessToStabilizeAsync"/>
/// </summary>
public static TimeSpan GetLivenessStabilizationTime(GlobalConfiguration global, bool didKill = false)
{
TimeSpan stabilizationTime = TimeSpan.Zero;
if (didKill)
{
// in case of hard kill (kill and not Stop), we should give silos time to detect failures first.
stabilizationTime = TestingUtils.Multiply(global.ProbeTimeout, global.NumMissedProbesLimit);
}
if (global.UseLivenessGossip)
{
stabilizationTime += TimeSpan.FromSeconds(5);
}
else
{
stabilizationTime += TestingUtils.Multiply(global.TableRefreshTimeout, 2);
}
return stabilizationTime;
}
/// <summary>
/// Start an additional silo, so that it joins the existing cluster.
/// </summary>
/// <returns>SiloHandle for the newly started silo.</returns>
public SiloHandle StartAdditionalSilo(bool startAdditionalSiloOnNewPort = false)
{
return this.StartAdditionalSilos(1, startAdditionalSiloOnNewPort).GetAwaiter().GetResult().Single();
}
/// <summary>
/// Start a number of additional silo, so that they join the existing cluster.
/// </summary>
/// <param name="silosToStart">Number of silos to start.</param>
/// <returns>List of SiloHandles for the newly started silos.</returns>
public async Task<List<SiloHandle>> StartAdditionalSilos(int silosToStart, bool startAdditionalSiloOnNewPort = false)
{
var instances = new List<SiloHandle>();
if (silosToStart > 0)
{
var siloStartTasks = Enumerable.Range(this.startedInstances, silosToStart)
.Select(instanceNumber => Task.Run(() => StartOrleansSilo((short)instanceNumber, this.options, startAdditionalSiloOnNewPort))).ToArray();
try
{
await Task.WhenAll(siloStartTasks);
}
catch (Exception)
{
this.additionalSilos.AddRange(siloStartTasks.Where(t => t.Exception == null).Select(t => t.Result));
throw;
}
instances.AddRange(siloStartTasks.Select(t => t.Result));
this.additionalSilos.AddRange(instances);
}
return instances;
}
/// <summary>
/// Stop any additional silos, not including the default Primary silo.
/// </summary>
public void StopSecondarySilos()
{
foreach (var instance in this.additionalSilos.ToList())
{
StopSilo(instance);
}
}
/// <summary>
/// Stops the default Primary silo.
/// </summary>
public void StopPrimarySilo()
{
if (Primary == null) throw new InvalidOperationException("There is no primary silo");
StopClusterClient();
StopSilo(Primary);
}
private void StopClusterClient()
{
try
{
this.InternalClient?.Close().GetAwaiter().GetResult();
}
catch (Exception exc)
{
WriteLog("Exception Uninitializing grain client: {0}", exc);
}
finally
{
this.InternalClient?.Dispose();
this.InternalClient = null;
}
}
/// <summary>
/// Stop all current silos.
/// </summary>
public void StopAllSilos()
{
StopClusterClient();
StopSecondarySilos();
if (Primary != null)
{
StopPrimarySilo();
}
AppDomain.CurrentDomain.UnhandledException -= ReportUnobservedException;
}
/// <summary>
/// Do a semi-graceful Stop of the specified silo.
/// </summary>
/// <param name="instance">Silo to be stopped.</param>
public void StopSilo(SiloHandle instance)
{
if (instance != null)
{
StopOrleansSilo(instance, true);
if (Primary == instance)
{
Primary = null;
}
else
{
additionalSilos.Remove(instance);
}
}
}
/// <summary>
/// Do an immediate Kill of the specified silo.
/// </summary>
/// <param name="instance">Silo to be killed.</param>
public void KillSilo(SiloHandle instance)
{
if (instance != null)
{
// do NOT stop, just kill directly, to simulate crash.
StopOrleansSilo(instance, false);
}
}
/// <summary>
/// Performs a hard kill on client. Client will not cleanup resources.
/// </summary>
public void KillClient()
{
this.InternalClient?.Abort();
this.InternalClient = null;
}
/// <summary>
/// Do a Stop or Kill of the specified silo, followed by a restart.
/// </summary>
/// <param name="instance">Silo to be restarted.</param>
public SiloHandle RestartSilo(SiloHandle instance)
{
if (instance != null)
{
var instanceNumber = instance.InstanceNumber;
var siloName = instance.Name;
StopSilo(instance);
var newInstance = StartOrleansSilo(instanceNumber, this.options);
if (siloName == Silo.PrimarySiloName)
{
Primary = newInstance;
}
else
{
additionalSilos.Add(newInstance);
}
return newInstance;
}
return null;
}
/// <summary>
/// Restart a previously stopped.
/// </summary>
/// <param name="siloName">Silo to be restarted.</param>
public SiloHandle RestartStoppedSecondarySilo(string siloName)
{
if (siloName == null) throw new ArgumentNullException(nameof(siloName));
var siloHandle = this.Silos.Single(s => s.Name.Equals(siloName, StringComparison.Ordinal));
var newInstance = StartOrleansSilo(this, this.Silos.IndexOf(siloHandle), this.options);
additionalSilos.Add(newInstance);
return newInstance;
}
#region Private methods
/// <summary>
/// Initialize the grain client. This should be already done by <see cref="Deploy()"/> or <see cref="DeployAsync"/>
/// </summary>
public void InitializeClient()
{
WriteLog("Initializing Cluster Client");
this.InternalClient = (IInternalClusterClient)TestClusterHostFactory.CreateClusterClient("MainClient", this.ConfigurationSources);
this.InternalClient.Connect().GetAwaiter().GetResult();
this.SerializationManager = this.ServiceProvider.GetRequiredService<SerializationManager>();
}
public IReadOnlyList<IConfigurationSource> ConfigurationSources { get; }
private async Task InitializeAsync()
{
short silosToStart = this.options.InitialSilosCount;
if (this.options.UseTestClusterMembership)
{
this.Primary = StartOrleansSilo(this.startedInstances, this.options);
silosToStart--;
}
if (silosToStart > 0)
{
await this.StartAdditionalSilos(silosToStart);
}
WriteLog("Done initializing cluster");
if (this.options.InitializeClientOnDeploy)
{
InitializeClient();
}
}
private SiloHandle StartOrleansSilo(int instanceNumber, TestClusterOptions clusterOptions, bool startSiloOnNewPort = false)
{
return StartOrleansSilo(this, instanceNumber, clusterOptions, null, startSiloOnNewPort);
}
/// <summary>
/// Start a new silo in the target cluster
/// </summary>
/// <param name="cluster">The TestCluster in which the silo should be deployed</param>
/// <param name="instanceNumber">The instance number to deploy</param>
/// <param name="clusterOptions">The options to use.</param>
/// <param name="configurationOverrides">Configuration overrides.</param>
/// <param name="startSiloOnNewPort">Whether we start this silo on a new port, instead of the default one</param>
/// <returns>A handle to the silo deployed</returns>
public static SiloHandle StartOrleansSilo(TestCluster cluster, int instanceNumber, TestClusterOptions clusterOptions, IReadOnlyList<IConfigurationSource> configurationOverrides = null, bool startSiloOnNewPort = false)
{
if (cluster == null) throw new ArgumentNullException(nameof(cluster));
var configurationSources = cluster.ConfigurationSources.ToList();
// Add overrides.
if (configurationOverrides != null) configurationSources.AddRange(configurationOverrides);
var siloSpecificOptions = TestSiloSpecificOptions.Create(clusterOptions, instanceNumber, startSiloOnNewPort);
configurationSources.Add(new MemoryConfigurationSource
{
InitialData = siloSpecificOptions.ToDictionary()
});
var handle = cluster.LoadSiloInNewAppDomain(
siloSpecificOptions.SiloName,
configurationSources);
handle.InstanceNumber = (short)instanceNumber;
Interlocked.Increment(ref cluster.startedInstances);
return handle;
}
private void StopOrleansSilo(SiloHandle instance, bool stopGracefully)
{
try
{
instance.StopSilo(stopGracefully);
instance.Dispose();
}
finally
{
Interlocked.Decrement(ref this.startedInstances);
}
}
private SiloHandle LoadSiloInNewAppDomain(string siloName, IList<IConfigurationSource> configuration)
{
WriteLog("Starting a new silo in app domain {0}", siloName);
return AppDomainSiloHandle.Create(siloName, configuration);
}
#endregion
#region Tracing helper functions
public string GetLog()
{
return this.log.ToString();
}
private void ReportUnobservedException(object sender, UnhandledExceptionEventArgs eventArgs)
{
Exception exception = (Exception)eventArgs.ExceptionObject;
this.WriteLog("Unobserved exception: {0}", exception);
}
private void WriteLog(string format, params object[] args)
{
log.AppendFormat(format + Environment.NewLine, args);
}
private void FlushLogToConsole()
{
Console.WriteLine(GetLog());
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System;
using System.Reflection;
using CultureInfo = System.Globalization.CultureInfo;
using System.Collections.Generic;
using System.Diagnostics.SymbolStore;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_ConstructorBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ConstructorBuilder : ConstructorInfo, _ConstructorBuilder
{
private readonly MethodBuilder m_methodBuilder;
internal bool m_isDefaultConstructor;
#region Constructor
private ConstructorBuilder()
{
}
internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type)
{
int sigLength;
byte[] sigBytes;
MethodToken token;
m_methodBuilder = new MethodBuilder(name, attributes, callingConvention, null, null, null,
parameterTypes, requiredCustomModifiers, optionalCustomModifiers, mod, type, false);
type.m_listMethods.Add(m_methodBuilder);
sigBytes = m_methodBuilder.GetMethodSignature().InternalGetSignature(out sigLength);
token = m_methodBuilder.GetToken();
}
internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) :
this(name, attributes, callingConvention, parameterTypes, null, null, mod, type)
{
}
#endregion
#region Internal
internal override Type[] GetParameterTypes()
{
return m_methodBuilder.GetParameterTypes();
}
private TypeBuilder GetTypeBuilder()
{
return m_methodBuilder.GetTypeBuilder();
}
internal ModuleBuilder GetModuleBuilder()
{
return GetTypeBuilder().GetModuleBuilder();
}
#endregion
#region Object Overrides
public override String ToString()
{
return m_methodBuilder.ToString();
}
#endregion
#region MemberInfo Overrides
internal int MetadataTokenInternal
{
get { return m_methodBuilder.MetadataTokenInternal; }
}
public override Module Module
{
get { return m_methodBuilder.Module; }
}
public override Type ReflectedType
{
get { return m_methodBuilder.ReflectedType; }
}
public override Type DeclaringType
{
get { return m_methodBuilder.DeclaringType; }
}
public override String Name
{
get { return m_methodBuilder.Name; }
}
#endregion
#region MethodBase Overrides
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
[Pure]
public override ParameterInfo[] GetParameters()
{
ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes);
return rci.GetParameters();
}
public override MethodAttributes Attributes
{
get { return m_methodBuilder.Attributes; }
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return m_methodBuilder.GetMethodImplementationFlags();
}
public override RuntimeMethodHandle MethodHandle
{
get { return m_methodBuilder.MethodHandle; }
}
#endregion
#region ConstructorInfo Overrides
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
return m_methodBuilder.GetCustomAttributes(inherit);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return m_methodBuilder.GetCustomAttributes(attributeType, inherit);
}
public override bool IsDefined (Type attributeType, bool inherit)
{
return m_methodBuilder.IsDefined(attributeType, inherit);
}
#endregion
#region Public Members
public MethodToken GetToken()
{
return m_methodBuilder.GetToken();
}
public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, String strParamName)
{
// Theoretically we shouldn't allow iSequence to be 0 because in reflection ctors don't have
// return parameters. But we'll allow it for backward compatibility with V2. The attributes
// defined on the return parameters won't be very useful but won't do much harm either.
// MD will assert if we try to set the reserved bits explicitly
attributes = attributes & ~ParameterAttributes.ReservedMask;
return m_methodBuilder.DefineParameter(iSequence, attributes, strParamName);
}
public void SetSymCustomAttribute(String name, byte[] data)
{
m_methodBuilder.SetSymCustomAttribute(name, data);
}
public ILGenerator GetILGenerator()
{
if (m_isDefaultConstructor)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorILGen"));
return m_methodBuilder.GetILGenerator();
}
public ILGenerator GetILGenerator(int streamSize)
{
if (m_isDefaultConstructor)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorILGen"));
return m_methodBuilder.GetILGenerator(streamSize);
}
public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
{
if (m_isDefaultConstructor)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorDefineBody"));
}
m_methodBuilder.SetMethodBody(il, maxStack, localSignature, exceptionHandlers, tokenFixups);
}
public override CallingConventions CallingConvention
{
get
{
if (DeclaringType.IsGenericType)
return CallingConventions.HasThis;
return CallingConventions.Standard;
}
}
public Module GetModule()
{
return m_methodBuilder.GetModule();
}
[Obsolete("This property has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] //It always returns null.
public Type ReturnType
{
get { return GetReturnType(); }
}
// This always returns null. Is that what we want?
internal override Type GetReturnType()
{
return m_methodBuilder.ReturnType;
}
public String Signature
{
get { return m_methodBuilder.Signature; }
}
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_methodBuilder.SetCustomAttribute(con, binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
m_methodBuilder.SetCustomAttribute(customBuilder);
}
public void SetImplementationFlags(MethodImplAttributes attributes)
{
m_methodBuilder.SetImplementationFlags(attributes);
}
public bool InitLocals
{
get { return m_methodBuilder.InitLocals; }
set { m_methodBuilder.InitLocals = value; }
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.CommandLineUtils;
using Lapis.CommandLineUtils.Converters;
using Lapis.CommandLineUtils.Util;
using System.Collections.Generic;
namespace Lapis.CommandLineUtils.Models
{
public interface ICommandModelBuilder
{
CommandModel BuildCommand(TypeInfo typeInfo);
CommandModel BuildCommand(MethodInfo methodInfo);
}
public class CommandModelBuilder : ICommandModelBuilder
{
public CommandModel BuildCommand(TypeInfo typeInfo)
{
var commandModel = CreateCommandModel(typeInfo);
if (commandModel == null)
return null;
foreach (var methodInfo in typeInfo.GetMethods())
{
var subCommandModel = BuildCommand(methodInfo);
if (subCommandModel != null)
commandModel.Command(subCommandModel);
}
return commandModel;
}
public CommandModel BuildCommand(MethodInfo methodInfo)
{
var commandModel = CreateCommandModel(methodInfo);
if (commandModel == null)
return null;
foreach (var parameterInfo in methodInfo.GetParameters())
{
var argumentModel = CreateArgumentModel(parameterInfo);
if (argumentModel != null)
{
commandModel.Argument(argumentModel);
continue;
}
var optionModel = CreateOptionModel(parameterInfo);
if (optionModel != null)
{
commandModel.Option(optionModel);
continue;
}
return null;
}
return commandModel;
}
protected virtual CommandModel CreateCommandModel(TypeInfo typeInfo)
{
if (typeInfo == null)
throw new ArgumentNullException(nameof(typeInfo));
if (!IsCommand(typeInfo))
return null;
var commandModel = new CommandModel();
{
var attribute = typeInfo.GetCustomAttribute<CommandAttribute>(inherit: true);
commandModel.Name = attribute?.Name ?? GetCommandName(typeInfo.Name);
commandModel.Description = attribute?.Description ?? typeInfo.ToString();
commandModel.AllowArgumentSeparator = attribute?.AllowArgumentSeparator ?? false;
commandModel.ExtendedHelpText = attribute?.ExtendedHelpText;
commandModel.ShowInHelpText = attribute?.ShowInHelpText ?? true;
}
foreach (var attribute in typeInfo.GetCustomAttributes<ConverterAttribute>(inherit: true))
{
if (commandModel.Converters == null)
commandModel.Converters = new List<Type>();
commandModel.Converters.Add(attribute.Type);
}
foreach (var attribute in typeInfo.GetCustomAttributes<ResultHandlerAttribute>(inherit: true))
{
if (commandModel.ResultHandlers == null)
commandModel.ResultHandlers = new List<Type>();
commandModel.ResultHandlers.Add(attribute.Type);
}
foreach (var attribute in typeInfo.GetCustomAttributes<ExceptionHandlerAttribute>(inherit: true))
{
if (commandModel.ExceptionHandlers == null)
commandModel.ExceptionHandlers = new List<Type>();
commandModel.ExceptionHandlers.Add(attribute.Type);
}
{
var attribute = typeInfo.GetCustomAttribute<HelpOptionAttribute>();
if (attribute != null)
commandModel.HelpOption = new CommandModel.HelpOptionModel() { Template = attribute.Template };
else if (typeInfo.GetCustomAttribute<NoHelpOptionAttribute>() == null)
{
attribute = typeInfo.GetCustomAttribute<HelpOptionAttribute>(inherit: true);
if (attribute != null)
commandModel.HelpOption = new CommandModel.HelpOptionModel() { Template = attribute.Template };
else if (typeInfo.GetCustomAttribute<NoHelpOptionAttribute>(inherit: true) == null)
commandModel.HelpOption = new CommandModel.HelpOptionModel() { Template = GetDefaultHelpOptionTemplate() };
}
}
{
var attribute = typeInfo.GetCustomAttribute<VersionOptionAttribute>(inherit: true);
if (attribute != null)
commandModel.VersionOption = new CommandModel.VersionOptionModel()
{
Template = attribute.Template,
ShortFormVersion = attribute.ShortFormVersion,
LongFormVersion = attribute.LongFormVersion
};
}
return commandModel;
}
protected virtual CommandModel CreateCommandModel(MethodInfo methodInfo)
{
if (methodInfo == null)
throw new ArgumentNullException(nameof(methodInfo));
if (!IsCommand(methodInfo))
return null;
var commandModel = new CommandModel() { Method = methodInfo };
{
var attribute = methodInfo.GetCustomAttribute<CommandAttribute>(inherit: true);
commandModel.Name = attribute?.Name ?? GetCommandName(methodInfo.Name);
commandModel.Description = attribute?.Description ?? methodInfo.ToString();
commandModel.AllowArgumentSeparator = attribute?.AllowArgumentSeparator ?? false;
commandModel.ExtendedHelpText = attribute?.ExtendedHelpText;
commandModel.ShowInHelpText = attribute?.ShowInHelpText ?? true;
}
foreach (var attribute in methodInfo.GetCustomAttributes<ConverterAttribute>(inherit: true))
{
if (commandModel.Converters == null)
commandModel.Converters = new List<Type>();
commandModel.Converters.Add(attribute.Type);
}
foreach (var attribute in methodInfo.ReturnParameter.GetCustomAttributes<ResultHandlerAttribute>(inherit: true))
{
if (commandModel.ResultHandlers == null)
commandModel.ResultHandlers = new List<Type>();
commandModel.ResultHandlers.Add(attribute.Type);
}
{
var attribute = methodInfo.GetCustomAttribute<HelpOptionAttribute>();
if (attribute != null)
commandModel.HelpOption = new CommandModel.HelpOptionModel() { Template = attribute.Template };
else if (methodInfo.GetCustomAttribute<NoHelpOptionAttribute>() == null)
{
attribute = methodInfo.GetCustomAttribute<HelpOptionAttribute>(inherit: true);
if (attribute != null)
commandModel.HelpOption = new CommandModel.HelpOptionModel() { Template = attribute.Template };
else if (methodInfo.GetCustomAttribute<NoHelpOptionAttribute>(inherit: true) == null)
commandModel.HelpOption = new CommandModel.HelpOptionModel() { Template = GetDefaultHelpOptionTemplate() };
}
}
{
var attribute = methodInfo.GetCustomAttribute<VersionOptionAttribute>(inherit: true);
if (attribute != null)
commandModel.VersionOption = new CommandModel.VersionOptionModel()
{
Template = attribute.Template,
ShortFormVersion = attribute.ShortFormVersion,
LongFormVersion = attribute.LongFormVersion
};
}
return commandModel;
}
protected virtual CommandModel.ArgumentModel CreateArgumentModel(ParameterInfo parameterInfo)
{
if (parameterInfo == null)
throw new ArgumentNullException(nameof(parameterInfo));
if (!IsArgument(parameterInfo))
return null;
var argumentModel = new CommandModel.ArgumentModel() { Parameter = parameterInfo };
{
var attribute = parameterInfo.GetCustomAttribute<ArgumentAttribute>(inherit: true);
argumentModel.Name = attribute?.Name ?? GetArgumentName(parameterInfo.Name);
argumentModel.Description = attribute?.Description ?? parameterInfo.ToString();
argumentModel.MultipleValues = attribute?.MultipleValues;
argumentModel.ShowInHelpText = attribute?.ShowInHelpText ?? true;
}
foreach (var attribute in parameterInfo.GetCustomAttributes<ConverterAttribute>(inherit: true))
{
if (argumentModel.Converters == null)
argumentModel.Converters = new List<Type>();
argumentModel.Converters.Add(attribute.Type);
}
return argumentModel;
}
protected virtual CommandModel.OptionModel CreateOptionModel(ParameterInfo parameterInfo)
{
if (parameterInfo == null)
throw new ArgumentNullException(nameof(parameterInfo));
if (!IsOption(parameterInfo))
return null;
var optionModel = new CommandModel.OptionModel() { Parameter = parameterInfo };
{
var attribute = parameterInfo.GetCustomAttribute<OptionAttribute>(inherit: true);
optionModel.Template = attribute?.Template ?? GetOptionTemplate(parameterInfo.Name);
optionModel.Description = attribute?.Description ?? parameterInfo.ToString();
optionModel.OptionType = attribute?.OptionType;
optionModel.ShowInHelpText = attribute?.ShowInHelpText ?? true;
if (optionModel.OptionType == null)
if (parameterInfo.ParameterType.IsAssignableFrom(typeof(bool)))
optionModel.OptionType = CommandOptionType.NoValue;
if (optionModel.Template == null)
if (optionModel.OptionType == CommandOptionType.NoValue)
optionModel.Template = GetOptionTemplate(parameterInfo.Name, false);
else
optionModel.Template = GetOptionTemplate(parameterInfo.Name, true);
}
foreach (var attribute in parameterInfo.GetCustomAttributes<ConverterAttribute>(inherit: true))
{
if (optionModel.Converters == null)
optionModel.Converters = new List<Type>();
optionModel.Converters.Add(attribute.Type);
}
return optionModel;
}
protected virtual bool IsCommand(TypeInfo typeInfo)
{
if (typeInfo == null)
throw new ArgumentNullException(nameof(typeInfo));
if (!typeInfo.IsClass)
return false;
if (typeInfo.IsAbstract && !typeInfo.IsSealed)
return false;
if (!typeInfo.IsPublic)
return false;
if (typeInfo.ContainsGenericParameters)
return false;
if (typeInfo.IsDefined(typeof(NonCommandAttribute)))
return false;
if (typeInfo.IsDefined(typeof(CommandAttribute)))
return true;
return true;
}
protected virtual bool IsCommand(MethodInfo methodInfo)
{
if (methodInfo == null)
throw new ArgumentNullException(nameof(methodInfo));
if (methodInfo.IsSpecialName)
return false;
if (methodInfo.IsDefined(typeof(NonCommandAttribute)))
return false;
if (methodInfo.GetBaseDefinition().DeclaringType == typeof(object))
return false;
if (IsIDisposableMethod(methodInfo))
return false;
if (methodInfo.IsAbstract)
return false;
if (methodInfo.IsConstructor)
return false;
if (methodInfo.IsGenericMethod)
return false;
if (!methodInfo.IsPublic)
return false;
if (methodInfo.IsDefined(typeof(NonCommandAttribute)))
return false;
if (methodInfo.IsDefined(typeof(CommandAttribute)))
return true;
return true;
}
protected virtual bool IsArgument(ParameterInfo parameterInfo)
{
if (parameterInfo == null)
throw new ArgumentNullException(nameof(parameterInfo));
if (parameterInfo.IsOut || parameterInfo.IsRetval)
return false;
if (parameterInfo.IsDefined(typeof(ArgumentAttribute)))
return true;
if (parameterInfo.IsDefined(typeof(OptionAttribute)))
return false;
if (parameterInfo.ParameterType == typeof(bool))
return false;
if (parameterInfo.HasDefaultValue || parameterInfo.IsOptional)
return false;
return true;
}
protected virtual bool IsOption(ParameterInfo parameterInfo)
{
if (parameterInfo == null)
throw new ArgumentNullException(nameof(parameterInfo));
if (parameterInfo.IsOut || parameterInfo.IsRetval)
return false;
if (parameterInfo.IsDefined(typeof(OptionAttribute)))
return true;
if (parameterInfo.IsDefined(typeof(ArgumentAttribute)))
return false;
if (parameterInfo.ParameterType == typeof(bool))
return true;
if (parameterInfo.IsOptional)
return true;
return true;
}
protected virtual string GetCommandName(string name)
{
var s = name.ToKebabCase();
if (s.EndsWith("command", StringComparison.OrdinalIgnoreCase) &&
s.Length > "command".Length)
s = s.Substring(0, s.Length - "command".Length);
else if (s.EndsWith("commands", StringComparison.OrdinalIgnoreCase) &&
s.Length > "commands".Length)
s = s.Substring(0, s.Length - "commands".Length);
return s.Trim('-');
}
protected virtual string GetArgumentName(string name, bool isOptional = false)
{
return name.ToSnakeCase();
}
protected virtual string GetOptionTemplate(string name, bool hasValue = false)
{
var s = name.ToKebabCase();
if (hasValue)
{
if (s.Length == 1)
return $"-{s} <{name.ToSnakeCase()}>";
else
return $"--{s} <{name.ToSnakeCase()}>";
}
else
{
if (s.Length == 1)
return $"-{s}";
else
return $"--{s}";
}
}
protected virtual string GetDefaultHelpOptionTemplate()
{
return "-?|-h|--help";
}
private bool IsIDisposableMethod(MethodInfo methodInfo)
{
var baseMethodInfo = methodInfo.GetBaseDefinition();
var declaringTypeInfo = baseMethodInfo.DeclaringType.GetTypeInfo();
return (typeof(IDisposable).GetTypeInfo().IsAssignableFrom(declaringTypeInfo) &&
declaringTypeInfo.GetRuntimeInterfaceMap(typeof(IDisposable)).TargetMethods[0] == baseMethodInfo);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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 Aurora.Framework;
namespace OpenSim.Region.Physics.BasicPhysicsPlugin
{
public class BasicCharacterActor : PhysicsCharacter
{
private Vector3 _size;
public override bool IsJumping
{
get { return false; }
}
public override bool IsPreJumping
{
get { return false; }
}
public override float SpeedModifier
{
get { return 1.0f; }
set { }
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Agent; }
}
public override Vector3 RotationalVelocity { get; set; }
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
get { return 0; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool Flying { get; set; }
public override bool IsTruelyColliding { get; set; }
public override bool IsColliding { get; set; }
public override Vector3 Position { get; set; }
public override Vector3 Size
{
get { return _size; }
set
{
_size = value;
_size.Z = _size.Z/2.0f;
}
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override Vector3 Velocity { get; set; }
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set { }
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override bool SubscribedEvents()
{
return false;
}
public override void SendCollisions()
{
}
public override void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
{
}
}
public class BasicObjectActor : PhysicsObject
{
private Vector3 _size;
public override bool Selected
{
set { }
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Agent; }
}
public override Vector3 RotationalVelocity { get; set; }
public override uint LocalID
{
get { return 0; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool IsTruelyColliding { get; set; }
public override bool IsColliding { get; set; }
public override Vector3 Position { get; set; }
public override Vector3 Size
{
get { return _size; }
set
{
_size = value;
_size.Z = _size.Z/2.0f;
}
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 Velocity { get; set; }
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set { }
}
public override Vector3 Acceleration
{
get { return Vector3.Zero; }
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override void CrossingFailure()
{
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
public override void SendCollisions()
{
}
public override void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
{
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateConstructor
{
[ExportLanguageService(typeof(IGenerateConstructorService), LanguageNames.CSharp), Shared]
internal class CSharpGenerateConstructorService : AbstractGenerateConstructorService<CSharpGenerateConstructorService, ArgumentSyntax, AttributeArgumentSyntax>
{
private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation();
protected override bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
{
return node is SimpleNameSyntax;
}
protected override bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
{
return node is ConstructorInitializerSyntax;
}
protected override bool IsClassDeclarationGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
{
return node is ClassDeclarationSyntax;
}
protected override bool TryInitializeConstructorInitializerGeneration(
SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken,
out SyntaxToken token, out IList<ArgumentSyntax> arguments, out INamedTypeSymbol typeToGenerateIn)
{
var constructorInitializer = (ConstructorInitializerSyntax)node;
if (!constructorInitializer.ArgumentList.CloseParenToken.IsMissing)
{
token = constructorInitializer.ThisOrBaseKeyword;
arguments = constructorInitializer.ArgumentList.Arguments.ToList();
var semanticModel = document.SemanticModel;
var currentType = semanticModel.GetEnclosingNamedType(constructorInitializer.SpanStart, cancellationToken);
typeToGenerateIn = constructorInitializer.IsKind(SyntaxKind.ThisConstructorInitializer)
? currentType
: currentType.BaseType.OriginalDefinition;
return typeToGenerateIn != null;
}
token = default(SyntaxToken);
arguments = null;
typeToGenerateIn = null;
return false;
}
protected override bool TryInitializeClassDeclarationGenerationState(
SemanticDocument document,
SyntaxNode node,
CancellationToken cancellationToken,
out SyntaxToken token,
out IMethodSymbol delegatedConstructor,
out INamedTypeSymbol typeToGenerateIn)
{
token = default(SyntaxToken);
typeToGenerateIn = null;
delegatedConstructor = null;
var semanticModel = document.SemanticModel;
var classDeclaration = (ClassDeclarationSyntax)node;
var classSymbol = semanticModel.GetDeclaredSymbol(classDeclaration, cancellationToken);
var baseType = classSymbol.BaseType;
var constructor = baseType.Constructors.FirstOrDefault(c => IsSymbolAccessible(c, document));
if (constructor == null)
{
return false;
}
typeToGenerateIn = classSymbol;
delegatedConstructor = constructor;
token = classDeclaration.Identifier;
return true;
}
protected override bool TryInitializeSimpleNameGenerationState(
SemanticDocument document,
SyntaxNode node,
CancellationToken cancellationToken,
out SyntaxToken token,
out IList<ArgumentSyntax> arguments,
out INamedTypeSymbol typeToGenerateIn)
{
var simpleName = (SimpleNameSyntax)node;
var fullName = simpleName.IsRightSideOfQualifiedName()
? (NameSyntax)simpleName.Parent
: simpleName;
if (fullName.Parent is ObjectCreationExpressionSyntax)
{
var objectCreationExpression = (ObjectCreationExpressionSyntax)fullName.Parent;
if (objectCreationExpression.ArgumentList != null &&
!objectCreationExpression.ArgumentList.CloseParenToken.IsMissing)
{
var symbolInfo = document.SemanticModel.GetSymbolInfo(objectCreationExpression.Type, cancellationToken);
token = simpleName.Identifier;
arguments = objectCreationExpression.ArgumentList.Arguments.ToList();
typeToGenerateIn = symbolInfo.GetAnySymbol() as INamedTypeSymbol;
return typeToGenerateIn != null;
}
}
token = default(SyntaxToken);
arguments = null;
typeToGenerateIn = null;
return false;
}
protected override bool TryInitializeSimpleAttributeNameGenerationState(
SemanticDocument document,
SyntaxNode node,
CancellationToken cancellationToken,
out SyntaxToken token,
out IList<ArgumentSyntax> arguments,
out IList<AttributeArgumentSyntax> attributeArguments,
out INamedTypeSymbol typeToGenerateIn)
{
var simpleName = (SimpleNameSyntax)node;
var fullName = simpleName.IsRightSideOfQualifiedName()
? (NameSyntax)simpleName.Parent
: simpleName;
if (fullName.Parent is AttributeSyntax)
{
var attribute = (AttributeSyntax)fullName.Parent;
if (attribute.ArgumentList != null &&
!attribute.ArgumentList.CloseParenToken.IsMissing)
{
var symbolInfo = document.SemanticModel.GetSymbolInfo(attribute, cancellationToken);
if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !symbolInfo.CandidateSymbols.IsEmpty)
{
token = simpleName.Identifier;
attributeArguments = attribute.ArgumentList.Arguments.ToList();
arguments = attributeArguments.Select(x => SyntaxFactory.Argument(x.NameColon ?? ((x.NameEquals != null) ? SyntaxFactory.NameColon(x.NameEquals.Name) : null), default(SyntaxToken), x.Expression)).ToList();
typeToGenerateIn = symbolInfo.CandidateSymbols.FirstOrDefault().ContainingSymbol as INamedTypeSymbol;
return typeToGenerateIn != null;
}
}
}
token = default(SyntaxToken);
arguments = null;
attributeArguments = null;
typeToGenerateIn = null;
return false;
}
protected override IList<ParameterName> GenerateParameterNames(
SemanticModel semanticModel, IEnumerable<ArgumentSyntax> arguments, IList<string> reservedNames)
{
return semanticModel.GenerateParameterNames(arguments, reservedNames);
}
protected override IList<ParameterName> GenerateParameterNames(
SemanticModel semanticModel, IEnumerable<AttributeArgumentSyntax> arguments, IList<string> reservedNames)
{
return semanticModel.GenerateParameterNames(arguments, reservedNames);
}
protected override string GenerateNameForArgument(
SemanticModel semanticModel, ArgumentSyntax argument)
{
return semanticModel.GenerateNameForArgument(argument);
}
protected override string GenerateNameForArgument(
SemanticModel semanticModel, AttributeArgumentSyntax argument)
{
return semanticModel.GenerateNameForArgument(argument);
}
protected override RefKind GetRefKind(ArgumentSyntax argument)
{
return argument.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword ? RefKind.Ref :
argument.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword ? RefKind.Out : RefKind.None;
}
protected override bool IsNamedArgument(ArgumentSyntax argument)
{
return argument.NameColon != null;
}
protected override ITypeSymbol GetArgumentType(
SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
{
return argument.DetermineParameterType(semanticModel, cancellationToken);
}
protected override ITypeSymbol GetAttributeArgumentType(
SemanticModel semanticModel, AttributeArgumentSyntax argument, CancellationToken cancellationToken)
{
return semanticModel.GetType(argument.Expression, cancellationToken);
}
protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
{
return compilation.ClassifyConversion(sourceType, targetType).IsImplicit;
}
internal override IMethodSymbol GetDelegatingConstructor(
State state,
SemanticDocument document,
int argumentCount,
INamedTypeSymbol namedType,
ISet<IMethodSymbol> candidates,
CancellationToken cancellationToken)
{
var oldToken = state.Token;
var tokenKind = oldToken.Kind();
if (state.IsConstructorInitializerGeneration)
{
SyntaxToken thisOrBaseKeyword;
SyntaxKind newCtorInitializerKind;
if (tokenKind != SyntaxKind.BaseKeyword && state.TypeToGenerateIn == namedType)
{
thisOrBaseKeyword = SyntaxFactory.Token(SyntaxKind.ThisKeyword);
newCtorInitializerKind = SyntaxKind.ThisConstructorInitializer;
}
else
{
thisOrBaseKeyword = SyntaxFactory.Token(SyntaxKind.BaseKeyword);
newCtorInitializerKind = SyntaxKind.BaseConstructorInitializer;
}
var ctorInitializer = (ConstructorInitializerSyntax)oldToken.Parent;
var oldArgumentList = ctorInitializer.ArgumentList;
var newArgumentList = GetNewArgumentList(oldArgumentList, argumentCount);
var newCtorInitializer = SyntaxFactory.ConstructorInitializer(newCtorInitializerKind, ctorInitializer.ColonToken, thisOrBaseKeyword, newArgumentList);
SemanticModel speculativeModel;
if (document.SemanticModel.TryGetSpeculativeSemanticModel(ctorInitializer.Span.Start, newCtorInitializer, out speculativeModel))
{
var symbolInfo = speculativeModel.GetSymbolInfo(newCtorInitializer, cancellationToken);
return GenerateConstructorHelpers.GetDelegatingConstructor(
document, symbolInfo, candidates, namedType, state.ParameterTypes);
}
}
else
{
var oldNode = oldToken.Parent
.AncestorsAndSelf(ascendOutOfTrivia: false)
.Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node))
.LastOrDefault();
var typeNameToReplace = (TypeSyntax)oldToken.Parent;
TypeSyntax newTypeName;
if (namedType != state.TypeToGenerateIn)
{
while (true)
{
var parentType = typeNameToReplace.Parent as TypeSyntax;
if (parentType == null)
{
break;
}
typeNameToReplace = parentType;
}
newTypeName = namedType.GenerateTypeSyntax().WithAdditionalAnnotations(s_annotation);
}
else
{
newTypeName = typeNameToReplace.WithAdditionalAnnotations(s_annotation);
}
var newNode = oldNode.ReplaceNode(typeNameToReplace, newTypeName);
newTypeName = (TypeSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
var oldArgumentList = (ArgumentListSyntax)newTypeName.Parent.ChildNodes().FirstOrDefault(n => n is ArgumentListSyntax);
if (oldArgumentList != null)
{
var newArgumentList = GetNewArgumentList(oldArgumentList, argumentCount);
if (newArgumentList != oldArgumentList)
{
newNode = newNode.ReplaceNode(oldArgumentList, newArgumentList);
newTypeName = (TypeSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
}
}
var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, document.SemanticModel);
if (speculativeModel != null)
{
var symbolInfo = speculativeModel.GetSymbolInfo(newTypeName.Parent, cancellationToken);
return GenerateConstructorHelpers.GetDelegatingConstructor(
document, symbolInfo, candidates, namedType, state.ParameterTypes);
}
}
return null;
}
private static ArgumentListSyntax GetNewArgumentList(ArgumentListSyntax oldArgumentList, int argumentCount)
{
if (oldArgumentList.IsMissing || oldArgumentList.Arguments.Count == argumentCount)
{
return oldArgumentList;
}
var newArguments = oldArgumentList.Arguments.Take(argumentCount);
return SyntaxFactory.ArgumentList(new SeparatedSyntaxList<ArgumentSyntax>().AddRange(newArguments));
}
}
}
| |
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 so18191213.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* Copyright (c) .NET Foundation and Contributors
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* https://github.com/piranhacms/piranha.core
*
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Piranha.Manager.Models;
using Piranha.Manager.Services;
using Piranha.Models;
namespace Piranha.Manager.Controllers
{
/// <summary>
/// Api controller for media management.
/// </summary>
[Area("Manager")]
[Route("manager/api/media")]
[Authorize(Policy = Permission.Admin)]
[ApiController]
[AutoValidateAntiforgeryToken]
public class MediaApiController : Controller
{
private readonly MediaService _service;
private readonly IApi _api;
private readonly ManagerLocalizer _localizer;
public MediaApiController(MediaService service, IApi api, ManagerLocalizer localizer)
{
_service = service;
_api = api;
_localizer = localizer;
}
/// <summary>
/// Gets single media
/// </summary>
/// <returns>The list model</returns>
[Route("{id}")]
[HttpGet]
public async Task<IActionResult> Get(Guid id)
{
var media = await _service.GetById(id);
if (media == null)
{
return NotFound();
}
return Ok(media);
}
/// <summary>
/// Gets the image url for the specified dimensions.
/// </summary>
/// <param name="id">The unique id</param>
/// <param name="width">The optional width</param>
/// <param name="height">The optional height</param>
/// <returns>The public url</returns>
[Route("url/{id}/{width?}/{height?}")]
[HttpGet]
public async Task<IActionResult> GetUrl(Guid id, int? width = null, int? height = null)
{
if (!width.HasValue)
{
var media = await _api.Media.GetByIdAsync(id);
if (media != null)
{
return Redirect(media.PublicUrl);
}
return NotFound();
}
else
{
return Redirect(await _api.Media.EnsureVersionAsync(id, width.Value, height));
}
}
/// <summary>
/// Gets the list model.
/// </summary>
/// <returns>The list model</returns>
[Route("list/{folderId:Guid?}")]
[HttpGet]
public async Task<MediaListModel> List(Guid? folderId = null, [FromQuery]MediaType? filter = null, [FromQuery] int? width = null, [FromQuery] int? height = null)
{
return await _service.GetList(folderId, filter, width, height);
}
/// <summary>
/// Saves the meta information for the given media asset.
/// </summary>
/// <param name="model">The media model</param>
[Route("meta/save")]
[HttpPost]
public async Task<IActionResult> SaveMeta(MediaListModel.MediaItem model)
{
if (await _service.SaveMeta(model))
{
return Ok(new StatusMessage
{
Type = StatusMessage.Success,
Body = _localizer.Media["The meta information was successfully updated"]
});
}
else
{
return Ok(new StatusMessage
{
Type = StatusMessage.Error,
Body = _localizer.Media["An error occured when updating the meta information"]
});
}
}
[Route("folder/save")]
[HttpPost]
[Authorize(Policy = Permission.MediaAddFolder)]
public async Task<IActionResult> SaveFolder(MediaFolderModel model, MediaType? filter = null)
{
try
{
await _service.SaveFolder(model);
var result = await _service.GetList(model.ParentId, filter);
result.Status = new StatusMessage
{
Type = StatusMessage.Success,
Body = String.Format(_localizer.Media["The folder <code>{0}</code> was saved"], model.Name)
};
return Ok(result);
}
catch (ValidationException e)
{
var result = new MediaListModel();
result.Status = new StatusMessage
{
Type = StatusMessage.Error,
Body = e.Message
};
return BadRequest(result);
}
}
[Route("folder/delete")]
[HttpDelete]
[Authorize(Policy = Permission.MediaDeleteFolder)]
public async Task<IActionResult> DeleteFolder([FromBody]Guid id)
{
try
{
var folderId = await _service.DeleteFolder(id);
var result = await _service.GetList(folderId);
result.Status = new StatusMessage
{
Type = StatusMessage.Success,
Body = _localizer.Media["The folder was successfully deleted"]
};
return Ok(result);
}
catch (ValidationException e)
{
var result = new MediaListModel();
result.Status = new StatusMessage
{
Type = StatusMessage.Error,
Body = e.Message
};
return BadRequest(result);
}
}
/// <summary>
/// Adds a new media upload.
/// </summary>
/// <param name="model">The upload model</param>
[Route("upload")]
[HttpPost]
[Consumes("multipart/form-data")]
[Authorize(Policy = Permission.MediaAdd)]
public async Task<IActionResult> Upload([FromForm] MediaUploadModel model)
{
// Allow for dropzone uploads
if (!model.Uploads.Any())
{
model.Uploads = HttpContext.Request.Form.Files;
}
try
{
var uploaded = await _service.SaveMedia(model);
if (uploaded == model.Uploads.Count())
{
return Ok(new StatusMessage
{
Type = StatusMessage.Success,
Body = _localizer.Media["Uploaded all media assets"]
});
}
else if (uploaded == 0)
{
return Ok(new StatusMessage
{
Type = StatusMessage.Error,
Body = _localizer.Media["Could not upload the media assets"]
});
}
else
{
return Ok(new StatusMessage
{
Type = StatusMessage.Information,
Body = String.Format(_localizer.Media["Uploaded {0} of {1} media assets"], uploaded, model.Uploads.Count())
});
}
}
catch (Exception e)
{
return BadRequest(new StatusMessage
{
Type = StatusMessage.Error,
Body = e.Message
});
}
}
[Route("move/{folderId?}")]
[HttpPost]
[Consumes("application/json")]
[Authorize(Policy = Permission.MediaEdit)]
public async Task<IActionResult> Move([FromBody] IEnumerable<Guid> items, Guid? folderId)
{
try
{
var moved = 0;
foreach (var id in items)
{
var media = await _api.Media.GetByIdAsync(id);
if (media != null)
{
await _api.Media.MoveAsync(media, folderId);
moved++;
continue;
}
var folder = await _api.Media.GetFolderByIdAsync(id);
if (folder != null)
{
if (folderId.HasValue && folderId == folder.Id)
continue;
folder.ParentId = folderId;
await _api.Media.SaveFolderAsync(folder);
moved++;
}
}
if (moved > 0)
{
return Ok(new StatusMessage
{
Type = StatusMessage.Success,
Body = _localizer.Media[$"Media file{(moved > 1 ? "s" : "")} was successfully moved."]
});
}
else
{
return BadRequest(new StatusMessage
{
Type = StatusMessage.Error,
Body = _localizer.Media["The media file was not found."]
});
}
}
catch (Exception e)
{
return BadRequest(new StatusMessage
{
Type = StatusMessage.Error,
Body = e.Message
});
}
}
[Route("delete")]
[HttpDelete]
[Consumes("application/json")]
[Authorize(Policy = Permission.MediaDelete)]
public async Task<IActionResult> Delete([FromBody] IEnumerable<Guid> items)
{
try
{
foreach(var id in items)
{
await _service.DeleteMedia(id);
}
return Ok(new StatusMessage
{
Type = StatusMessage.Success,
Body = _localizer.Media[$"The media file{(items.Count() > 1 ? "s" : "")} was successfully deleted"]
});
}
catch (ValidationException e)
{
return BadRequest(new StatusMessage
{
Type = StatusMessage.Error,
Body = e.Message
});
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
/// <summary>
/// Class of extension rule for Metadata.Core.2016
/// </summary>
[Export(typeof(ExtensionRule))]
public class MetadataCore2016 : ExtensionRule
{
/// <summary>
/// Gets Category property
/// </summary>
public override string Category
{
get
{
return "core";
}
}
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Metadata.Core.2016";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "A data service SHOULD support target paths that define elements with mixed content.";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string SpecificationSection
{
get
{
return "2.2.3.7.2.1";
}
}
/// <summary>
/// Gets the version.
/// </summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V1_V2_V3;
}
}
/// <summary>
/// Gets location of help information of the rule
/// </summary>
public override string HelpLink
{
get
{
return null;
}
}
/// <summary>
/// Gets the error message for validation failure
/// </summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
/// <summary>
/// Gets the requirement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Should;
}
}
/// <summary>
/// Gets the payload type to which the rule applies.
/// </summary>
public override PayloadType? PayloadType
{
get
{
return RuleEngine.PayloadType.Metadata;
}
}
/// <summary>
/// Gets the flag whether the rule requires metadata document
/// </summary>
public override bool? RequireMetadata
{
get
{
return true;
}
}
/// <summary>
/// Gets the offline context to which the rule applies
/// </summary>
public override bool? IsOfflineContext
{
get
{
return false;
}
}
/// <summary>
/// Gets the payload format to which the rule applies.
/// </summary>
public override PayloadFormat? PayloadFormat
{
get
{
return RuleEngine.PayloadFormat.Xml;
}
}
/// <summary>
/// Verify Metadata.Core.2016
/// </summary>
/// <param name="context">Service context</param>
/// <param name="info">out parameter to return violation information when rule fail</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
info = null;
// Adding all AtomPub mappings to a list
List<string> atomPubMapping = new List<string>(new string[]
{
"SyndicationAuthorName",
"SyndicationAuthorEmail",
"SyndicationAuthorUri",
"SyndicationPublished",
"SyndicationRights",
"SyndicationTitle",
"SyndicationUpdated",
"SyndicationContributorName",
"SyndicationContributorEmail",
"SyndicationContributorUri",
"SyndicationSource",
"SyndicationSummary"
});
// Load MetadataDocument into XMLDOM
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(context.MetadataDocument);
// Find the namespace(s) in order to query for EntitySet name
XmlNodeList namespaceList = xmlDoc.SelectNodes("//*[@*[name()='Namespace']]");
// Find all nodes
XmlNodeList xmlNodeList = xmlDoc.SelectNodes("//*[@*[name()='m:FC_TargetPath']]");
if (xmlNodeList.Count != 0)
{
XmlNode entitySetNode = null;
foreach (XmlNode node in xmlNodeList)
{
// Find the EntitySet node
bool foundEntitySet = false;
foreach (XmlNode nsNode in namespaceList)
{
if (!foundEntitySet)
{
entitySetNode = xmlDoc.SelectSingleNode("//*[@*[name()='EntityType'] = '" + nsNode.Attributes["Namespace"].Value + "." + node.ParentNode.Attributes["Name"].Value + "']");
if (entitySetNode != null)
{
foundEntitySet = true;
}
}
}
List<string> pathList = new List<string>();
if (!atomPubMapping.Exists(item => item == node.Attributes["m:FC_TargetPath"].Value))
{
// Construct the XPath query
pathList = node.Attributes["m:FC_TargetPath"].Value.Split('/').ToList();
StringBuilder xpathQuery = new StringBuilder();
xpathQuery.Append("//*/*[local-name()='entry']");
foreach (string path in pathList)
{
xpathQuery.Append("/*[local-name()='");
xpathQuery.Append(path);
xpathQuery.Append("']");
}
// Query to find the first entity in the EntitySet
Uri absoluteUri = new Uri(context.Destination.OriginalString);
Uri relativeUri = new Uri(entitySetNode.Attributes["Name"].Value + "?$top=1", UriKind.Relative);
Uri combinedUri = new Uri(absoluteUri, relativeUri);
Response response = WebHelper.Get(combinedUri, Constants.AcceptHeaderAtom, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
if (response.StatusCode == HttpStatusCode.OK)
{
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.LoadXml(response.ResponsePayload);
if (xmlDoc2.SelectSingleNode(xpathQuery.ToString()) != null)
{
passed = true;
}
else
{
passed = false;
break;
}
}
}
}
}
info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
return passed;
}
}
}
| |
/********************************************************************
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.
*********************************************************************/
namespace Multiverse.Tools.TerrainAssembler
{
partial class LoadLayerDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.zoneNameLabel = new System.Windows.Forms.Label();
this.zoneNameValueLabel = new System.Windows.Forms.Label();
this.layerLabel = new System.Windows.Forms.Label();
this.layerComboBox = new System.Windows.Forms.ComboBox();
this.imageNameLabel = new System.Windows.Forms.Label();
this.imageNameTextBox = new System.Windows.Forms.TextBox();
this.browseButton = new System.Windows.Forms.Button();
this.loadButton = new System.Windows.Forms.Button();
this.helpButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.metersPerPixelLabel = new System.Windows.Forms.Label();
this.metersPerPixelComboBox = new System.Windows.Forms.ComboBox();
this.validationErrorProvider = new System.Windows.Forms.ErrorProvider(this.components);
((System.ComponentModel.ISupportInitialize)(this.validationErrorProvider)).BeginInit();
this.SuspendLayout();
//
// zoneNameLabel
//
this.zoneNameLabel.AutoSize = true;
this.zoneNameLabel.Location = new System.Drawing.Point(25, 25);
this.zoneNameLabel.Name = "zoneNameLabel";
this.zoneNameLabel.Size = new System.Drawing.Size(66, 13);
this.zoneNameLabel.TabIndex = 0;
this.zoneNameLabel.Text = "Zone Name:";
//
// zoneNameValueLabel
//
this.zoneNameValueLabel.AutoSize = true;
this.zoneNameValueLabel.Location = new System.Drawing.Point(121, 25);
this.zoneNameValueLabel.Name = "zoneNameValueLabel";
this.zoneNameValueLabel.Size = new System.Drawing.Size(12, 13);
this.zoneNameValueLabel.TabIndex = 1;
this.zoneNameValueLabel.Text = "x";
//
// layerLabel
//
this.layerLabel.AutoSize = true;
this.layerLabel.Location = new System.Drawing.Point(25, 62);
this.layerLabel.Name = "layerLabel";
this.layerLabel.Size = new System.Drawing.Size(36, 13);
this.layerLabel.TabIndex = 2;
this.layerLabel.Text = "Layer:";
//
// layerComboBox
//
this.layerComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.layerComboBox.FormattingEnabled = true;
this.layerComboBox.Location = new System.Drawing.Point(124, 59);
this.layerComboBox.Name = "layerComboBox";
this.layerComboBox.Size = new System.Drawing.Size(135, 21);
this.layerComboBox.TabIndex = 3;
//
// imageNameLabel
//
this.imageNameLabel.AutoSize = true;
this.imageNameLabel.Location = new System.Drawing.Point(25, 107);
this.imageNameLabel.Name = "imageNameLabel";
this.imageNameLabel.Size = new System.Drawing.Size(70, 13);
this.imageNameLabel.TabIndex = 4;
this.imageNameLabel.Text = "Image Name:";
//
// imageNameTextBox
//
this.imageNameTextBox.Location = new System.Drawing.Point(124, 104);
this.imageNameTextBox.Name = "imageNameTextBox";
this.imageNameTextBox.Size = new System.Drawing.Size(361, 20);
this.imageNameTextBox.TabIndex = 5;
this.imageNameTextBox.Validated += new System.EventHandler(this.imageNameTextBox_Validated);
this.imageNameTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.imageNameTextBox_Validating);
//
// browseButton
//
this.browseButton.Location = new System.Drawing.Point(517, 102);
this.browseButton.Name = "browseButton";
this.browseButton.Size = new System.Drawing.Size(75, 23);
this.browseButton.TabIndex = 6;
this.browseButton.Text = "Browse...";
this.browseButton.UseVisualStyleBackColor = true;
this.browseButton.Click += new System.EventHandler(this.browseButton_Click);
//
// loadButton
//
this.loadButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.loadButton.Enabled = false;
this.loadButton.Location = new System.Drawing.Point(28, 300);
this.loadButton.Name = "loadButton";
this.loadButton.Size = new System.Drawing.Size(75, 23);
this.loadButton.TabIndex = 7;
this.loadButton.Text = "Load";
this.loadButton.UseVisualStyleBackColor = true;
//
// helpButton
//
this.helpButton.Location = new System.Drawing.Point(410, 300);
this.helpButton.Name = "helpButton";
this.helpButton.Size = new System.Drawing.Size(75, 23);
this.helpButton.TabIndex = 8;
this.helpButton.Text = "Help";
this.helpButton.UseVisualStyleBackColor = true;
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(517, 300);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 9;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
//
// metersPerPixelLabel
//
this.metersPerPixelLabel.AutoSize = true;
this.metersPerPixelLabel.Location = new System.Drawing.Point(25, 152);
this.metersPerPixelLabel.Name = "metersPerPixelLabel";
this.metersPerPixelLabel.Size = new System.Drawing.Size(86, 13);
this.metersPerPixelLabel.TabIndex = 10;
this.metersPerPixelLabel.Text = "Meters Per Pixel:";
//
// metersPerPixelComboBox
//
this.metersPerPixelComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.metersPerPixelComboBox.FormattingEnabled = true;
this.metersPerPixelComboBox.Items.AddRange(new object[] {
"1",
"2",
"4",
"8",
"16",
"32",
"64"});
this.metersPerPixelComboBox.Location = new System.Drawing.Point(124, 149);
this.metersPerPixelComboBox.Name = "metersPerPixelComboBox";
this.metersPerPixelComboBox.Size = new System.Drawing.Size(135, 21);
this.metersPerPixelComboBox.TabIndex = 11;
this.metersPerPixelComboBox.SelectedIndexChanged += new System.EventHandler(this.metersPerPixelComboBox_SelectedIndexChanged);
//
// validationErrorProvider
//
this.validationErrorProvider.ContainerControl = this;
//
// LoadLayerDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(619, 347);
this.Controls.Add(this.metersPerPixelComboBox);
this.Controls.Add(this.metersPerPixelLabel);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.helpButton);
this.Controls.Add(this.loadButton);
this.Controls.Add(this.browseButton);
this.Controls.Add(this.imageNameTextBox);
this.Controls.Add(this.imageNameLabel);
this.Controls.Add(this.layerComboBox);
this.Controls.Add(this.layerLabel);
this.Controls.Add(this.zoneNameValueLabel);
this.Controls.Add(this.zoneNameLabel);
this.Name = "LoadLayerDialog";
this.Text = "Load a layer";
((System.ComponentModel.ISupportInitialize)(this.validationErrorProvider)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label zoneNameLabel;
private System.Windows.Forms.Label zoneNameValueLabel;
private System.Windows.Forms.Label layerLabel;
private System.Windows.Forms.ComboBox layerComboBox;
private System.Windows.Forms.Label imageNameLabel;
private System.Windows.Forms.TextBox imageNameTextBox;
private System.Windows.Forms.Button browseButton;
private System.Windows.Forms.Button loadButton;
private System.Windows.Forms.Button helpButton;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Label metersPerPixelLabel;
private System.Windows.Forms.ComboBox metersPerPixelComboBox;
private System.Windows.Forms.ErrorProvider validationErrorProvider;
}
}
| |
// Copyright (c) 2011-2015 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Runtime.InteropServices;
using X11;
#if MONO
using Mono.Unix;
#endif
namespace X11.XKlavier
{
/// <summary>
/// Provides access to the xklavier XKB keyboarding engine methods.
/// </summary>
/// <seealso href="https://developer.gnome.org/libxklavier/stable/libxklavier-xkl-engine.html"/>
internal class XklEngine : IXklEngine
{
private struct XklState
{
#pragma warning disable 649 // the struct is initialized by marshaling pointers
public int Group;
public int Indicators;
#pragma warning restore 649
}
private string[] m_GroupNames;
private string[] m_LocalizedGroupNames;
public XklEngine() : this(X11Helper.GetDisplayConnection())
{
}
public XklEngine(IntPtr display)
{
Engine = xkl_engine_get_instance(display);
#if MONO
Catalog.Init("xkeyboard-config", string.Empty);
#endif
}
public void Close()
{
}
public IntPtr Engine { get; private set; }
public string Name
{
get
{
var name = xkl_engine_get_backend_name(Engine);
return Marshal.PtrToStringAuto(name);
}
}
public int NumGroups
{
get { return xkl_engine_get_num_groups(Engine); }
}
/// <summary>
/// Gets the non-localized, English names of the installed XKB keyboards
/// </summary>
public virtual string[] GroupNames
{
get
{
if (m_GroupNames == null)
{
int count = NumGroups;
var names = xkl_engine_get_groups_names(Engine);
var namePtrs = new IntPtr[count];
Marshal.Copy(names, namePtrs, 0, count);
m_GroupNames = new string[count];
for (int i = 0; i < count; i++)
{
m_GroupNames[i] = Marshal.PtrToStringAuto(namePtrs[i]);
}
}
return m_GroupNames;
}
}
/// <summary>
/// Gets the localized names of the installed XKB keyboards
/// </summary>
public virtual string[] LocalizedGroupNames
{
get
{
if (m_LocalizedGroupNames == null)
{
var count = GroupNames.Length;
m_LocalizedGroupNames = new string[count];
for (int i = 0; i < count; i++)
{
#if MONO
m_LocalizedGroupNames[i] = Catalog.GetString(GroupNames[i]);
#endif
}
}
return m_LocalizedGroupNames;
}
}
public int NextGroup
{
get { return xkl_engine_get_next_group(Engine); }
}
public int PrevGroup
{
get { return xkl_engine_get_prev_group(Engine); }
}
public int CurrentWindowGroup
{
get { return xkl_engine_get_current_window_group(Engine); }
}
public int DefaultGroup
{
get { return xkl_engine_get_default_group(Engine); }
set { xkl_engine_set_default_group(Engine, value); }
}
public void SetGroup(int grp)
{
xkl_engine_lock_group(Engine, grp);
}
public void SetToplevelWindowGroup(bool fGlobal)
{
xkl_engine_set_group_per_toplevel_window(Engine, fGlobal);
}
public bool IsToplevelWindowGroup
{
get { return xkl_engine_is_group_per_toplevel_window(Engine); }
}
public int CurrentState
{
get
{
var statePtr = xkl_engine_get_current_state(Engine);
var state = (XklState)Marshal.PtrToStructure(statePtr, typeof(XklState));
return state.Group;
}
}
public int CurrentWindowState
{
get
{
var window = xkl_engine_get_current_window(Engine);
IntPtr statePtr;
if (xkl_engine_get_state(Engine, window, out statePtr))
{
var state = (XklState)Marshal.PtrToStructure(statePtr, typeof(XklState));
return state.Group;
}
return -1;
}
}
public string LastError
{
get
{
var error = xkl_get_last_error();
return Marshal.PtrToStringAuto(error);
}
}
// from libXKlavier
[DllImport("libxklavier")]
private extern static IntPtr xkl_engine_get_instance(IntPtr display);
[DllImport("libxklavier")]
private extern static IntPtr xkl_engine_get_backend_name(IntPtr engine);
[DllImport("libxklavier")]
private extern static int xkl_engine_get_num_groups(IntPtr engine);
[DllImport("libxklavier")]
private extern static IntPtr xkl_engine_get_groups_names(IntPtr engine);
[DllImport("libxklavier")]
private extern static int xkl_engine_get_next_group(IntPtr engine);
[DllImport("libxklavier")]
private extern static int xkl_engine_get_prev_group(IntPtr engine);
[DllImport("libxklavier")]
private extern static int xkl_engine_get_current_window_group(IntPtr engine);
[DllImport("libxklavier")]
private extern static void xkl_engine_lock_group(IntPtr engine, int grp);
[DllImport("libxklavier")]
private extern static int xkl_engine_get_default_group(IntPtr engine);
[DllImport("libxklavier")]
private extern static void xkl_engine_set_default_group(IntPtr engine, int grp);
[DllImport("libxklavier")]
private extern static void xkl_engine_set_group_per_toplevel_window(IntPtr engine, bool isGlobal);
[DllImport("libxklavier")]
private extern static bool xkl_engine_is_group_per_toplevel_window(IntPtr engine);
[DllImport("libxklavier")]
private extern static IntPtr xkl_engine_get_current_state(IntPtr engine);
[DllImport("libxklavier")]
private extern static IntPtr xkl_engine_get_current_window(IntPtr engine);
[DllImport("libxklavier")]
private extern static bool xkl_engine_get_state(IntPtr engine, IntPtr win, out IntPtr state_out);
[DllImport("libxklavier")]
private extern static IntPtr xkl_get_last_error();
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticmapreduce-2009-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticMapReduce.Model
{
/// <summary>
/// A description of the Amazon EC2 instance running the job flow. A valid JobFlowInstancesConfig
/// must contain at least InstanceGroups, which is the recommended configuration. However,
/// a valid alternative is to have MasterInstanceType, SlaveInstanceType, and InstanceCount
/// (all three must be present).
/// </summary>
public partial class JobFlowInstancesConfig
{
private List<string> _additionalMasterSecurityGroups = new List<string>();
private List<string> _additionalSlaveSecurityGroups = new List<string>();
private string _ec2KeyName;
private string _ec2SubnetId;
private string _emrManagedMasterSecurityGroup;
private string _emrManagedSlaveSecurityGroup;
private string _hadoopVersion;
private int? _instanceCount;
private List<InstanceGroupConfig> _instanceGroups = new List<InstanceGroupConfig>();
private bool? _keepJobFlowAliveWhenNoSteps;
private string _masterInstanceType;
private PlacementType _placement;
private string _slaveInstanceType;
private bool? _terminationProtected;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public JobFlowInstancesConfig() { }
/// <summary>
/// Gets and sets the property AdditionalMasterSecurityGroups.
/// <para>
/// A list of additional Amazon EC2 security group IDs for the master node.
/// </para>
/// </summary>
public List<string> AdditionalMasterSecurityGroups
{
get { return this._additionalMasterSecurityGroups; }
set { this._additionalMasterSecurityGroups = value; }
}
// Check to see if AdditionalMasterSecurityGroups property is set
internal bool IsSetAdditionalMasterSecurityGroups()
{
return this._additionalMasterSecurityGroups != null && this._additionalMasterSecurityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property AdditionalSlaveSecurityGroups.
/// <para>
/// A list of additional Amazon EC2 security group IDs for the slave nodes.
/// </para>
/// </summary>
public List<string> AdditionalSlaveSecurityGroups
{
get { return this._additionalSlaveSecurityGroups; }
set { this._additionalSlaveSecurityGroups = value; }
}
// Check to see if AdditionalSlaveSecurityGroups property is set
internal bool IsSetAdditionalSlaveSecurityGroups()
{
return this._additionalSlaveSecurityGroups != null && this._additionalSlaveSecurityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property Ec2KeyName.
/// <para>
/// The name of the Amazon EC2 key pair that can be used to ssh to the master node as
/// the user called "hadoop."
/// </para>
/// </summary>
public string Ec2KeyName
{
get { return this._ec2KeyName; }
set { this._ec2KeyName = value; }
}
// Check to see if Ec2KeyName property is set
internal bool IsSetEc2KeyName()
{
return this._ec2KeyName != null;
}
/// <summary>
/// Gets and sets the property Ec2SubnetId.
/// <para>
/// To launch the job flow in Amazon Virtual Private Cloud (Amazon VPC), set this parameter
/// to the identifier of the Amazon VPC subnet where you want the job flow to launch.
/// If you do not specify this value, the job flow is launched in the normal Amazon Web
/// Services cloud, outside of an Amazon VPC.
/// </para>
///
/// <para>
/// Amazon VPC currently does not support cluster compute quadruple extra large (cc1.4xlarge)
/// instances. Thus you cannot specify the cc1.4xlarge instance type for nodes of a job
/// flow launched in a Amazon VPC.
/// </para>
/// </summary>
public string Ec2SubnetId
{
get { return this._ec2SubnetId; }
set { this._ec2SubnetId = value; }
}
// Check to see if Ec2SubnetId property is set
internal bool IsSetEc2SubnetId()
{
return this._ec2SubnetId != null;
}
/// <summary>
/// Gets and sets the property EmrManagedMasterSecurityGroup.
/// <para>
/// The identifier of the Amazon EC2 security group (managed by Amazon ElasticMapReduce)
/// for the master node.
/// </para>
/// </summary>
public string EmrManagedMasterSecurityGroup
{
get { return this._emrManagedMasterSecurityGroup; }
set { this._emrManagedMasterSecurityGroup = value; }
}
// Check to see if EmrManagedMasterSecurityGroup property is set
internal bool IsSetEmrManagedMasterSecurityGroup()
{
return this._emrManagedMasterSecurityGroup != null;
}
/// <summary>
/// Gets and sets the property EmrManagedSlaveSecurityGroup.
/// <para>
/// The identifier of the Amazon EC2 security group (managed by Amazon ElasticMapReduce)
/// for the slave nodes.
/// </para>
/// </summary>
public string EmrManagedSlaveSecurityGroup
{
get { return this._emrManagedSlaveSecurityGroup; }
set { this._emrManagedSlaveSecurityGroup = value; }
}
// Check to see if EmrManagedSlaveSecurityGroup property is set
internal bool IsSetEmrManagedSlaveSecurityGroup()
{
return this._emrManagedSlaveSecurityGroup != null;
}
/// <summary>
/// Gets and sets the property HadoopVersion.
/// <para>
/// The Hadoop version for the job flow. Valid inputs are "0.18" (deprecated), "0.20"
/// (deprecated), "0.20.205" (deprecated), "1.0.3", "2.2.0", or "2.4.0". If you do not
/// set this value, the default of 0.18 is used, unless the AmiVersion parameter is set
/// in the RunJobFlow call, in which case the default version of Hadoop for that AMI version
/// is used.
/// </para>
/// </summary>
public string HadoopVersion
{
get { return this._hadoopVersion; }
set { this._hadoopVersion = value; }
}
// Check to see if HadoopVersion property is set
internal bool IsSetHadoopVersion()
{
return this._hadoopVersion != null;
}
/// <summary>
/// Gets and sets the property InstanceCount.
/// <para>
/// The number of Amazon EC2 instances used to execute the job flow.
/// </para>
/// </summary>
public int InstanceCount
{
get { return this._instanceCount.GetValueOrDefault(); }
set { this._instanceCount = value; }
}
// Check to see if InstanceCount property is set
internal bool IsSetInstanceCount()
{
return this._instanceCount.HasValue;
}
/// <summary>
/// Gets and sets the property InstanceGroups.
/// <para>
/// Configuration for the job flow's instance groups.
/// </para>
/// </summary>
public List<InstanceGroupConfig> InstanceGroups
{
get { return this._instanceGroups; }
set { this._instanceGroups = value; }
}
// Check to see if InstanceGroups property is set
internal bool IsSetInstanceGroups()
{
return this._instanceGroups != null && this._instanceGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property KeepJobFlowAliveWhenNoSteps.
/// <para>
/// Specifies whether the job flow should be kept alive after completing all steps.
/// </para>
/// </summary>
public bool KeepJobFlowAliveWhenNoSteps
{
get { return this._keepJobFlowAliveWhenNoSteps.GetValueOrDefault(); }
set { this._keepJobFlowAliveWhenNoSteps = value; }
}
// Check to see if KeepJobFlowAliveWhenNoSteps property is set
internal bool IsSetKeepJobFlowAliveWhenNoSteps()
{
return this._keepJobFlowAliveWhenNoSteps.HasValue;
}
/// <summary>
/// Gets and sets the property MasterInstanceType.
/// <para>
/// The EC2 instance type of the master node.
/// </para>
/// </summary>
public string MasterInstanceType
{
get { return this._masterInstanceType; }
set { this._masterInstanceType = value; }
}
// Check to see if MasterInstanceType property is set
internal bool IsSetMasterInstanceType()
{
return this._masterInstanceType != null;
}
/// <summary>
/// Gets and sets the property Placement.
/// <para>
/// The Availability Zone the job flow will run in.
/// </para>
/// </summary>
public PlacementType Placement
{
get { return this._placement; }
set { this._placement = value; }
}
// Check to see if Placement property is set
internal bool IsSetPlacement()
{
return this._placement != null;
}
/// <summary>
/// Gets and sets the property SlaveInstanceType.
/// <para>
/// The EC2 instance type of the slave nodes.
/// </para>
/// </summary>
public string SlaveInstanceType
{
get { return this._slaveInstanceType; }
set { this._slaveInstanceType = value; }
}
// Check to see if SlaveInstanceType property is set
internal bool IsSetSlaveInstanceType()
{
return this._slaveInstanceType != null;
}
/// <summary>
/// Gets and sets the property TerminationProtected.
/// <para>
/// Specifies whether to lock the job flow to prevent the Amazon EC2 instances from being
/// terminated by API call, user intervention, or in the event of a job flow error.
/// </para>
/// </summary>
public bool TerminationProtected
{
get { return this._terminationProtected.GetValueOrDefault(); }
set { this._terminationProtected = value; }
}
// Check to see if TerminationProtected property is set
internal bool IsSetTerminationProtected()
{
return this._terminationProtected.HasValue;
}
}
}
| |
//
// Frame.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.ComponentModel;
using Xwt.Drawing;
using System.Windows.Markup;
namespace Xwt
{
[BackendType (typeof(IFrameBackend))]
[ContentProperty("Content")]
public class Frame: Widget
{
Widget child;
WidgetSpacing borderWidth;
WidgetSpacing padding;
FrameType type;
protected new class WidgetBackendHost: Widget.WidgetBackendHost, IFrameEventSink
{
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
IFrameBackend Backend {
get { return (IFrameBackend)BackendHost.Backend; }
}
public Frame ()
{
}
public Frame (FrameType frameType)
{
VerifyConstructorCall (this);
Type = frameType;
}
public Frame (Widget content)
{
VerifyConstructorCall (this);
Content = content;
}
[Obsolete ("Use Xwt.FrameBox")]
public Frame (Widget content, FrameType frameType)
{
VerifyConstructorCall (this);
Type = frameType;
Content = content;
}
[Obsolete ("Use Xwt.FrameBox")]
[DefaultValue (FrameType.WidgetBox)]
public FrameType Type {
get { return type; }
set { type = value; Backend.SetFrameType (type); }
}
[DefaultValue (null)]
public string Label {
get { return Backend.Label; }
set { Backend.Label = value; }
}
public WidgetSpacing Padding {
get { return padding; }
set {
padding = value;
UpdatePadding ();
}
}
[DefaultValue (0d)]
public double PaddingLeft {
get { return padding.Left; }
set {
padding.Left = value;
UpdatePadding ();
}
}
[DefaultValue (0d)]
public double PaddingRight {
get { return padding.Right; }
set {
padding.Right = value;
UpdatePadding ();
}
}
[DefaultValue (0d)]
public double PaddingTop {
get { return padding.Top; }
set {
padding.Top = value;
UpdatePadding ();
}
}
[DefaultValue (0d)]
public double PaddingBottom {
get { return padding.Bottom; }
set {
padding.Bottom = value;
UpdatePadding ();
}
}
void UpdatePadding ()
{
Backend.SetPadding (padding.Left, padding.Right, padding.Top, padding.Bottom);
OnPreferredSizeChanged ();
}
[Obsolete ("Use Xwt.FrameBox")]
public WidgetSpacing BorderWidth {
get { return borderWidth; }
set {
borderWidth = value;
UpdateBorderWidth ();
}
}
[Obsolete ("Use Xwt.FrameBox")]
[DefaultValue (0d)]
public double BorderWidthLeft {
get { return borderWidth.Left; }
set {
borderWidth.Left = value;
UpdateBorderWidth ();
}
}
[Obsolete ("Use Xwt.FrameBox")]
[DefaultValue (0d)]
public double BorderWidthRight {
get { return borderWidth.Right; }
set {
borderWidth.Right = value;
UpdateBorderWidth ();
}
}
[Obsolete ("Use Xwt.FrameBox")]
[DefaultValue (0d)]
public double BorderWidthTop {
get { return borderWidth.Top; }
set {
borderWidth.Top = value;
UpdateBorderWidth ();
}
}
[Obsolete ("Use Xwt.FrameBox")]
[DefaultValue (0d)]
public double BorderWidthBottom {
get { return borderWidth.Bottom; }
set {
borderWidth.Bottom = value;
UpdateBorderWidth ();
}
}
void UpdateBorderWidth ()
{
Backend.SetBorderSize (borderWidth.Left, borderWidth.Right, borderWidth.Top, borderWidth.Bottom);
OnPreferredSizeChanged ();
}
[Obsolete ("Use Xwt.FrameBox")]
public Color BorderColor {
get { return Backend.BorderColor; }
set { Backend.BorderColor = value; }
}
/// <summary>
/// Removes all children of the Frame
/// </summary>
public void Clear ()
{
Content = null;
}
[DefaultValue (null)]
public new Widget Content {
get { return child; }
set {
if (child != null)
UnregisterChild (child);
child = value;
if (child != null)
RegisterChild (child);
Backend.SetContent ((IWidgetBackend)GetBackend (child));
OnPreferredSizeChanged ();
}
}
}
public enum FrameType
{
Custom,
WidgetBox
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Globalization;
namespace Lucene.Net.Support
{
/// <summary>
/// A simple class for number conversions.
/// </summary>
public class Number
{
/// <summary>
/// Min radix value.
/// </summary>
public const int MIN_RADIX = 2;
/// <summary>
/// Max radix value.
/// </summary>
public const int MAX_RADIX = 36;
private const System.String digits = "0123456789abcdefghijklmnopqrstuvwxyz";
/// <summary>
/// Converts a number to System.String.
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public static System.String ToString(long number)
{
System.Text.StringBuilder s = new System.Text.StringBuilder();
if (number == 0)
{
s.Append("0");
}
else
{
if (number < 0)
{
s.Append("-");
number = -number;
}
while (number > 0)
{
char c = digits[(int)number % 36];
s.Insert(0, c);
number = number / 36;
}
}
return s.ToString();
}
/// <summary>
/// Converts a number to System.String.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static System.String ToString(float f)
{
if (((float)(int)f) == f)
{
return ((int)f).ToString() + ".0";
}
else
{
return f.ToString(NumberFormatInfo.InvariantInfo);
}
}
/// <summary>
/// Converts a number to System.String in the specified radix.
/// </summary>
/// <param name="i">A number to be converted.</param>
/// <param name="radix">A radix.</param>
/// <returns>A System.String representation of the number in the specified redix.</returns>
public static System.String ToString(long i, int radix)
{
if (radix < MIN_RADIX || radix > MAX_RADIX)
radix = 10;
char[] buf = new char[65];
int charPos = 64;
bool negative = (i < 0);
if (!negative)
{
i = -i;
}
while (i <= -radix)
{
buf[charPos--] = digits[(int)(-(i % radix))];
i = i / radix;
}
buf[charPos] = digits[(int)(-i)];
if (negative)
{
buf[--charPos] = '-';
}
return new System.String(buf, charPos, (65 - charPos));
}
/// <summary>
/// Parses a number in the specified radix.
/// </summary>
/// <param name="s">An input System.String.</param>
/// <param name="radix">A radix.</param>
/// <returns>The parsed number in the specified radix.</returns>
public static long Parse(System.String s, int radix)
{
if (s == null)
{
throw new ArgumentException("null");
}
if (radix < MIN_RADIX)
{
throw new NotSupportedException("radix " + radix +
" less than Number.MIN_RADIX");
}
if (radix > MAX_RADIX)
{
throw new NotSupportedException("radix " + radix +
" greater than Number.MAX_RADIX");
}
long result = 0;
long mult = 1;
s = s.ToLower();
for (int i = s.Length - 1; i >= 0; i--)
{
int weight = digits.IndexOf(s[i]);
if (weight == -1)
throw new FormatException("Invalid number for the specified radix");
result += (weight * mult);
mult *= radix;
}
return result;
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, int bits)
{
return (int)(((uint)number) >> bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, int bits)
{
return (long)(((ulong)number) >> bits);
}
/// <summary>
/// Returns the index of the first bit that is set to true that occurs
/// on or after the specified starting index. If no such bit exists
/// then -1 is returned.
/// </summary>
/// <param name="bits">The BitArray object.</param>
/// <param name="fromIndex">The index to start checking from (inclusive).</param>
/// <returns>The index of the next set bit.</returns>
public static int NextSetBit(System.Collections.BitArray bits, int fromIndex)
{
for (int i = fromIndex; i < bits.Length; i++)
{
if (bits[i] == true)
{
return i;
}
}
return -1;
}
/// <summary>
/// Converts a System.String number to long.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static long ToInt64(System.String s)
{
long number = 0;
long factor;
// handle negative number
if (s.StartsWith("-"))
{
s = s.Substring(1);
factor = -1;
}
else
{
factor = 1;
}
// generate number
for (int i = s.Length - 1; i > -1; i--)
{
int n = digits.IndexOf(s[i]);
// not supporting fractional or scientific notations
if (n < 0)
throw new System.ArgumentException("Invalid or unsupported character in number: " + s[i]);
number += (n * factor);
factor *= 36;
}
return number;
}
}
}
| |
// 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.Threading.Tasks;
using System.Xml.Schema;
namespace System.Xml
{
internal class XmlAsyncCheckReader : XmlReader
{
private readonly XmlReader _coreReader = null;
private Task _lastTask = Task.CompletedTask;
internal XmlReader CoreReader
{
get
{
return _coreReader;
}
}
public static XmlAsyncCheckReader CreateAsyncCheckWrapper(XmlReader reader)
{
if (reader is IXmlLineInfo)
{
if (reader is IXmlNamespaceResolver)
{
if (reader is IXmlSchemaInfo)
{
return new XmlAsyncCheckReaderWithLineInfoNSSchema(reader);
}
return new XmlAsyncCheckReaderWithLineInfoNS(reader);
}
Debug.Assert(!(reader is IXmlSchemaInfo));
return new XmlAsyncCheckReaderWithLineInfo(reader);
}
else if (reader is IXmlNamespaceResolver)
{
Debug.Assert(!(reader is IXmlSchemaInfo));
return new XmlAsyncCheckReaderWithNS(reader);
}
Debug.Assert(!(reader is IXmlSchemaInfo));
return new XmlAsyncCheckReader(reader);
}
public XmlAsyncCheckReader(XmlReader reader)
{
_coreReader = reader;
}
private void CheckAsync()
{
if (!_lastTask.IsCompleted)
{
throw new InvalidOperationException(SR.Xml_AsyncIsRunningException);
}
}
#region Sync Methods, Properties Check
public override XmlReaderSettings Settings
{
get
{
XmlReaderSettings settings = _coreReader.Settings;
if (null != settings)
{
settings = settings.Clone();
}
else
{
settings = new XmlReaderSettings();
}
settings.Async = true;
settings.ReadOnly = true;
return settings;
}
}
public override XmlNodeType NodeType
{
get
{
CheckAsync();
return _coreReader.NodeType;
}
}
public override string Name
{
get
{
CheckAsync();
return _coreReader.Name;
}
}
public override string LocalName
{
get
{
CheckAsync();
return _coreReader.LocalName;
}
}
public override string NamespaceURI
{
get
{
CheckAsync();
return _coreReader.NamespaceURI;
}
}
public override string Prefix
{
get
{
CheckAsync();
return _coreReader.Prefix;
}
}
public override bool HasValue
{
get
{
CheckAsync();
return _coreReader.HasValue;
}
}
public override string Value
{
get
{
CheckAsync();
return _coreReader.Value;
}
}
public override int Depth
{
get
{
CheckAsync();
return _coreReader.Depth;
}
}
public override string BaseURI
{
get
{
CheckAsync();
return _coreReader.BaseURI;
}
}
public override bool IsEmptyElement
{
get
{
CheckAsync();
return _coreReader.IsEmptyElement;
}
}
public override bool IsDefault
{
get
{
CheckAsync();
return _coreReader.IsDefault;
}
}
public override char QuoteChar
{
get
{
CheckAsync();
return _coreReader.QuoteChar;
}
}
public override XmlSpace XmlSpace
{
get
{
CheckAsync();
return _coreReader.XmlSpace;
}
}
public override string XmlLang
{
get
{
CheckAsync();
return _coreReader.XmlLang;
}
}
public override IXmlSchemaInfo SchemaInfo
{
get
{
CheckAsync();
return _coreReader.SchemaInfo;
}
}
public override System.Type ValueType
{
get
{
CheckAsync();
return _coreReader.ValueType;
}
}
public override object ReadContentAsObject()
{
CheckAsync();
return _coreReader.ReadContentAsObject();
}
public override bool ReadContentAsBoolean()
{
CheckAsync();
return _coreReader.ReadContentAsBoolean();
}
public override DateTime ReadContentAsDateTime()
{
CheckAsync();
return _coreReader.ReadContentAsDateTime();
}
public override double ReadContentAsDouble()
{
CheckAsync();
return _coreReader.ReadContentAsDouble();
}
public override float ReadContentAsFloat()
{
CheckAsync();
return _coreReader.ReadContentAsFloat();
}
public override decimal ReadContentAsDecimal()
{
CheckAsync();
return _coreReader.ReadContentAsDecimal();
}
public override int ReadContentAsInt()
{
CheckAsync();
return _coreReader.ReadContentAsInt();
}
public override long ReadContentAsLong()
{
CheckAsync();
return _coreReader.ReadContentAsLong();
}
public override string ReadContentAsString()
{
CheckAsync();
return _coreReader.ReadContentAsString();
}
public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
CheckAsync();
return _coreReader.ReadContentAs(returnType, namespaceResolver);
}
public override object ReadElementContentAsObject()
{
CheckAsync();
return _coreReader.ReadElementContentAsObject();
}
public override object ReadElementContentAsObject(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadElementContentAsObject(localName, namespaceURI);
}
public override bool ReadElementContentAsBoolean()
{
CheckAsync();
return _coreReader.ReadElementContentAsBoolean();
}
public override bool ReadElementContentAsBoolean(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadElementContentAsBoolean(localName, namespaceURI);
}
public override DateTime ReadElementContentAsDateTime()
{
CheckAsync();
return _coreReader.ReadElementContentAsDateTime();
}
public override DateTime ReadElementContentAsDateTime(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadElementContentAsDateTime(localName, namespaceURI);
}
public override DateTimeOffset ReadContentAsDateTimeOffset()
{
CheckAsync();
return _coreReader.ReadContentAsDateTimeOffset();
}
public override double ReadElementContentAsDouble()
{
CheckAsync();
return _coreReader.ReadElementContentAsDouble();
}
public override double ReadElementContentAsDouble(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadElementContentAsDouble(localName, namespaceURI);
}
public override float ReadElementContentAsFloat()
{
CheckAsync();
return _coreReader.ReadElementContentAsFloat();
}
public override float ReadElementContentAsFloat(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadElementContentAsFloat(localName, namespaceURI);
}
public override decimal ReadElementContentAsDecimal()
{
CheckAsync();
return _coreReader.ReadElementContentAsDecimal();
}
public override decimal ReadElementContentAsDecimal(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadElementContentAsDecimal(localName, namespaceURI);
}
public override int ReadElementContentAsInt()
{
CheckAsync();
return _coreReader.ReadElementContentAsInt();
}
public override int ReadElementContentAsInt(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadElementContentAsInt(localName, namespaceURI);
}
public override long ReadElementContentAsLong()
{
CheckAsync();
return _coreReader.ReadElementContentAsLong();
}
public override long ReadElementContentAsLong(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadElementContentAsLong(localName, namespaceURI);
}
public override string ReadElementContentAsString()
{
CheckAsync();
return _coreReader.ReadElementContentAsString();
}
public override string ReadElementContentAsString(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadElementContentAsString(localName, namespaceURI);
}
public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
CheckAsync();
return _coreReader.ReadElementContentAs(returnType, namespaceResolver);
}
public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadElementContentAs(returnType, namespaceResolver, localName, namespaceURI);
}
public override int AttributeCount
{
get
{
CheckAsync();
return _coreReader.AttributeCount;
}
}
public override string GetAttribute(string name)
{
CheckAsync();
return _coreReader.GetAttribute(name);
}
public override string GetAttribute(string name, string namespaceURI)
{
CheckAsync();
return _coreReader.GetAttribute(name, namespaceURI);
}
public override string GetAttribute(int i)
{
CheckAsync();
return _coreReader.GetAttribute(i);
}
public override string this[int i]
{
get
{
CheckAsync();
return _coreReader[i];
}
}
public override string this[string name]
{
get
{
CheckAsync();
return _coreReader[name];
}
}
public override string this[string name, string namespaceURI]
{
get
{
CheckAsync();
return _coreReader[name, namespaceURI];
}
}
public override bool MoveToAttribute(string name)
{
CheckAsync();
return _coreReader.MoveToAttribute(name);
}
public override bool MoveToAttribute(string name, string ns)
{
CheckAsync();
return _coreReader.MoveToAttribute(name, ns);
}
public override void MoveToAttribute(int i)
{
CheckAsync();
_coreReader.MoveToAttribute(i);
}
public override bool MoveToFirstAttribute()
{
CheckAsync();
return _coreReader.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute()
{
CheckAsync();
return _coreReader.MoveToNextAttribute();
}
public override bool MoveToElement()
{
CheckAsync();
return _coreReader.MoveToElement();
}
public override bool ReadAttributeValue()
{
CheckAsync();
return _coreReader.ReadAttributeValue();
}
public override bool Read()
{
CheckAsync();
return _coreReader.Read();
}
public override bool EOF
{
get
{
CheckAsync();
return _coreReader.EOF;
}
}
public override void Close()
{
CheckAsync();
_coreReader.Close();
}
public override ReadState ReadState
{
get
{
CheckAsync();
return _coreReader.ReadState;
}
}
public override void Skip()
{
CheckAsync();
_coreReader.Skip();
}
public override XmlNameTable NameTable
{
get
{
CheckAsync();
return _coreReader.NameTable;
}
}
public override string LookupNamespace(string prefix)
{
CheckAsync();
return _coreReader.LookupNamespace(prefix);
}
public override bool CanResolveEntity
{
get
{
CheckAsync();
return _coreReader.CanResolveEntity;
}
}
public override void ResolveEntity()
{
CheckAsync();
_coreReader.ResolveEntity();
}
public override bool CanReadBinaryContent
{
get
{
CheckAsync();
return _coreReader.CanReadBinaryContent;
}
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
CheckAsync();
return _coreReader.ReadContentAsBase64(buffer, index, count);
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
CheckAsync();
return _coreReader.ReadElementContentAsBase64(buffer, index, count);
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
CheckAsync();
return _coreReader.ReadContentAsBinHex(buffer, index, count);
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
CheckAsync();
return _coreReader.ReadElementContentAsBinHex(buffer, index, count);
}
public override bool CanReadValueChunk
{
get
{
CheckAsync();
return _coreReader.CanReadValueChunk;
}
}
public override int ReadValueChunk(char[] buffer, int index, int count)
{
CheckAsync();
return _coreReader.ReadValueChunk(buffer, index, count);
}
public override string ReadString()
{
CheckAsync();
return _coreReader.ReadString();
}
public override XmlNodeType MoveToContent()
{
CheckAsync();
return _coreReader.MoveToContent();
}
public override void ReadStartElement()
{
CheckAsync();
_coreReader.ReadStartElement();
}
public override void ReadStartElement(string name)
{
CheckAsync();
_coreReader.ReadStartElement(name);
}
public override void ReadStartElement(string localname, string ns)
{
CheckAsync();
_coreReader.ReadStartElement(localname, ns);
}
public override string ReadElementString()
{
CheckAsync();
return _coreReader.ReadElementString();
}
public override string ReadElementString(string name)
{
CheckAsync();
return _coreReader.ReadElementString(name);
}
public override string ReadElementString(string localname, string ns)
{
CheckAsync();
return _coreReader.ReadElementString(localname, ns);
}
public override void ReadEndElement()
{
CheckAsync();
_coreReader.ReadEndElement();
}
public override bool IsStartElement()
{
CheckAsync();
return _coreReader.IsStartElement();
}
public override bool IsStartElement(string name)
{
CheckAsync();
return _coreReader.IsStartElement(name);
}
public override bool IsStartElement(string localname, string ns)
{
CheckAsync();
return _coreReader.IsStartElement(localname, ns);
}
public override bool ReadToFollowing(string name)
{
CheckAsync();
return _coreReader.ReadToFollowing(name);
}
public override bool ReadToFollowing(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadToFollowing(localName, namespaceURI);
}
public override bool ReadToDescendant(string name)
{
CheckAsync();
return _coreReader.ReadToDescendant(name);
}
public override bool ReadToDescendant(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadToDescendant(localName, namespaceURI);
}
public override bool ReadToNextSibling(string name)
{
CheckAsync();
return _coreReader.ReadToNextSibling(name);
}
public override bool ReadToNextSibling(string localName, string namespaceURI)
{
CheckAsync();
return _coreReader.ReadToNextSibling(localName, namespaceURI);
}
public override string ReadInnerXml()
{
CheckAsync();
return _coreReader.ReadInnerXml();
}
public override string ReadOuterXml()
{
CheckAsync();
return _coreReader.ReadOuterXml();
}
public override XmlReader ReadSubtree()
{
CheckAsync();
XmlReader subtreeReader = _coreReader.ReadSubtree();
return CreateAsyncCheckWrapper(subtreeReader);
}
public override bool HasAttributes
{
get
{
CheckAsync();
return _coreReader.HasAttributes;
}
}
protected override void Dispose(bool disposing)
{
CheckAsync();
//since it is protected method, we can't call coreReader.Dispose(disposing).
//Internal, it is always called to Dispose(true). So call coreReader.Dispose() is OK.
_coreReader.Dispose();
}
internal override XmlNamespaceManager NamespaceManager
{
get
{
CheckAsync();
return _coreReader.NamespaceManager;
}
}
internal override IDtdInfo DtdInfo
{
get
{
CheckAsync();
return _coreReader.DtdInfo;
}
}
#endregion
#region Async Methods
public override Task<string> GetValueAsync()
{
CheckAsync();
var task = _coreReader.GetValueAsync();
_lastTask = task;
return task;
}
public override Task<object> ReadContentAsObjectAsync()
{
CheckAsync();
var task = _coreReader.ReadContentAsObjectAsync();
_lastTask = task;
return task;
}
public override Task<string> ReadContentAsStringAsync()
{
CheckAsync();
var task = _coreReader.ReadContentAsStringAsync();
_lastTask = task;
return task;
}
public override Task<object> ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
CheckAsync();
var task = _coreReader.ReadContentAsAsync(returnType, namespaceResolver);
_lastTask = task;
return task;
}
public override Task<object> ReadElementContentAsObjectAsync()
{
CheckAsync();
var task = _coreReader.ReadElementContentAsObjectAsync();
_lastTask = task;
return task;
}
public override Task<string> ReadElementContentAsStringAsync()
{
CheckAsync();
var task = _coreReader.ReadElementContentAsStringAsync();
_lastTask = task;
return task;
}
public override Task<object> ReadElementContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
CheckAsync();
var task = _coreReader.ReadElementContentAsAsync(returnType, namespaceResolver);
_lastTask = task;
return task;
}
public override Task<bool> ReadAsync()
{
CheckAsync();
var task = _coreReader.ReadAsync();
_lastTask = task;
return task;
}
public override Task SkipAsync()
{
CheckAsync();
var task = _coreReader.SkipAsync();
_lastTask = task;
return task;
}
public override Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count)
{
CheckAsync();
var task = _coreReader.ReadContentAsBase64Async(buffer, index, count);
_lastTask = task;
return task;
}
public override Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count)
{
CheckAsync();
var task = _coreReader.ReadElementContentAsBase64Async(buffer, index, count);
_lastTask = task;
return task;
}
public override Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count)
{
CheckAsync();
var task = _coreReader.ReadContentAsBinHexAsync(buffer, index, count);
_lastTask = task;
return task;
}
public override Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count)
{
CheckAsync();
var task = _coreReader.ReadElementContentAsBinHexAsync(buffer, index, count);
_lastTask = task;
return task;
}
public override Task<int> ReadValueChunkAsync(char[] buffer, int index, int count)
{
CheckAsync();
var task = _coreReader.ReadValueChunkAsync(buffer, index, count);
_lastTask = task;
return task;
}
public override Task<XmlNodeType> MoveToContentAsync()
{
CheckAsync();
var task = _coreReader.MoveToContentAsync();
_lastTask = task;
return task;
}
public override Task<string> ReadInnerXmlAsync()
{
CheckAsync();
var task = _coreReader.ReadInnerXmlAsync();
_lastTask = task;
return task;
}
public override Task<string> ReadOuterXmlAsync()
{
CheckAsync();
var task = _coreReader.ReadOuterXmlAsync();
_lastTask = task;
return task;
}
#endregion
}
internal class XmlAsyncCheckReaderWithNS : XmlAsyncCheckReader, IXmlNamespaceResolver
{
private readonly IXmlNamespaceResolver _readerAsIXmlNamespaceResolver;
public XmlAsyncCheckReaderWithNS(XmlReader reader)
: base(reader)
{
_readerAsIXmlNamespaceResolver = (IXmlNamespaceResolver)reader;
}
#region IXmlNamespaceResolver members
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return _readerAsIXmlNamespaceResolver.GetNamespacesInScope(scope);
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return _readerAsIXmlNamespaceResolver.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _readerAsIXmlNamespaceResolver.LookupPrefix(namespaceName);
}
#endregion
}
internal class XmlAsyncCheckReaderWithLineInfo : XmlAsyncCheckReader, IXmlLineInfo
{
private readonly IXmlLineInfo _readerAsIXmlLineInfo;
public XmlAsyncCheckReaderWithLineInfo(XmlReader reader)
: base(reader)
{
_readerAsIXmlLineInfo = (IXmlLineInfo)reader;
}
#region IXmlLineInfo members
public virtual bool HasLineInfo()
{
return _readerAsIXmlLineInfo.HasLineInfo();
}
public virtual int LineNumber
{
get
{
return _readerAsIXmlLineInfo.LineNumber;
}
}
public virtual int LinePosition
{
get
{
return _readerAsIXmlLineInfo.LinePosition;
}
}
#endregion
}
internal class XmlAsyncCheckReaderWithLineInfoNS : XmlAsyncCheckReaderWithLineInfo, IXmlNamespaceResolver
{
private readonly IXmlNamespaceResolver _readerAsIXmlNamespaceResolver;
public XmlAsyncCheckReaderWithLineInfoNS(XmlReader reader)
: base(reader)
{
_readerAsIXmlNamespaceResolver = (IXmlNamespaceResolver)reader;
}
#region IXmlNamespaceResolver members
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return _readerAsIXmlNamespaceResolver.GetNamespacesInScope(scope);
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return _readerAsIXmlNamespaceResolver.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _readerAsIXmlNamespaceResolver.LookupPrefix(namespaceName);
}
#endregion
}
internal class XmlAsyncCheckReaderWithLineInfoNSSchema : XmlAsyncCheckReaderWithLineInfoNS, IXmlSchemaInfo
{
private readonly IXmlSchemaInfo _readerAsIXmlSchemaInfo;
public XmlAsyncCheckReaderWithLineInfoNSSchema(XmlReader reader)
: base(reader)
{
_readerAsIXmlSchemaInfo = (IXmlSchemaInfo)reader;
}
#region IXmlSchemaInfo members
XmlSchemaValidity IXmlSchemaInfo.Validity
{
get
{
return _readerAsIXmlSchemaInfo.Validity;
}
}
bool IXmlSchemaInfo.IsDefault
{
get
{
return _readerAsIXmlSchemaInfo.IsDefault;
}
}
bool IXmlSchemaInfo.IsNil
{
get
{
return _readerAsIXmlSchemaInfo.IsNil;
}
}
XmlSchemaSimpleType IXmlSchemaInfo.MemberType
{
get
{
return _readerAsIXmlSchemaInfo.MemberType;
}
}
XmlSchemaType IXmlSchemaInfo.SchemaType
{
get
{
return _readerAsIXmlSchemaInfo.SchemaType;
}
}
XmlSchemaElement IXmlSchemaInfo.SchemaElement
{
get
{
return _readerAsIXmlSchemaInfo.SchemaElement;
}
}
XmlSchemaAttribute IXmlSchemaInfo.SchemaAttribute
{
get
{
return _readerAsIXmlSchemaInfo.SchemaAttribute;
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#region
using System;
using System.Collections.Generic;
using System.Linq;
using NLog.Config;
using NLog.Targets;
using Xunit;
#endregion
namespace NLog.UnitTests.Config
{
public class ConfigApiTests
{
[Fact]
public void AddTarget_testname()
{
var config = new LoggingConfiguration();
config.AddTarget("name1", new FileTarget { Name = "File" });
var allTargets = config.AllTargets;
Assert.NotNull(allTargets);
Assert.Single(allTargets);
//maybe confusing, but the name of the target is not changed, only the one of the key.
Assert.Equal("File", allTargets.First().Name);
Assert.NotNull(config.FindTargetByName<FileTarget>("name1"));
config.RemoveTarget("name1");
allTargets = config.AllTargets;
Assert.Empty(allTargets);
}
[Fact]
public void AddTarget_WithName_NullNameParam()
{
var config = new LoggingConfiguration();
Exception ex = Assert.Throws<ArgumentException>(() => config.AddTarget(name: null, target: new FileTarget { Name = "name1" }));
}
[Fact]
public void AddTarget_WithName_NullTargetParam()
{
var config = new LoggingConfiguration();
Exception ex = Assert.Throws<ArgumentNullException>(() => config.AddTarget(name: "Name1", target: null));
}
[Fact]
public void AddTarget_TargetOnly_NullParam()
{
var config = new LoggingConfiguration();
Exception ex = Assert.Throws<ArgumentNullException>(() => config.AddTarget(target: null));
}
[Fact]
public void AddTarget_testname_param()
{
var config = new LoggingConfiguration();
config.AddTarget("name1", new FileTarget { Name = "name2" });
var allTargets = config.AllTargets;
Assert.NotNull(allTargets);
Assert.Single(allTargets);
//maybe confusing, but the name of the target is not changed, only the one of the key.
Assert.Equal("name2", allTargets.First().Name);
Assert.NotNull(config.FindTargetByName<FileTarget>("name1"));
}
[Fact]
public void AddTarget_testname_fromtarget()
{
var config = new LoggingConfiguration();
config.AddTarget(new FileTarget { Name = "name2" });
var allTargets = config.AllTargets;
Assert.NotNull(allTargets);
Assert.Single(allTargets);
Assert.Equal("name2", allTargets.First().Name);
Assert.NotNull(config.FindTargetByName<FileTarget>("name2"));
}
[Fact]
public void AddRule_min_max()
{
var config = new LoggingConfiguration();
config.AddTarget(new FileTarget { Name = "File" });
config.AddRule(LogLevel.Info, LogLevel.Error, "File", "*a");
Assert.NotNull(config.LoggingRules);
Assert.Equal(1, config.LoggingRules.Count);
var rule1 = config.LoggingRules.FirstOrDefault();
Assert.NotNull(rule1);
Assert.False(rule1.Final);
Assert.Equal("*a", rule1.LoggerNamePattern);
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Fatal));
Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Error));
Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Warn));
Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Info));
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Debug));
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Trace));
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Off));
}
[Fact]
public void AddRule_all()
{
var config = new LoggingConfiguration();
config.AddTarget(new FileTarget { Name = "File" });
config.AddRuleForAllLevels("File", "*a");
Assert.NotNull(config.LoggingRules);
Assert.Equal(1, config.LoggingRules.Count);
var rule1 = config.LoggingRules.FirstOrDefault();
Assert.NotNull(rule1);
Assert.False(rule1.Final);
Assert.Equal("*a", rule1.LoggerNamePattern);
Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Fatal));
Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Error));
Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Warn));
Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Info));
Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Debug));
Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Trace));
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Off));
}
[Fact]
public void AddRule_onelevel()
{
var config = new LoggingConfiguration();
config.AddTarget(new FileTarget { Name = "File" });
config.AddRuleForOneLevel(LogLevel.Error, "File", "*a");
Assert.NotNull(config.LoggingRules);
Assert.Equal(1, config.LoggingRules.Count);
var rule1 = config.LoggingRules.FirstOrDefault();
Assert.NotNull(rule1);
Assert.False(rule1.Final);
Assert.Equal("*a", rule1.LoggerNamePattern);
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Fatal));
Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Error));
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Warn));
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Info));
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Debug));
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Trace));
Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Off));
}
[Fact]
public void AddRule_with_target()
{
var config = new LoggingConfiguration();
var fileTarget = new FileTarget { Name = "File" };
config.AddRuleForOneLevel(LogLevel.Error, fileTarget, "*a");
Assert.NotNull(config.LoggingRules);
Assert.Equal(1, config.LoggingRules.Count);
config.AddTarget(new FileTarget { Name = "File" });
var allTargets = config.AllTargets;
Assert.NotNull(allTargets);
Assert.Single(allTargets);
Assert.Equal("File", allTargets.First().Name);
Assert.NotNull(config.FindTargetByName<FileTarget>("File"));
}
[Fact]
public void AddRule_missingtarget()
{
var config = new LoggingConfiguration();
Assert.Throws<NLogConfigurationException>(() => config.AddRuleForOneLevel(LogLevel.Error, "File", "*a"));
}
[Fact]
public void CheckAllTargets()
{
var config = new LoggingConfiguration();
var fileTarget = new FileTarget { Name = "File", FileName = "file" };
config.AddRuleForOneLevel(LogLevel.Error, fileTarget, "*a");
config.AddTarget(fileTarget);
Assert.Single(config.AllTargets);
Assert.Equal(fileTarget, config.AllTargets[0]);
config.InitializeAll();
Assert.Single(config.AllTargets);
Assert.Equal(fileTarget, config.AllTargets[0]);
}
[Fact]
public void LogRuleToStringTest_min()
{
var target = new FileTarget { Name = "file1" };
var loggingRule = new LoggingRule("*", LogLevel.Error, target);
var s = loggingRule.ToString();
Assert.Equal("logNamePattern: (:All) levels: [ Error Fatal ] appendTo: [ file1 ]", s);
}
[Fact]
public void LogRuleToStringTest_minAndMax()
{
var target = new FileTarget { Name = "file1" };
var loggingRule = new LoggingRule("*", LogLevel.Debug, LogLevel.Error, target);
var s = loggingRule.ToString();
Assert.Equal("logNamePattern: (:All) levels: [ Debug Info Warn Error ] appendTo: [ file1 ]", s);
}
[Fact]
public void LogRuleToStringTest_none()
{
var target = new FileTarget { Name = "file1" };
var loggingRule = new LoggingRule("*", target);
var s = loggingRule.ToString();
Assert.Equal("logNamePattern: (:All) levels: [ ] appendTo: [ file1 ]", s);
}
[Fact]
public void LogRuleToStringTest_empty()
{
var target = new FileTarget { Name = "file1" };
var loggingRule = new LoggingRule("", target);
var s = loggingRule.ToString();
Assert.Equal("logNamePattern: (:Equals) levels: [ ] appendTo: [ file1 ]", s);
}
[Fact]
public void LogRuleToStringTest_filter()
{
var target = new FileTarget { Name = "file1" };
var loggingRule = new LoggingRule("namespace.comp1", target);
var s = loggingRule.ToString();
Assert.Equal("logNamePattern: (namespace.comp1:Equals) levels: [ ] appendTo: [ file1 ]", s);
}
[Fact]
public void LogRuleToStringTest_multiple_targets()
{
var target = new FileTarget { Name = "file1" };
var target2 = new FileTarget { Name = "file2" };
var loggingRule = new LoggingRule("namespace.comp1", target);
loggingRule.Targets.Add(target2);
var s = loggingRule.ToString();
Assert.Equal("logNamePattern: (namespace.comp1:Equals) levels: [ ] appendTo: [ file1 file2 ]", s);
}
[Fact]
public void LogRuleSetLoggingLevels_enables()
{
var rule = new LoggingRule();
rule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal);
Assert.Equal(rule.Levels, new[] { LogLevel.Warn, LogLevel.Error, LogLevel.Fatal });
}
[Fact]
public void LogRuleSetLoggingLevels_disables()
{
var rule = new LoggingRule();
rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel);
rule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal);
Assert.Equal(rule.Levels, new[] { LogLevel.Warn, LogLevel.Error, LogLevel.Fatal });
}
[Fact]
public void LogRuleSetLoggingLevels_off()
{
var rule = new LoggingRule();
rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel);
rule.SetLoggingLevels(LogLevel.Off, LogLevel.Off);
Assert.Equal(rule.Levels, new LogLevel[0]);
}
[Fact]
public void LogRuleDisableLoggingLevels()
{
var rule = new LoggingRule();
rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel);
rule.DisableLoggingForLevels(LogLevel.Warn, LogLevel.Fatal);
Assert.Equal(rule.Levels, new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info });
}
[Fact]
public void ConfigLogRuleWithName()
{
var config = new LoggingConfiguration();
var rule = new LoggingRule("hello");
config.LoggingRules.Add(rule);
var ruleLookup = config.FindRuleByName("hello");
Assert.Same(rule, ruleLookup);
Assert.True(config.RemoveRuleByName("hello"));
ruleLookup = config.FindRuleByName("hello");
Assert.Null(ruleLookup);
Assert.False(config.RemoveRuleByName("hello"));
}
[Fact]
public void FindRuleByName_AfterRename_FindNewOneAndDontFindOld()
{
// Arrange
var config = new LoggingConfiguration();
var rule = new LoggingRule("hello");
config.LoggingRules.Add(rule);
// Act
var foundRule1 = config.FindRuleByName("hello");
foundRule1.RuleName = "world";
var foundRule2 = config.FindRuleByName("hello");
var foundRule3 = config.FindRuleByName("world");
// Assert
Assert.Null(foundRule2);
Assert.NotNull(foundRule1);
Assert.Same(foundRule1, foundRule3);
}
[Fact]
public void LoggerNameMatcher_None()
{
var matcher = LoggerNameMatcher.Create(null);
Assert.Equal("logNamePattern: (:None)", matcher.ToString());
}
[Fact]
public void LoggerNameMatcher_All()
{
var matcher = LoggerNameMatcher.Create("*");
Assert.Equal("logNamePattern: (:All)", matcher.ToString());
}
[Fact]
public void LoggerNameMatcher_Empty()
{
var matcher = LoggerNameMatcher.Create("");
Assert.Equal("logNamePattern: (:Equals)", matcher.ToString());
}
[Fact]
public void LoggerNameMatcher_Equals()
{
var matcher = LoggerNameMatcher.Create("abc");
Assert.Equal("logNamePattern: (abc:Equals)", matcher.ToString());
}
[Fact]
public void LoggerNameMatcher_StartsWith()
{
var matcher = LoggerNameMatcher.Create("abc*");
Assert.Equal("logNamePattern: (abc:StartsWith)", matcher.ToString());
}
[Fact]
public void LoggerNameMatcher_EndsWith()
{
var matcher = LoggerNameMatcher.Create("*abc");
Assert.Equal("logNamePattern: (abc:EndsWith)", matcher.ToString());
}
[Fact]
public void LoggerNameMatcher_Contains()
{
var matcher = LoggerNameMatcher.Create("*abc*");
Assert.Equal("logNamePattern: (abc:Contains)", matcher.ToString());
}
[Fact]
public void LoggerNameMatcher_MultiplePattern_StarInternal()
{
var matcher = LoggerNameMatcher.Create("a*bc");
Assert.Equal("logNamePattern: (^a.*bc$:MultiplePattern)", matcher.ToString());
}
[Fact]
public void LoggerNameMatcher_MultiplePattern_QuestionMark()
{
var matcher = LoggerNameMatcher.Create("a?bc");
Assert.Equal("logNamePattern: (^a.bc$:MultiplePattern)", matcher.ToString());
}
[Fact]
public void LoggerNameMatcher_MultiplePattern_EscapedChars()
{
var matcher = LoggerNameMatcher.Create("a?b.c.foo.bar");
Assert.Equal("logNamePattern: (^a.b\\.c\\.foo\\.bar$:MultiplePattern)", matcher.ToString());
}
[Theory]
[InlineData(null, false)]
[InlineData("", false)]
[InlineData("foobar", false)]
public void LoggerNameMatcher_Matches_None(string name, bool result)
{
LoggerNameMatcher_Matches("None", null, name, result);
}
[Theory]
[InlineData(null, false)]
[InlineData("", false)]
[InlineData("foobar", false)]
[InlineData("A", false)]
[InlineData("a", true)]
public void LoggerNameMatcher_Matches_Equals(string name, bool result)
{
LoggerNameMatcher_Matches("Equals", "a", name, result);
}
[Theory]
[InlineData(null, false)]
[InlineData("", false)]
[InlineData("Foo", false)]
[InlineData("Foobar", false)]
[InlineData("foo", true)]
[InlineData("foobar", true)]
public void LoggerNameMatcher_Matches_StartsWith(string name, bool result)
{
LoggerNameMatcher_Matches("StartsWith", "foo*", name, result);
}
[Theory]
[InlineData(null, false)]
[InlineData("", false)]
[InlineData("Bar", false)]
[InlineData("fooBar", false)]
[InlineData("bar", true)]
[InlineData("foobar", true)]
public void LoggerNameMatcher_Matches_EndsWith(string name, bool result)
{
LoggerNameMatcher_Matches("EndsWith", "*bar", name, result);
}
[Theory]
[InlineData(null, false)]
[InlineData("", false)]
[InlineData("Bar", false)]
[InlineData("fooBar", false)]
[InlineData("Barbaz", false)]
[InlineData("fooBarbaz", false)]
[InlineData("bar", true)]
[InlineData("foobar", true)]
[InlineData("barbaz", true)]
[InlineData("foobarbaz", true)]
public void LoggerNameMatcher_Matches_Contains(string name, bool result)
{
LoggerNameMatcher_Matches("Contains", "*bar*", name, result);
}
[Theory]
[InlineData(null, false)]
[InlineData("", false)]
[InlineData("Server[123].connection[2].reader", false)]
[InlineData("server[123].connection[2].reader", true)]
[InlineData("server[123].connection[2].", true)]
[InlineData("server[123].connection[2]", false)]
[InlineData("server[123].connection[25].reader", false)]
[InlineData("server[].connection[2].reader", true)]
public void LoggerNameMatcher_Matches_MultiplePattern(string name, bool result)
{
LoggerNameMatcher_Matches("MultiplePattern", "server[*].connection[?].*", name, result);
}
[Theory]
[InlineData("MultiplePattern", "server[*].connection[??].*", "server[].connection[2].reader", false)]
[InlineData("MultiplePattern", "server[*].connection[??].*", "server[].connection[25].reader", true)]
[InlineData("MultiplePattern", "server[*].connection[??].*", "server[].connection[254].reader", false)]
public void LoggerNameMatcher_Matches(string matcherType, string pattern, string name, bool result)
{
var matcher = LoggerNameMatcher.Create(pattern);
Assert.Contains(":" + matcherType, matcher.ToString());
Assert.Equal(result, matcher.NameMatches(name));
}
}
}
| |
/*
* 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 log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Friends;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using OpenSim.Server.Base;
using OpenMetaverse;
namespace OpenSim.Services.Connectors.Hypergrid
{
public class HGFriendsServicesConnector : FriendsSimConnector
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
private string m_ServiceKey = String.Empty;
private UUID m_SessionID;
public HGFriendsServicesConnector()
{
}
public HGFriendsServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public HGFriendsServicesConnector(string serverURI, UUID sessionID, string serviceKey)
{
m_ServerURI = serverURI.TrimEnd('/');
m_ServiceKey = serviceKey;
m_SessionID = sessionID;
}
protected override string ServicePath()
{
return "hgfriends";
}
#region IFriendsService
public uint GetFriendPerms(UUID PrincipalID, UUID friendID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["PRINCIPALID"] = PrincipalID.ToString();
sendData["FRIENDID"] = friendID.ToString();
sendData["METHOD"] = "getfriendperms";
sendData["KEY"] = m_ServiceKey;
sendData["SESSIONID"] = m_SessionID.ToString();
string reqString = ServerUtils.BuildQueryString(sendData);
string uri = m_ServerURI + "/hgfriends";
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
reqString);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && replyData.ContainsKey("Value") && (replyData["Value"] != null))
{
uint perms = 0;
uint.TryParse(replyData["Value"].ToString(), out perms);
return perms;
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: GetFriendPerms {0} received null response",
PrincipalID);
}
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Exception when contacting friends server at {0}: {1}", uri, e.Message);
}
return 0;
}
public bool NewFriendship(UUID PrincipalID, string Friend)
{
FriendInfo finfo = new FriendInfo();
finfo.PrincipalID = PrincipalID;
finfo.Friend = Friend;
Dictionary<string, object> sendData = finfo.ToKeyValuePairs();
sendData["METHOD"] = "newfriendship";
sendData["KEY"] = m_ServiceKey;
sendData["SESSIONID"] = m_SessionID.ToString();
string reply = string.Empty;
string uri = m_ServerURI + "/hgfriends";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Exception when contacting friends server at {0}: {1}", uri, e.Message);
return false;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && replyData.ContainsKey("Result") && (replyData["Result"] != null))
{
bool success = false;
Boolean.TryParse(replyData["Result"].ToString(), out success);
return success;
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: StoreFriend {0} {1} received null response",
PrincipalID, Friend);
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: StoreFriend received null reply");
return false;
}
public bool DeleteFriendship(UUID PrincipalID, UUID Friend, string secret)
{
FriendInfo finfo = new FriendInfo();
finfo.PrincipalID = PrincipalID;
finfo.Friend = Friend.ToString();
Dictionary<string, object> sendData = finfo.ToKeyValuePairs();
sendData["METHOD"] = "deletefriendship";
sendData["SECRET"] = secret;
string reply = string.Empty;
string uri = m_ServerURI + "/hgfriends";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Exception when contacting friends server at {0}: {1}", uri, e.Message);
return false;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("RESULT"))
{
if (replyData["RESULT"].ToString().ToLower() == "true")
return true;
else
return false;
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: reply data does not contain result field");
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: received empty reply");
return false;
}
public bool ValidateFriendshipOffered(UUID fromID, UUID toID)
{
FriendInfo finfo = new FriendInfo();
finfo.PrincipalID = fromID;
finfo.Friend = toID.ToString();
Dictionary<string, object> sendData = finfo.ToKeyValuePairs();
sendData["METHOD"] = "validate_friendship_offered";
string reply = string.Empty;
string uri = m_ServerURI + "/hgfriends";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Exception when contacting friends server at {0}: {1}", uri, e.Message);
return false;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("RESULT"))
{
if (replyData["RESULT"].ToString().ToLower() == "true")
return true;
else
return false;
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: reply data does not contain result field");
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: received empty reply");
return false;
}
public List<UUID> StatusNotification(List<string> friends, UUID userID, bool online)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
List<UUID> friendsOnline = new List<UUID>();
sendData["METHOD"] = "statusnotification";
sendData["userID"] = userID.ToString();
sendData["online"] = online.ToString();
int i = 0;
foreach (string s in friends)
{
sendData["friend_" + i.ToString()] = s;
i++;
}
string reply = string.Empty;
string uri = m_ServerURI + "/hgfriends";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), 15);
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Exception when contacting friends server at {0}: {1}", uri, e.Message);
return friendsOnline;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
// Here is the actual response
foreach (string key in replyData.Keys)
{
if (key.StartsWith("friend_") && replyData[key] != null)
{
UUID uuid;
if (UUID.TryParse(replyData[key].ToString(), out uuid))
friendsOnline.Add(uuid);
}
}
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Received empty reply from remote StatusNotify");
return friendsOnline;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Completion
{
internal static class CommonCompletionUtilities
{
private const string NonBreakingSpaceString = "\x00A0";
public static TextSpan GetWordSpan(SourceText text, int position,
Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter)
{
int start = position;
while (start > 0 && isWordStartCharacter(text[start - 1]))
{
start--;
}
// If we're brought up in the middle of a word, extend to the end of the word as well.
// This means that if a user brings up the completion list at the start of the word they
// will "insert" the text before what's already there (useful for qualifying existing
// text). However, if they bring up completion in the "middle" of a word, then they will
// "overwrite" the text. Useful for correcting misspellings or just replacing unwanted
// code with new code.
int end = position;
if (start != position)
{
while (end < text.Length && isWordCharacter(text[end]))
{
end++;
}
}
return TextSpan.FromBounds(start, end);
}
public static bool IsStartingNewWord(SourceText text, int characterPosition, Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter)
{
var ch = text[characterPosition];
if (!isWordStartCharacter(ch))
{
return false;
}
// Only want to trigger if we're the first character in an identifier. If there's a
// character before or after us, then we don't want to trigger.
if (characterPosition > 0 &&
isWordCharacter(text[characterPosition - 1]))
{
return false;
}
if (characterPosition < text.Length - 1 &&
isWordCharacter(text[characterPosition + 1]))
{
return false;
}
return true;
}
public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory(
Workspace workspace,
SemanticModel semanticModel,
int position,
ISymbol symbol)
{
return CreateDescriptionFactory(workspace, semanticModel, position, new[] { symbol });
}
public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory(
Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols)
{
return c => CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms: null, cancellationToken: c);
}
public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory(
Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols, SupportedPlatformData supportedPlatforms)
{
return c => CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms: supportedPlatforms, cancellationToken: c);
}
public static async Task<CompletionDescription> CreateDescriptionAsync(
Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols, SupportedPlatformData supportedPlatforms, CancellationToken cancellationToken)
{
var symbolDisplayService = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<ISymbolDisplayService>();
var formatter = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<IDocumentationCommentFormattingService>();
// TODO(cyrusn): Figure out a way to cancel this.
var symbol = symbols[0];
var sections = await symbolDisplayService.ToDescriptionGroupsAsync(workspace, semanticModel, position, ImmutableArray.Create(symbol), cancellationToken).ConfigureAwait(false);
if (!sections.ContainsKey(SymbolDescriptionGroups.MainDescription))
{
return CompletionDescription.Empty;
}
var textContentBuilder = new List<TaggedText>();
textContentBuilder.AddRange(sections[SymbolDescriptionGroups.MainDescription]);
switch (symbol.Kind)
{
case SymbolKind.Method:
case SymbolKind.NamedType:
if (symbols.Count > 1)
{
var overloadCount = symbols.Count - 1;
var isGeneric = symbol.GetArity() > 0;
textContentBuilder.AddSpace();
textContentBuilder.AddPunctuation("(");
textContentBuilder.AddPunctuation("+");
textContentBuilder.AddText(NonBreakingSpaceString + overloadCount.ToString());
AddOverloadPart(textContentBuilder, overloadCount, isGeneric);
textContentBuilder.AddPunctuation(")");
}
break;
}
AddDocumentationPart(textContentBuilder, symbol, semanticModel, position, formatter, cancellationToken);
if (sections.ContainsKey(SymbolDescriptionGroups.AwaitableUsageText))
{
textContentBuilder.AddRange(sections[SymbolDescriptionGroups.AwaitableUsageText]);
}
if (sections.ContainsKey(SymbolDescriptionGroups.AnonymousTypes))
{
var parts = sections[SymbolDescriptionGroups.AnonymousTypes];
if (!parts.IsDefaultOrEmpty)
{
textContentBuilder.AddLineBreak();
textContentBuilder.AddLineBreak();
textContentBuilder.AddRange(parts);
}
}
if (supportedPlatforms != null)
{
textContentBuilder.AddLineBreak();
textContentBuilder.AddRange(supportedPlatforms.ToDisplayParts().ToTaggedText());
}
return CompletionDescription.Create(textContentBuilder.AsImmutable());
}
private static void AddOverloadPart(List<TaggedText> textContentBuilder, int overloadCount, bool isGeneric)
{
var text = isGeneric
? overloadCount == 1
? FeaturesResources.generic_overload
: FeaturesResources.generic_overloads
: overloadCount == 1
? FeaturesResources.overload
: FeaturesResources.overloads_;
textContentBuilder.AddText(NonBreakingSpaceString + text);
}
private static void AddDocumentationPart(
List<TaggedText> textContentBuilder, ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken)
{
var documentation = symbol.GetDocumentationParts(semanticModel, position, formatter, cancellationToken);
if (documentation.Any())
{
textContentBuilder.AddLineBreak();
textContentBuilder.AddRange(documentation);
}
}
internal static bool IsTextualTriggerString(SourceText text, int characterPosition, string value)
{
// The character position starts at the last character of 'value'. So if 'value' has
// length 1, then we don't want to move, if it has length 2 we want to move back one,
// etc.
characterPosition = characterPosition - value.Length + 1;
for (int i = 0; i < value.Length; i++, characterPosition++)
{
if (characterPosition < 0 || characterPosition >= text.Length)
{
return false;
}
if (text[characterPosition] != value[i])
{
return false;
}
}
return true;
}
public static bool TryRemoveAttributeSuffix(ISymbol symbol, SyntaxContext context, out string name)
{
var isAttributeNameContext = context.IsAttributeNameContext;
var syntaxFacts = context.GetLanguageService<ISyntaxFactsService>();
if (!isAttributeNameContext)
{
name = null;
return false;
}
// Do the symbol textual check first. Then the more expensive symbolic check.
if (!symbol.Name.TryGetWithoutAttributeSuffix(syntaxFacts.IsCaseSensitive, out name) ||
!symbol.IsAttribute())
{
return false;
}
return true;
}
}
}
| |
//-----------------------------------------------------------------------------
// Filename: RTPHeader.cs
//
// Description: RTP Header as defined in RFC3550.
//
//
// RTP Header:
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |V=2|P|X| CC |M| PT | sequence number |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | timestamp |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | synchronization source (SSRC) identifier |
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
// | contributing source (CSRC) identifiers |
// | .... |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// (V)ersion (2 bits) = 2
// (P)adding (1 bit) = Indicates whether the packet contains additional padding octets.
// e(X)tension (1 bit) = If set the fixed header must be followed by exactly one header extension.
// CSRC Count (CC) (4 bits) = Number of Contributing Source identifiers following fixed header.
// (M)arker (1 bit) = Used by profiles to enable marks to be set in the data.
// Payload Type (PT) (7 bits) = RTP payload type.
// - GSM: 000 0011 (3)
// - PCMU (G711): 000 0000 (0)
// Sequence Number (16 bits) = Increments by one for each RTP packet sent, initial value random.
// Timestamp (32 bits) = The sampling instant of the first bit in the RTP data packet.
// Synchronisation Source Id (SSRC) (32 bits) = The unique synchronisation source for the data stream.
// Contributing Source Identifier Ids (0 to 15 items 32 bits each, see CC) = List of contributing sources for the payload in this field.
//
//
// Wallclock time (absolute date and time) is represented using the
// timestamp format of the Network Time Protocol (NTP), which is in
// seconds relative to 0h UTC on 1 January 1900 [4]. The full
// resolution NTP timestamp is a 64-bit unsigned fixed-point number with
// the integer part in the first 32 bits and the fractional part in the
// last 32 bits. In some fields where a more compact representation is
// appropriate, only the middle 32 bits are used; that is, the low 16
// bits of the integer part and the high 16 bits of the fractional part.
// The high 16 bits of the integer part must be determined
// independently.
//
// History:
// 22 May 2005 Aaron Clauson Created.
//
// License:
// Aaron Clauson
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Net;
using SIPSorcery.Sys;
namespace SIPSorcery.Net
{
public class RTPHeader
{
public const int MIN_HEADER_LEN = 12;
//public readonly static DateTime ZeroTime = new DateTime(2007, 1, 1).ToUniversalTime();
public const int RTP_VERSION = 2;
public int Version = RTP_VERSION; // 2 bits.
public int PaddingFlag = 0; // 1 bit.
public int HeaderExtensionFlag = 0; // 1 bit.
public int CSRCCount = 0; // 4 bits
public int MarkerBit = 0; // 1 bit.
public int PayloadType = (int)RTPPayloadTypesEnum.PCMU; // 7 bits.
public UInt16 SequenceNumber; // 16 bits.
public uint Timestamp; // 32 bits.
public uint SyncSource; // 32 bits.
public int[] CSRCList; // 32 bits.
public UInt16 ExtensionProfile; // 16 bits.
public UInt16 ExtensionLength; // 16 bits, length of the header extensions in 32 bit words.
public byte[] ExtensionPayload;
public int Length
{
get { return MIN_HEADER_LEN + (CSRCCount * 4) + ((HeaderExtensionFlag == 0) ? 0 : 4 + (ExtensionLength * 4)); }
}
public RTPHeader()
{
SequenceNumber = Crypto.GetRandomUInt16();
SyncSource = Crypto.GetRandomUInt();
Timestamp = Crypto.GetRandomUInt();
}
/// <summary>
/// Extract and load the RTP header from an RTP packet.
/// </summary>
/// <param name="packet"></param>
public RTPHeader(byte[] packet)
{
if (packet.Length < MIN_HEADER_LEN)
{
throw new ApplicationException("The packet did not contain the minimum number of bytes for an RTP header packet.");
}
UInt16 firstWord = BitConverter.ToUInt16(packet, 0);
if (BitConverter.IsLittleEndian)
{
firstWord = NetConvert.DoReverseEndian(firstWord);
SequenceNumber = NetConvert.DoReverseEndian(BitConverter.ToUInt16(packet, 2));
Timestamp = NetConvert.DoReverseEndian(BitConverter.ToUInt32(packet, 4));
SyncSource = NetConvert.DoReverseEndian(BitConverter.ToUInt32(packet, 8));
}
else
{
SequenceNumber = BitConverter.ToUInt16(packet, 2);
Timestamp = BitConverter.ToUInt32(packet, 4);
SyncSource = BitConverter.ToUInt32(packet, 8);
}
Version = firstWord >> 14;
PaddingFlag = (firstWord >> 13) & 0x1;
HeaderExtensionFlag = (firstWord >> 12) & 0x1;
CSRCCount = (firstWord >> 8) & 0xf;
MarkerBit = (firstWord >> 7) & 0x1;
PayloadType = firstWord & 0x7f;
if (HeaderExtensionFlag == 1)
{
if (BitConverter.IsLittleEndian)
{
ExtensionProfile = NetConvert.DoReverseEndian(BitConverter.ToUInt16(packet, 12 + 4 * CSRCCount));
ExtensionLength = NetConvert.DoReverseEndian(BitConverter.ToUInt16(packet, 14 + 4 * CSRCCount));
}
else
{
ExtensionProfile = BitConverter.ToUInt16(packet, 8 + 4 * CSRCCount);
ExtensionLength = BitConverter.ToUInt16(packet, 10 + 4 * CSRCCount);
}
}
}
public byte[] GetHeader(UInt16 sequenceNumber, uint timestamp, uint syncSource)
{
SequenceNumber = sequenceNumber;
Timestamp = timestamp;
SyncSource = syncSource;
return GetBytes();
}
public byte[] GetBytes()
{
byte[] header = new byte[Length];
UInt16 firstWord = Convert.ToUInt16(Version * 16384 + PaddingFlag * 8192 + HeaderExtensionFlag * 4096 + CSRCCount * 256 + MarkerBit * 128 + PayloadType);
if (BitConverter.IsLittleEndian)
{
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(firstWord)), 0, header, 0, 2);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SequenceNumber)), 0, header, 2, 2);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(Timestamp)), 0, header, 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SyncSource)), 0, header, 8, 4);
if (HeaderExtensionFlag == 1)
{
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(ExtensionProfile)), 0, header, 12 + 4 * CSRCCount, 2);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(ExtensionLength)), 0, header, 14 + 4 * CSRCCount, 2);
}
}
else
{
Buffer.BlockCopy(BitConverter.GetBytes(firstWord), 0, header, 0, 2);
Buffer.BlockCopy(BitConverter.GetBytes(SequenceNumber), 0, header, 2, 2);
Buffer.BlockCopy(BitConverter.GetBytes(Timestamp), 0, header, 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(SyncSource), 0, header, 8, 4);
if (HeaderExtensionFlag == 1)
{
Buffer.BlockCopy(BitConverter.GetBytes(ExtensionProfile), 0, header, 12 + 4 * CSRCCount, 2);
Buffer.BlockCopy(BitConverter.GetBytes(ExtensionLength), 0, header, 14 + 4 * CSRCCount, 2);
}
}
if (ExtensionLength > 0 && ExtensionPayload != null)
{
Buffer.BlockCopy(ExtensionPayload, 0, header, 16 + 4 * CSRCCount, ExtensionLength * 4);
}
return header;
}
/*public static uint GetWallclockUTCStamp(DateTime time)
{
return Convert.ToUInt32(time.ToUniversalTime().Subtract(DateTime.Now.Date).TotalMilliseconds);
}
/// <summary>
///
/// </summary>
/// <param name="timestamp"></param>
/// <returns>The timestamp as a UTC DateTime object.</returns>
public static DateTime GetWallclockUTCTimeFromStamp(uint timestamp)
{
return DateTime.Now.Date.AddMilliseconds(timestamp);
}*/
}
}
| |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Microsoft.WindowsAzure.MobileServices;
using Windows.Data.Json;
using MonoTouch.Foundation;
namespace Microsoft.Azure.Zumo.Win8.CSharp.Test
{
public class ZumoServiceTests : TestBase
{
/// <summary>
/// Verify we have an installation ID created whenever we use a ZUMO
/// service.
/// </summary>
[Test]
public void InstallationId()
{
MobileServiceClient service = new MobileServiceClient("http://test.com");
var defaults = NSUserDefaults.StandardUserDefaults;
string settings = defaults.StringForKey ("MobileServices.Installation.config");
string id = JsonValue.Parse(settings).Get("applicationInstallationId").AsString();
Assert.IsNotNull(id);
}
[Test]
public void Construction()
{
string appUrl = "http://www.test.com/";
string appKey = "secret...";
MobileServiceClient service = new MobileServiceClient(new Uri(appUrl), appKey);
Assert.AreEqual(appUrl, service.ApplicationUri.ToString());
Assert.AreEqual(appKey, service.ApplicationKey);
service = new MobileServiceClient(appUrl, appKey);
Assert.AreEqual(appUrl, service.ApplicationUri.ToString());
Assert.AreEqual(appKey, service.ApplicationKey);
service = new MobileServiceClient(new Uri(appUrl));
Assert.AreEqual(appUrl, service.ApplicationUri.ToString());
Assert.AreEqual(null, service.ApplicationKey);
service = new MobileServiceClient(appUrl);
Assert.AreEqual(appUrl, service.ApplicationUri.ToString());
Assert.AreEqual(null, service.ApplicationKey);
Uri none = null;
Assert.Throws<ArgumentNullException>(() => new MobileServiceClient(none));
Assert.Throws<UriFormatException>(() => new MobileServiceClient("not a valid uri!!!@#!@#"));
}
[Test]
public void WithFilter()
{
string appUrl = "http://www.test.com/";
string appKey = "secret...";
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service =
new MobileServiceClient(new Uri(appUrl), appKey)
.WithFilter(hijack);
// Ensure properties are copied over
Assert.AreEqual(appUrl, service.ApplicationUri.ToString());
Assert.AreEqual(appKey, service.ApplicationKey);
// Set the filter to return an empty array
hijack.Response.Content = new JsonArray().Stringify();
service.GetTable("foo").ReadAsync("bar")
.ContinueWith (t =>
{
// Verify the filter was in the loop
Assert.That (hijack.Request.Uri.ToString(), Is.StringStarting (appUrl));
Assert.Throws<ArgumentNullException>(() => service.WithFilter(null));
}).WaitOrFail (Timeout);
}
[Test]
public void LoginAsync()
{
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...")
.WithFilter(hijack);
// Send back a successful login response
hijack.Response.Content =
new JsonObject()
.Set("authenticationToken", "rhubarb")
.Set("user",
new JsonObject()
.Set("userId", "123456")).Stringify();
service.LoginAsync("donkey").ContinueWith (t =>
{
var current = t.Result;
Assert.IsNotNull(current);
Assert.AreEqual("123456", current.UserId);
Assert.AreEqual("rhubarb", current.MobileServiceAuthenticationToken);
Assert.That (hijack.Request.Uri.ToString(), Is.StringEnding ("login"));
string input = JsonValue.Parse(hijack.Request.Content).Get("authenticationToken").AsString();
Assert.AreEqual("donkey", input);
Assert.AreEqual("POST", hijack.Request.Method);
Assert.AreSame(current, service.CurrentUser);
// Set the Auth Token
service.CurrentUser.MobileServiceAuthenticationToken = "Not rhubarb";
// Verify that the user token is sent with each request
service.GetTable("foo").ReadAsync("bar").ContinueWith (rt =>
{
var response = rt.Result;
Assert.AreEqual("Not rhubarb", hijack.Request.Headers["X-ZUMO-AUTH"]);
// Verify error cases
ThrowsAsync<ArgumentNullException>(() => service.LoginAsync(null));
ThrowsAsync<ArgumentException>(() => service.LoginAsync(""));
// Send back a failure and ensure it throws
hijack.Response.Content =
new JsonObject().Set("error", "login failed").Stringify();
hijack.Response.StatusCode = 401;
ThrowsAsync<InvalidOperationException>(() => service.LoginAsync("donkey"));
}).WaitOrFail (Timeout);
}).WaitOrFail (Timeout);
}
[Test]
public void Logout()
{
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...")
.WithFilter(hijack);
// Send back a successful login response
hijack.Response.Content =
new JsonObject()
.Set("authenticationToken", "rhubarb")
.Set("user",
new JsonObject()
.Set("userId", "123456")).Stringify();
service.LoginAsync("donkey").ContinueWith (t =>
{
Assert.IsNotNull(service.CurrentUser);
service.Logout();
Assert.IsNull(service.CurrentUser);
}).WaitOrFail (Timeout);
}
[Test]
public void StandardRequestFormat()
{
string appUrl = "http://www.test.com";
string appKey = "secret...";
string collection = "tests";
string query = "$filter=id eq 12";
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service = new MobileServiceClient(appUrl, appKey)
.WithFilter(hijack);
hijack.Response.Content =
new JsonArray()
.Append(new JsonObject().Set("id", 12).Set("value", "test"))
.Stringify();
service.GetTable(collection).ReadAsync(query).ContinueWith (t => {
Assert.IsNotNull(hijack.Request.Headers["X-ZUMO-INSTALLATION-ID"]);
Assert.AreEqual("secret...", hijack.Request.Headers["X-ZUMO-APPLICATION"]);
Assert.AreEqual("application/json", hijack.Request.Accept);
});
}
[Test]
public void ErrorMessageConstruction()
{
string appUrl = "http://www.test.com";
string appKey = "secret...";
string collection = "tests";
string query = "$filter=id eq 12";
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service = new MobileServiceClient(appUrl, appKey)
.WithFilter(hijack);
// Verify the error message is correctly pulled out
hijack.Response.Content =
new JsonObject()
.Set("error", "error message")
.Set("other", "donkey")
.Stringify();
hijack.Response.StatusCode = 401;
hijack.Response.StatusDescription = "YOU SHALL NOT PASS.";
try
{
service.GetTable(collection).ReadAsync(query).WaitOrFail (Timeout);
}
catch (AggregateException aex)
{
var ex = aex.AssertCaught<InvalidOperationException>();
Assert.That (ex.Message, Is.EqualTo ("error message"));
}
// Verify all of the exception parameters
hijack.Response.Content =
new JsonObject()
.Set("error", "error message")
.Set("other", "donkey")
.Stringify();
hijack.Response.StatusCode = 401;
hijack.Response.StatusDescription = "YOU SHALL NOT PASS.";
try
{
service.GetTable(collection).ReadAsync(query).WaitOrFail (Timeout);
}
catch (AggregateException aex)
{
var ex = aex.AssertCaught<MobileServiceInvalidOperationException>();
Assert.That (ex.Message, Is.EqualTo ("error message"));
Assert.AreEqual((int)HttpStatusCode.Unauthorized, ex.Response.StatusCode);
Assert.That (ex.Response.Content, Contains.Substring ("donkey"));
Assert.That (ex.Request.Uri.ToString(), Is.StringStarting (appUrl));
Assert.AreEqual("YOU SHALL NOT PASS.", ex.Response.StatusDescription);
}
// If no error message in the response, we'll use the
// StatusDescription instead
hijack.Response.Content =
new JsonObject()
.Set("other", "donkey")
.Stringify();
try
{
service.GetTable(collection).ReadAsync(query).WaitOrFail (Timeout);
}
catch (AggregateException aex)
{
var ex = aex.AssertCaught<InvalidOperationException>();
Assert.AreEqual ("The request could not be completed. (YOU SHALL NOT PASS.)", ex.Message);
}
}
public class Person
{
public long Id { get; set; }
public string Name { get; set; }
}
[Test]
public void ReadAsync()
{
string appUrl = "http://www.test.com";
string appKey = "secret...";
string collection = "tests";
string query = "$filter=id eq 12";
var userDefinedParameters = new Dictionary<string, string> { { "tags", "#pizza #beer" } };
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service = new MobileServiceClient(appUrl, appKey)
.WithFilter(hijack);
hijack.Response.Content =
new JsonArray()
.Append(new JsonObject().Set("id", 12).Set("value", "test"))
.Stringify();
service.GetTable(collection).ReadAsync(query, userDefinedParameters).ContinueWith (t => {
Assert.That (hijack.Request.Uri.ToString(), Contains.Substring (collection));
Assert.That (hijack.Request.Uri.AbsoluteUri, Contains.Substring ("tags=%23pizza%20%23beer"));
Assert.That (hijack.Request.Uri.ToString(), Contains.Substring (query));
ThrowsAsync<ArgumentNullException>(() => service.GetTable(null).ReadAsync(query));
ThrowsAsync<ArgumentException>(() => service.GetTable("").ReadAsync(query));
var invalidUserDefinedParameters = new Dictionary<string, string>() { { "$this is invalid", "since it starts with a '$'" } };
ThrowsAsync<ArgumentException>(() => service.GetTable(collection).ReadAsync(query, invalidUserDefinedParameters));
}).WaitOrFail (Timeout);
}
[Test]
public void ReadAsyncGeneric()
{
string appUrl = "http://www.test.com";
string appKey = "secret...";
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service = new MobileServiceClient(appUrl, appKey)
.WithFilter(hijack);
hijack.Response.Content =
new JsonArray()
.Append(new JsonObject().Set("id", 12).Set("Name", "Bob"))
.Stringify();
IMobileServiceTable<Person> table = service.GetTable<Person>();
table.Where(p => p.Id == 12).ToListAsync().ContinueWith (t => {
var people = t.Result;
Assert.AreEqual(1, people.Count);
Assert.AreEqual(12L, people[0].Id);
Assert.AreEqual("Bob", people[0].Name);
}).WaitOrFail (Timeout);
}
[Test]
public void LookupAsync()
{
string appUrl = "http://www.test.com";
string appKey = "secret...";
var userDefinedParameters = new Dictionary<string, string>() { { "state", "CA" } };
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service = new MobileServiceClient(appUrl, appKey)
.WithFilter(hijack);
hijack.Response.Content =
new JsonObject()
.Set("id", 12)
.Set("Name", "Bob")
.Stringify();
IMobileServiceTable<Person> table = service.GetTable<Person>();
table.LookupAsync(12, userDefinedParameters).ContinueWith (t => {
var bob = t.Result;
Assert.That(hijack.Request.Uri.Query, Contains.Substring("state=CA"));
Assert.AreEqual(12L, bob.Id);
Assert.AreEqual("Bob", bob.Name);
hijack.Response.StatusCode = 404;
bool thrown = false;
try
{
Task<Person> lookup = table.LookupAsync (12);
lookup.WaitOrFail (Timeout);
bob = lookup.Result;
}
catch (AggregateException aex)
{
aex.AssertCaught<InvalidOperationException>();
thrown = true;
}
Assert.IsTrue(thrown, "Exception should be thrown on a 404!");
}).WaitOrFail (Timeout);
}
[Test]
public void InsertAsync()
{
string appUrl = "http://www.test.com";
string appKey = "secret...";
string collection = "tests";
var userDefinedParameters = new Dictionary<string, string>() {{ "state", "AL" }};
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service = new MobileServiceClient(appUrl, appKey)
.WithFilter(hijack);
JsonObject obj = new JsonObject().Set("value", "new");
hijack.Response.Content =
new JsonObject().Set("id", 12).Set("value", "new").Stringify();
service.GetTable(collection).InsertAsync(obj, userDefinedParameters).WaitOrFail (Timeout);
Assert.AreEqual(12, obj.Get("id").AsInteger());
Assert.That(hijack.Request.Uri.ToString(), Contains.Substring (collection));
Assert.That(hijack.Request.Uri.Query, Contains.Substring("state=AL"));
ThrowsAsync<ArgumentNullException>(
() => service.GetTable(collection).InsertAsync(null));
// Verify we throw if ID is set on both JSON and strongly typed
// instances
ThrowsAsync<ArgumentException>(
() => service.GetTable(collection).InsertAsync(
new JsonObject().Set("id", 15)));
ThrowsAsync<ArgumentException>(
() => service.GetTable<Person>().InsertAsync(
new Person() { Id = 15 }));
}
[Test]
public void InsertAsyncThrowsIfIdExists()
{
string appUrl = "http://www.test.com";
string collection = "tests";
MobileServiceClient service = new MobileServiceClient(appUrl);
// Verify we throw if ID is set on both JSON and strongly typed
// instances
ThrowsAsync<ArgumentException>(
() => service.GetTable(collection).InsertAsync(
new JsonObject().Set("id", 15)));
ThrowsAsync<ArgumentException>(
() => service.GetTable<Person>().InsertAsync(
new Person() { Id = 15 }));
}
[Test]
public void UpdateAsync()
{
string appUrl = "http://www.test.com";
string appKey = "secret...";
string collection = "tests";
var userDefinedParameters = new Dictionary<string, string>() { { "state", "FL" } };
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service = new MobileServiceClient(appUrl, appKey)
.WithFilter(hijack);
JsonObject obj = new JsonObject().Set("id", 12).Set("value", "new");
hijack.Response.Content =
new JsonObject()
.Set("id", 12)
.Set("value", "new")
.Set("other", "123")
.Stringify();
IMobileServiceTable table = service.GetTable(collection);
table.UpdateAsync(obj, userDefinedParameters).WaitOrFail (Timeout);
Assert.AreEqual("123", obj.Get("other").AsString());
Assert.That (hijack.Request.Uri.ToString(), Contains.Substring (collection));
ThrowsAsync<ArgumentNullException>(() => table.UpdateAsync(null));
ThrowsAsync<ArgumentException>(() => table.UpdateAsync(new JsonObject()));
}
[Test]
public void DeleteAsync()
{
string appUrl = "http://www.test.com";
string appKey = "secret...";
string collection = "tests";
var userDefinedParameters = new Dictionary<string, string>() { { "state", "WY" } };
TestServiceFilter hijack = new TestServiceFilter();
MobileServiceClient service = new MobileServiceClient(appUrl, appKey)
.WithFilter(hijack);
JsonObject obj = new JsonObject().Set("id", 12).Set("value", "new");
IMobileServiceTable table = service.GetTable(collection);
table.DeleteAsync(obj, userDefinedParameters).WaitOrFail (Timeout);
Assert.That (hijack.Request.Uri.ToString(), Contains.Substring (collection));
ThrowsAsync<ArgumentNullException>(() => table.DeleteAsync(null));
ThrowsAsync<ArgumentException>(() => table.DeleteAsync(new JsonObject()));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using Xunit;
namespace System.Net.Http.Tests
{
public class HttpHeaderValueCollectionTest
{
private const string knownHeader = "known-header";
private static readonly Uri specialValue = new Uri("http://special/");
private static readonly Uri invalidValue = new Uri("http://invalid/");
private static readonly TransferCodingHeaderValue specialChunked = new TransferCodingHeaderValue("chunked");
// Note that this type just forwards calls to HttpHeaders. So this test method focusses on making sure
// the correct calls to HttpHeaders are made. This test suite will not test HttpHeaders functionality.
[Fact]
public void IsReadOnly_CallProperty_AlwaysFalse()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string)));
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers);
Assert.False(collection.IsReadOnly);
}
[Fact]
public void Count_AddSingleValueThenQueryCount_ReturnsValueCountWithSpecialValues()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string)));
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers,
"special");
Assert.Equal(0, collection.Count);
headers.Add(knownHeader, "value2");
Assert.Equal(1, collection.Count);
headers.Clear();
headers.Add(knownHeader, "special");
Assert.Equal(1, collection.Count);
headers.Add(knownHeader, "special");
headers.Add(knownHeader, "special");
Assert.Equal(3, collection.Count);
}
[Fact]
public void Count_AddMultipleValuesThenQueryCount_ReturnsValueCountWithSpecialValues()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string)));
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers,
"special");
Assert.Equal(0, collection.Count);
collection.Add("value1");
headers.Add(knownHeader, "special");
Assert.Equal(2, collection.Count);
headers.Add(knownHeader, "special");
headers.Add(knownHeader, "value2");
headers.Add(knownHeader, "special");
Assert.Equal(5, collection.Count);
}
[Fact]
public void Add_CallWithNullValue_Throw()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
Assert.Throws<ArgumentNullException>(() => { collection.Add(null); });
}
[Fact]
public void Add_AddValues_AllValuesAdded()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.Equal(3, collection.Count);
}
[Fact]
public void Add_UseSpecialValue_Success()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.Equal(String.Empty, headers.TransferEncoding.ToString());
headers.TransferEncoding.Add(specialChunked);
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked, headers.TransferEncoding.First());
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
}
[Fact]
public void Add_UseSpecialValueWithSpecialAlreadyPresent_AddsDuplicate()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncodingChunked = true;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
headers.TransferEncoding.Add(specialChunked);
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(2, headers.TransferEncoding.Count);
Assert.Equal("chunked, chunked", headers.TransferEncoding.ToString());
// removes first instance of
headers.TransferEncodingChunked = false;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
// does not add duplicate
headers.TransferEncodingChunked = true;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
}
[Fact]
public void ParseAdd_CallWithNullValue_NothingAdded()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
collection.ParseAdd(null);
Assert.False(collection.IsSpecialValueSet);
Assert.Equal(0, collection.Count);
Assert.Equal(String.Empty, collection.ToString());
}
[Fact]
public void ParseAdd_AddValues_AllValuesAdded()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.ParseAdd("http://www.example.org/1/");
collection.ParseAdd("http://www.example.org/2/");
collection.ParseAdd("http://www.example.org/3/");
Assert.Equal(3, collection.Count);
}
[Fact]
public void ParseAdd_UseSpecialValue_Added()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.ParseAdd(specialValue.AbsoluteUri);
Assert.True(collection.IsSpecialValueSet);
Assert.Equal(specialValue.ToString(), collection.ToString());
}
[Fact]
public void ParseAdd_AddBadValue_Throws()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess";
Assert.Throws<FormatException>(() => { headers.WwwAuthenticate.ParseAdd(input); });
}
[Fact]
public void TryParseAdd_CallWithNullValue_NothingAdded()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
Assert.True(headers.WwwAuthenticate.TryParseAdd(null));
Assert.False(headers.WwwAuthenticate.IsSpecialValueSet);
Assert.Equal(0, headers.WwwAuthenticate.Count);
Assert.Equal(String.Empty, headers.WwwAuthenticate.ToString());
}
[Fact]
public void TryParseAdd_AddValues_AllAdded()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
Assert.True(collection.TryParseAdd("http://www.example.org/1/"));
Assert.True(collection.TryParseAdd("http://www.example.org/2/"));
Assert.True(collection.TryParseAdd("http://www.example.org/3/"));
Assert.Equal(3, collection.Count);
}
[Fact]
public void TryParseAdd_UseSpecialValue_Added()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
Assert.True(collection.TryParseAdd(specialValue.AbsoluteUri));
Assert.True(collection.IsSpecialValueSet);
Assert.Equal(specialValue.ToString(), collection.ToString());
}
[Fact]
public void TryParseAdd_AddBadValue_False()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess";
Assert.False(headers.WwwAuthenticate.TryParseAdd(input));
Assert.Equal(string.Empty, headers.WwwAuthenticate.ToString());
Assert.Equal(string.Empty, headers.ToString());
}
[Fact]
public void TryParseAdd_AddBadAfterGoodValue_False()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Negotiate"));
string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess";
Assert.False(headers.WwwAuthenticate.TryParseAdd(input));
Assert.Equal("Negotiate", headers.WwwAuthenticate.ToString());
Assert.Equal("WWW-Authenticate: Negotiate\r\n", headers.ToString());
}
[Fact]
public void Clear_AddValuesThenClear_NoElementsInCollection()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.Equal(3, collection.Count);
collection.Clear();
Assert.Equal(0, collection.Count);
}
[Fact]
public void Clear_AddValuesAndSpecialValueThenClear_EverythingCleared()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.SetSpecialValue();
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.Equal(4, collection.Count);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
collection.Clear();
Assert.Equal(0, collection.Count);
Assert.False(collection.IsSpecialValueSet, "Special value was removed by Clear().");
}
[Fact]
public void Contains_CallWithNullValue_Throw()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
Assert.Throws<ArgumentNullException>(() => { collection.Contains(null); });
}
[Fact]
public void Contains_AddValuesThenCallContains_ReturnsTrueForExistingItemsFalseOtherwise()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.True(collection.Contains(new Uri("http://www.example.org/2/")), "Expected true for existing item.");
Assert.False(collection.Contains(new Uri("http://www.example.org/4/")),
"Expected false for non-existing item.");
}
[Fact]
public void Contains_UseSpecialValueWhenEmpty_False()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void Contains_UseSpecialValueWithProperty_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncodingChunked = true;
Assert.True(headers.TransferEncoding.Contains(specialChunked));
headers.TransferEncodingChunked = false;
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void Contains_UseSpecialValueWhenSpecilValueIsPresent_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncoding.Add(specialChunked);
Assert.True(headers.TransferEncoding.Contains(specialChunked));
headers.TransferEncoding.Remove(specialChunked);
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void CopyTo_CallWithStartIndexPlusElementCountGreaterArrayLength_Throw()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
Uri[] array = new Uri[2];
// startIndex + Count = 1 + 2 > array.Length
Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 1); });
}
[Fact]
public void CopyTo_EmptyToEmpty_Success()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
Uri[] array = new Uri[0];
collection.CopyTo(array, 0);
}
[Fact]
public void CopyTo_NoValues_DoesNotChangeArray()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
Uri[] array = new Uri[4];
collection.CopyTo(array, 0);
for (int i = 0; i < array.Length; i++)
{
Assert.Null(array[i]);
}
}
[Fact]
public void CopyTo_AddSingleValue_ContainsSingleValue()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/"));
Uri[] array = new Uri[1];
collection.CopyTo(array, 0);
Assert.Equal(new Uri("http://www.example.org/"), array[0]);
// Now only set the special value: nothing should be added to the array.
headers.Clear();
headers.Add(knownHeader, specialValue.ToString());
array[0] = null;
collection.CopyTo(array, 0);
Assert.Equal(specialValue, array[0]);
}
[Fact]
public void CopyTo_AddMultipleValues_ContainsAllValuesInTheRightOrder()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Uri[] array = new Uri[5];
collection.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new Uri("http://www.example.org/1/"), array[1]);
Assert.Equal(new Uri("http://www.example.org/2/"), array[2]);
Assert.Equal(new Uri("http://www.example.org/3/"), array[3]);
Assert.Null(array[4]);
}
[Fact]
public void CopyTo_AddValuesAndSpecialValue_AllValuesCopied()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.SetSpecialValue();
collection.Add(new Uri("http://www.example.org/3/"));
Uri[] array = new Uri[5];
collection.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new Uri("http://www.example.org/1/"), array[1]);
Assert.Equal(new Uri("http://www.example.org/2/"), array[2]);
Assert.Equal(specialValue, array[3]);
Assert.Equal(new Uri("http://www.example.org/3/"), array[4]);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void CopyTo_OnlySpecialValue_Copied()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.SetSpecialValue();
headers.Add(knownHeader, specialValue.ToString());
headers.Add(knownHeader, specialValue.ToString());
headers.Add(knownHeader, specialValue.ToString());
Uri[] array = new Uri[4];
array[0] = null;
collection.CopyTo(array, 0);
Assert.Equal(specialValue, array[0]);
Assert.Equal(specialValue, array[1]);
Assert.Equal(specialValue, array[2]);
Assert.Equal(specialValue, array[3]);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void CopyTo_OnlySpecialValueEmptyDestination_Copied()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.SetSpecialValue();
headers.Add(knownHeader, specialValue.ToString());
Uri[] array = new Uri[2];
collection.CopyTo(array, 0);
Assert.Equal(specialValue, array[0]);
Assert.Equal(specialValue, array[1]);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void CopyTo_ArrayTooSmall_Throw()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string)));
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers,
"special");
string[] array = new string[1];
array[0] = null;
collection.CopyTo(array, 0); // no exception
Assert.Null(array[0]);
Assert.Throws<ArgumentNullException>(() => { collection.CopyTo(null, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { collection.CopyTo(array, -1); });
Assert.Throws<ArgumentOutOfRangeException>(() => { collection.CopyTo(array, 2); });
headers.Add(knownHeader, "special");
array = new string[0];
Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); });
headers.Add(knownHeader, "special");
headers.Add(knownHeader, "special");
array = new string[1];
Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); });
headers.Add(knownHeader, "value1");
array = new string[0];
Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); });
headers.Add(knownHeader, "value2");
array = new string[1];
Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); });
array = new string[2];
Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 1); });
}
[Fact]
public void Remove_CallWithNullValue_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
Assert.Throws<ArgumentNullException>(() => { collection.Remove(null); });
}
[Fact]
public void Remove_AddValuesThenCallRemove_ReturnsTrueWhenRemovingExistingValuesFalseOtherwise()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.True(collection.Remove(new Uri("http://www.example.org/2/")), "Expected true for existing item.");
Assert.False(collection.Remove(new Uri("http://www.example.org/4/")),
"Expected false for non-existing item.");
}
[Fact]
public void Remove_UseSpecialValue_FalseWhenEmpty()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.TransferEncoding.Remove(specialChunked));
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
}
[Fact]
public void Remove_UseSpecialValueWhenSetWithProperty_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncodingChunked = true;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.True(headers.TransferEncoding.Contains(specialChunked));
Assert.True(headers.TransferEncoding.Remove(specialChunked));
Assert.False((bool)headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void Remove_UseSpecialValueWhenAdded_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncoding.Add(specialChunked);
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.True(headers.TransferEncoding.Contains(specialChunked));
Assert.True(headers.TransferEncoding.Remove(specialChunked));
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void GetEnumerator_AddSingleValueAndGetEnumerator_AllValuesReturned()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
collection.Add(new Uri("http://www.example.org/"));
bool started = false;
foreach (var item in collection)
{
Assert.False(started, "We have more than one element returned by the enumerator.");
Assert.Equal(new Uri("http://www.example.org/"), item);
}
}
[Fact]
public void GetEnumerator_AddValuesAndGetEnumerator_AllValuesReturned()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
int i = 1;
foreach (var item in collection)
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
[Fact]
public void GetEnumerator_NoValues_EmptyEnumerator()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
IEnumerator<Uri> enumerator = collection.GetEnumerator();
Assert.False(enumerator.MoveNext(), "No items expected in enumerator.");
}
[Fact]
public void GetEnumerator_AddValuesAndGetEnumeratorFromInterface_AllValuesReturned()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
System.Collections.IEnumerable enumerable = collection;
int i = 1;
foreach (var item in enumerable)
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
[Fact]
public void GetEnumerator_AddValuesAndSpecialValueAndGetEnumeratorFromInterface_AllValuesReturned()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
collection.SetSpecialValue();
System.Collections.IEnumerable enumerable = collection;
// The "special value" should be ignored and not part of the resulting collection.
int i = 1;
bool specialFound = false;
foreach (var item in enumerable)
{
if (item.Equals(specialValue))
{
specialFound = true;
}
else
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
Assert.True(specialFound);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void GetEnumerator_AddValuesAndSpecialValue_AllValuesReturned()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.SetSpecialValue();
collection.Add(new Uri("http://www.example.org/3/"));
System.Collections.IEnumerable enumerable = collection;
// The special value we added above, must be part of the collection returned by GetEnumerator().
int i = 1;
bool specialFound = false;
foreach (var item in enumerable)
{
if (item.Equals(specialValue))
{
specialFound = true;
}
else
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
Assert.True(specialFound);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void IsSpecialValueSet_NoSpecialValueUsed_ReturnsFalse()
{
// Create a new collection _without_ specifying a special value.
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
null, null);
Assert.False(collection.IsSpecialValueSet,
"Special value is set even though collection doesn't define a special value.");
}
[Fact]
public void RemoveSpecialValue_AddRemoveSpecialValue_SpecialValueGetsRemoved()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.SetSpecialValue();
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
Assert.Equal(1, headers.GetValues(knownHeader).Count());
collection.RemoveSpecialValue();
Assert.False(collection.IsSpecialValueSet, "Special value is set.");
// Since the only header value was the "special value", removing it will remove the whole header
// from the collection.
Assert.False(headers.Contains(knownHeader));
}
[Fact]
public void RemoveSpecialValue_AddValueAndSpecialValueThenRemoveSpecialValue_SpecialValueGetsRemoved()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/"));
collection.SetSpecialValue();
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
Assert.Equal(2, headers.GetValues(knownHeader).Count());
collection.RemoveSpecialValue();
Assert.False(collection.IsSpecialValueSet, "Special value is set.");
Assert.Equal(1, headers.GetValues(knownHeader).Count());
}
[Fact]
public void RemoveSpecialValue_AddTwoValuesAndSpecialValueThenRemoveSpecialValue_SpecialValueGetsRemoved()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.SetSpecialValue();
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
Assert.Equal(3, headers.GetValues(knownHeader).Count());
// The difference between this test and the previous one is that HttpHeaders in this case will use
// a List<T> to store the two remaining values, whereas in the previous case it will just store
// the remaining value (no list).
collection.RemoveSpecialValue();
Assert.False(collection.IsSpecialValueSet, "Special value is set.");
Assert.Equal(2, headers.GetValues(knownHeader).Count());
}
[Fact]
public void Ctor_ProvideValidator_ValidatorIsUsedWhenAddingValues()
{
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
MockValidator);
// Adding an arbitrary Uri should not throw.
collection.Add(new Uri("http://some/"));
// When we add 'invalidValue' our MockValidator will throw.
Assert.Throws<MockException>(() => { collection.Add(invalidValue); });
}
[Fact]
public void Ctor_ProvideValidator_ValidatorIsUsedWhenRemovingValues()
{
// Use different ctor overload than in previous test to make sure all ctor overloads work correctly.
MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
specialValue, MockValidator);
// When we remove 'invalidValue' our MockValidator will throw.
Assert.Throws<MockException>(() => { collection.Remove(invalidValue); });
}
[Fact]
public void ToString_SpecialValues_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
request.Headers.TransferEncodingChunked = true;
string result = request.Headers.TransferEncoding.ToString();
Assert.Equal("chunked", result);
request.Headers.ExpectContinue = true;
result = request.Headers.Expect.ToString();
Assert.Equal("100-continue", result);
request.Headers.ConnectionClose = true;
result = request.Headers.Connection.ToString();
Assert.Equal("close", result);
}
[Fact]
public void ToString_SpecialValueAndExtra_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
request.Headers.Add(HttpKnownHeaderNames.TransferEncoding, "bla1");
request.Headers.TransferEncodingChunked = true;
request.Headers.Add(HttpKnownHeaderNames.TransferEncoding, "bla2");
string result = request.Headers.TransferEncoding.ToString();
Assert.Equal("bla1, chunked, bla2", result);
}
[Fact]
public void ToString_SingleValue_Success()
{
HttpResponseMessage response = new HttpResponseMessage();
string input = "Basic";
response.Headers.Add(HttpKnownHeaderNames.WWWAuthenticate, input);
string result = response.Headers.WwwAuthenticate.ToString();
Assert.Equal(input, result);
}
[Fact]
public void ToString_MultipleValue_Success()
{
HttpResponseMessage response = new HttpResponseMessage();
string input = "Basic, NTLM, Negotiate, Custom";
response.Headers.Add(HttpKnownHeaderNames.WWWAuthenticate, input);
string result = response.Headers.WwwAuthenticate.ToString();
Assert.Equal(input, result);
}
[Fact]
public void ToString_EmptyValue_Success()
{
HttpResponseMessage response = new HttpResponseMessage();
string result = response.Headers.WwwAuthenticate.ToString();
Assert.Equal(string.Empty, result);
}
#region Helper methods
private static void MockValidator(HttpHeaderValueCollection<Uri> collection, Uri value)
{
if (value == invalidValue)
{
throw new MockException();
}
}
public class MockException : Exception
{
public MockException() { }
public MockException(string message) : base(message) { }
public MockException(string message, Exception inner) : base(message, inner) { }
}
private class MockHeaders : HttpHeaders
{
public MockHeaders()
{
}
public MockHeaders(string headerName, HttpHeaderParser parser)
{
Dictionary<string, HttpHeaderParser> parserStore = new Dictionary<string, HttpHeaderParser>();
parserStore.Add(headerName, parser);
SetConfiguration(parserStore, new HashSet<string>());
}
}
private class MockHeaderParser : HttpHeaderParser
{
private static MockComparer comparer = new MockComparer();
private Type valueType;
public override IEqualityComparer Comparer
{
get { return comparer; }
}
public MockHeaderParser(Type valueType)
: base(true)
{
this.valueType = valueType;
}
public override bool TryParseValue(string value, object storeValue, ref int index, out object parsedValue)
{
parsedValue = null;
if (value == null)
{
return true;
}
index = value.Length;
// Just return the raw string (as string or Uri depending on the value type)
if (valueType == typeof(string))
{
parsedValue = value;
}
else if (valueType == typeof(Uri))
{
parsedValue = new Uri(value);
}
else
{
Assert.True(false, string.Format("Parser: Unknown value type '{0}'", valueType.ToString()));
}
return true;
}
}
private class MockComparer : IEqualityComparer
{
public int EqualsCount { get; private set; }
public int GetHashCodeCount { get; private set; }
#region IEqualityComparer Members
public new bool Equals(object x, object y)
{
EqualsCount++;
return x.Equals(y);
}
public int GetHashCode(object obj)
{
GetHashCodeCount++;
return obj.GetHashCode();
}
#endregion
}
#endregion
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using NUnit.Framework;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki.Tests.PageTests
{
[TestFixture]
public class RevisionTests
{
/// <summary>
/// Generate a diff of tag-less page content revisions
/// </summary>
/// <feature>
/// <name>GET:pages/{pageid}/diff</name>
/// <uri>http://developer.mindtouch.com/Deki/API_Reference/GET%3apages%2f%2f%7bpageid%7d%2f%2fdiff</uri>
/// </feature>
/// <expected>Output correct diff</expected>
[Test]
public void GetPageDiffWithoutTags()
{
// 1. Create a page with some content
// 2. Retrieve revisions list
// (3) Assert revisions list is populated
// 4. Save page with some new content
// 5. Retrieve revisions list
// (6) Assret revisions list is populated
// 7. Perform a diff
// (8) Assert diff result matches expected diff
// 9. Delete the page
// GET:pages/{pageid}/revisions
// http://developer.mindtouch.com/Deki/API_Reference/GET%3apages%2f%2f%7bpageid%7d%2f%2frevisions
Plug p = Utils.BuildPlugForAdmin();
string content = "This is test content";
string id = null;
string path = null;
DreamMessage msg = PageUtils.SavePage(p, string.Empty,
PageUtils.GenerateUniquePageName(), content, out id, out path);
msg = p.At("pages", "=" + XUri.DoubleEncode(path), "revisions").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Page revisions retrieval failed (1)");
Assert.IsFalse(msg.ToDocument()["page"].IsEmpty, "Page revisions list is empty?! (1)");
PageUtils.SavePage(p, path, "New content");
msg = p.At("pages", id, "revisions").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Page revisions retrieval failed (2)");
Assert.IsFalse(msg.ToDocument()["page"].IsEmpty, "Page revisions list is empty?! (2)");
// GET:pages/{pageid}/diff
// http://developer.mindtouch.com/Deki/API_Reference/GET%3apages%2f%2f%7bpageid%7d%2f%2fdiff
msg = p.At("pages", id, "diff").With("revision", "head").With("previous", -1).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "diff generation failed");
string diff = "<ins>New</ins><del>This is test</del> content";
Assert.AreEqual(diff, msg.ToDocument().Contents, "diff result does not match expected result");
PageUtils.DeletePageByID(p, id, true);
}
/// <summary>
/// Generate a diff of page content revisions with tags
/// </summary>
/// <feature>
/// <name>GET:pages/{pageid}/diff</name>
/// <uri>http://developer.mindtouch.com/Deki/API_Reference/GET%3apages%2f%2f%7bpageid%7d%2f%2fdiff</uri>
/// </feature>
/// <expected>Output correct diff</expected>
[Test]
public void GetPageDiffWithTags()
{
// 1. Create a page with some content with tags
// 2. Retrieve revisions list
// (3) Assert revisions list is populated
// 4. Save page with some new content with tags
// 5. Retrieve revisions list
// (6) Assret revisions list is populated
// 7. Perform a diff
// (8) Assert diff result matches expected diff
// 9. Delete the page
Plug p = Utils.BuildPlugForAdmin();
string content = "<p>This is test</p><p>content</p>";
string id = null;
string path = null;
DreamMessage msg = PageUtils.SavePage(p, string.Empty,
PageUtils.GenerateUniquePageName(), content, out id, out path);
msg = p.At("pages", "=" + XUri.DoubleEncode(path), "revisions").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Page revisions retrieval failed (1)");
Assert.IsFalse(msg.ToDocument()["page"].IsEmpty, "Page revisions list is empty?! (1)");
PageUtils.SavePage(p, path, "<p>New</p><p>content</p>");
msg = p.At("pages", id, "revisions").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Page revisions retrieval failed (2)");
Assert.IsFalse(msg.ToDocument()["page"].IsEmpty, "Page revisions list is empty?! 2)");
msg = p.At("pages", id, "diff").With("revision", "head").With("previous", -1).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "diff generation failed");
string diff = "<p><ins>New</ins><del>This is test</del></p><p>...</p>";
Assert.AreEqual(diff, msg.ToDocument().Contents, "diff result does not match expected result");
PageUtils.DeletePageByID(p, id, true);
}
/// <summary>
/// Performs several
/// </summary>
/// <feature>
/// <name>POST:pages/{pageid}/revisions</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/POST%3apages%2f%2f%7Bpageid%7D%2f%2frevisions</uri>
/// </feature>
/// <expected>Output correct diff</expected>
[Ignore] // Bug 8097
[Test]
public void RevisionHideAndUnhide() {
// 1. Create a page with 3 revisions
// 2. Create a user with Contributor role
// (3) Assert unhidden contents can be viewed by user
// 4. Hide second revision
// (5) Assert first revision remains unhidden
// (6) Assert second revision is hidden
// (7) Assert third revision is unhidden
// (8) Assert admin can view hidden revision contents
// (9) Assert Unauthorized HTTP response returned to user attempting to view hidden revision contents
// (10) Assert Forbidden HTTP response returned to user when attempting to unhide a hidden revision
// (11) Assert user is allowed to hide a revision
// (12) Assert Conflict HTTP response returned to user when attempting to revert to hidden revision
// 13. Delete the page
// 14. Restore page as admin
// (15) Assert restored page persists hidden state
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.SavePage(p, string.Empty, PageUtils.GenerateUniquePageName(), "Rev1", out id, out path);
PageUtils.SavePage(p, path, "Rev2");
PageUtils.SavePage(p, path, "Rev3");
string userid;
string username;
UserUtils.CreateRandomUser(p, "Contributor", out userid, out username);
//Check that anon can see contents before hiding revs
msg = Utils.BuildPlugForUser(username).At("pages", id, "contents").With("revision", 2).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "reg user can't see contents even before hiding!");
//Reinit plug to admin
Utils.BuildPlugForAdmin();
string comment = "just cuz..";
XDoc hideRequestXml = new XDoc("revisions").Start("page").Attr("id", id).Attr("hidden", true).Attr("revision", 2).End();
msg = p.At("pages", id, "revisions").With("comment", comment).PostAsync(hideRequestXml).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Non 200 status hiding revisions");
//Ensure correct revisions coming back is visible + hidden
msg = p.At("pages", id, "revisions").With("revision", 1).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "pages/{id}/revisions?revision=x returned non 200 status");
Assert.IsFalse(msg.ToDocument()["/page[@revision = \"1\"]/@hidden"].AsBool ?? false, "Rev 1 is hidden!");
//validate hidden rev
msg = p.At("pages", id, "revisions").With("revision", 2).GetAsync().Wait();
Assert.IsTrue(msg.ToDocument()["/page[@revision = \"2\"]/@hidden"].AsBool ?? false, "Rev 2 is not hidden!");
Assert.AreEqual(comment, msg.ToDocument()["/page[@revision = \"2\"]/description.hidden"].AsText, "hide comment missing or invalid");
Assert.IsTrue(!string.IsNullOrEmpty(msg.ToDocument()["/page[@revision = \"2\"]/date.hidden"].AsText), "date.hidden missing");
Assert.IsNotNull(msg.ToDocument()["/page[@revision = \"2\"]/user.hiddenby/@id"].AsUInt, "user.hiddenby id missing");
msg = p.At("pages", id, "revisions").With("revision", 3).GetAsync().Wait();
Assert.IsFalse(msg.ToDocument()["/page[@revision = \"3\"]/@hidden"].AsBool ?? false, "Rev 3 is hidden!");
//Ensure admin still has rights to see hidden page contents
msg = p.At("pages", id, "contents").With("revision", 2).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "admin can't see hidden contents!");
//Ensure non-admin cannot see hidden page contents
msg = Utils.BuildPlugForUser(username).At("pages", id, "contents").With("revision", 2).GetAsync().Wait();
Assert.IsTrue(msg.Status == DreamStatus.Unauthorized || msg.Status == DreamStatus.Forbidden, "reg user can still see contents!");
//Attempt to unhide a rev by non admin
hideRequestXml = new XDoc("revisions").Start("page").Attr("id", id).Attr("hidden", false).Attr("revision", 2).End();
msg = p.At("pages", id, "revisions").With("comment", comment).PostAsync(hideRequestXml).Wait();
Assert.AreEqual(DreamStatus.Forbidden, msg.Status, "non admin able to unhide rev");
//Attempt to hide a rev by non admin
hideRequestXml = new XDoc("revisions").Start("page").Attr("id", id).Attr("hidden", true).Attr("revision", 1).End();
msg = p.At("pages", id, "revisions").With("comment", comment).PostAsync(hideRequestXml).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "DELETE holder unable to hide rev");
//revert hidden rev
msg = p.At("pages", id, "revert").With("fromrevision", 2).PostAsync().Wait();
Assert.AreEqual(DreamStatus.Conflict, msg.Status, "able to revert a hidden rev!");
//delete page
msg = p.At("pages", id).DeleteAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "unable to delete page!");
//Reinit plug to admin
Utils.BuildPlugForAdmin();
//undelete page
msg = p.At("archive", "pages", id, "restore").PostAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "unable to restore page!");
//Ensure correct revisions coming back is visible + hidden
msg = p.At("pages", id, "revisions").With("revision", 2).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "pages/{id}/revisions?revision=x returned non 200 status");
Assert.IsTrue(msg.ToDocument()["/page[@revision = \"2\"]/@hidden"].AsBool ?? false, "Rev 2 is no longer hidden after delete/restore!");
}
}
}
| |
/*
* 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.
*/
/* Revised Aug, Sept 2009 by Kitto Flora. ODEDynamics.cs replaces
* ODEVehicleSettings.cs. It and ODEPrim.cs are re-organised:
* ODEPrim.cs contains methods dealing with Prim editing, Prim
* characteristics and Kinetic motion.
* ODEDynamics.cs contains methods dealing with Prim Physical motion
* (dynamics) and the associated settings. Old Linear and angular
* motors for dynamic motion have been replace with MoveLinear()
* and MoveAngular(); 'Physical' is used only to switch ODE dynamic
* simualtion on/off; VEHICAL_TYPE_NONE/VEHICAL_TYPE_<other> is to
* switch between 'VEHICLE' parameter use and general dynamics
* settings use.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using log4net;
using OpenMetaverse;
using Ode.NET;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.OdePlugin
{
public class ODEDynamics
{
public Vehicle Type
{
get { return m_type; }
}
public IntPtr Body
{
get { return m_body; }
}
private int frcount = 0; // Used to limit dynamics debug output to
// every 100th frame
// private OdeScene m_parentScene = null;
private IntPtr m_body = IntPtr.Zero;
// private IntPtr m_jointGroup = IntPtr.Zero;
// private IntPtr m_aMotor = IntPtr.Zero;
// Vehicle properties
private Vehicle m_type = Vehicle.TYPE_NONE; // If a 'VEHICLE', and what kind
// private Quaternion m_referenceFrame = Quaternion.Identity; // Axis modifier
private VehicleFlag m_flags = (VehicleFlag) 0; // Boolean settings:
// HOVER_TERRAIN_ONLY
// HOVER_GLOBAL_HEIGHT
// NO_DEFLECTION_UP
// HOVER_WATER_ONLY
// HOVER_UP_ONLY
// LIMIT_MOTOR_UP
// LIMIT_ROLL_ONLY
private VehicleFlag m_Hoverflags = (VehicleFlag)0;
private Vector3 m_BlockingEndPoint = Vector3.Zero;
private Quaternion m_RollreferenceFrame = Quaternion.Identity;
// Linear properties
private Vector3 m_linearMotorDirection = Vector3.Zero; // velocity requested by LSL, decayed by time
private Vector3 m_linearMotorDirectionLASTSET = Vector3.Zero; // velocity requested by LSL
private Vector3 m_dir = Vector3.Zero; // velocity applied to body
private Vector3 m_linearFrictionTimescale = Vector3.Zero;
private float m_linearMotorDecayTimescale = 0;
private float m_linearMotorTimescale = 0;
private Vector3 m_lastLinearVelocityVector = Vector3.Zero;
private d.Vector3 m_lastPositionVector = new d.Vector3();
// private bool m_LinearMotorSetLastFrame = false;
// private Vector3 m_linearMotorOffset = Vector3.Zero;
//Angular properties
private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor
private int m_angularMotorApply = 0; // application frame counter
private Vector3 m_angularMotorVelocity = Vector3.Zero; // current angular motor velocity
private float m_angularMotorTimescale = 0; // motor angular velocity ramp up rate
private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate
private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate
private Vector3 m_lastAngularVelocity = Vector3.Zero; // what was last applied to body
// private Vector3 m_lastVertAttractor = Vector3.Zero; // what VA was last applied to body
//Deflection properties
// private float m_angularDeflectionEfficiency = 0;
// private float m_angularDeflectionTimescale = 0;
// private float m_linearDeflectionEfficiency = 0;
// private float m_linearDeflectionTimescale = 0;
//Banking properties
// private float m_bankingEfficiency = 0;
// private float m_bankingMix = 0;
// private float m_bankingTimescale = 0;
//Hover and Buoyancy properties
private float m_VhoverHeight = 0f;
// private float m_VhoverEfficiency = 0f;
private float m_VhoverTimescale = 0f;
private float m_VhoverTargetHeight = -1.0f; // if <0 then no hover, else its the current target height
private float m_VehicleBuoyancy = 0f; //KF: m_VehicleBuoyancy is set by VEHICLE_BUOYANCY for a vehicle.
// Modifies gravity. Slider between -1 (double-gravity) and 1 (full anti-gravity)
// KF: So far I have found no good method to combine a script-requested .Z velocity and gravity.
// Therefore only m_VehicleBuoyancy=1 (0g) will use the script-requested .Z velocity.
//Attractor properties
private float m_verticalAttractionEfficiency = 1.0f; // damped
private float m_verticalAttractionTimescale = 500f; // Timescale > 300 means no vert attractor.
internal void ProcessFloatVehicleParam(Vehicle pParam, float pValue)
{
switch (pParam)
{
case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY:
if (pValue < 0.01f) pValue = 0.01f;
// m_angularDeflectionEfficiency = pValue;
break;
case Vehicle.ANGULAR_DEFLECTION_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
// m_angularDeflectionTimescale = pValue;
break;
case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_angularMotorDecayTimescale = pValue;
break;
case Vehicle.ANGULAR_MOTOR_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_angularMotorTimescale = pValue;
break;
case Vehicle.BANKING_EFFICIENCY:
if (pValue < 0.01f) pValue = 0.01f;
// m_bankingEfficiency = pValue;
break;
case Vehicle.BANKING_MIX:
if (pValue < 0.01f) pValue = 0.01f;
// m_bankingMix = pValue;
break;
case Vehicle.BANKING_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
// m_bankingTimescale = pValue;
break;
case Vehicle.BUOYANCY:
if (pValue < -1f) pValue = -1f;
if (pValue > 1f) pValue = 1f;
m_VehicleBuoyancy = pValue;
break;
// case Vehicle.HOVER_EFFICIENCY:
// if (pValue < 0f) pValue = 0f;
// if (pValue > 1f) pValue = 1f;
// m_VhoverEfficiency = pValue;
// break;
case Vehicle.HOVER_HEIGHT:
m_VhoverHeight = pValue;
break;
case Vehicle.HOVER_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_VhoverTimescale = pValue;
break;
case Vehicle.LINEAR_DEFLECTION_EFFICIENCY:
if (pValue < 0.01f) pValue = 0.01f;
// m_linearDeflectionEfficiency = pValue;
break;
case Vehicle.LINEAR_DEFLECTION_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
// m_linearDeflectionTimescale = pValue;
break;
case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_linearMotorDecayTimescale = pValue;
break;
case Vehicle.LINEAR_MOTOR_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_linearMotorTimescale = pValue;
break;
case Vehicle.VERTICAL_ATTRACTION_EFFICIENCY:
if (pValue < 0.1f) pValue = 0.1f; // Less goes unstable
if (pValue > 1.0f) pValue = 1.0f;
m_verticalAttractionEfficiency = pValue;
break;
case Vehicle.VERTICAL_ATTRACTION_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_verticalAttractionTimescale = pValue;
break;
// These are vector properties but the engine lets you use a single float value to
// set all of the components to the same value
case Vehicle.ANGULAR_FRICTION_TIMESCALE:
m_angularFrictionTimescale = new Vector3(pValue, pValue, pValue);
break;
case Vehicle.ANGULAR_MOTOR_DIRECTION:
m_angularMotorDirection = new Vector3(pValue, pValue, pValue);
m_angularMotorApply = 10;
break;
case Vehicle.LINEAR_FRICTION_TIMESCALE:
m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue);
break;
case Vehicle.LINEAR_MOTOR_DIRECTION:
m_linearMotorDirection = new Vector3(pValue, pValue, pValue);
m_linearMotorDirectionLASTSET = new Vector3(pValue, pValue, pValue);
break;
case Vehicle.LINEAR_MOTOR_OFFSET:
// m_linearMotorOffset = new Vector3(pValue, pValue, pValue);
break;
}
}//end ProcessFloatVehicleParam
internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue)
{
switch (pParam)
{
case Vehicle.ANGULAR_FRICTION_TIMESCALE:
m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.ANGULAR_MOTOR_DIRECTION:
m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
// Limit requested angular speed to 2 rps= 4 pi rads/sec
if (m_angularMotorDirection.X > 12.56f) m_angularMotorDirection.X = 12.56f;
if (m_angularMotorDirection.X < - 12.56f) m_angularMotorDirection.X = - 12.56f;
if (m_angularMotorDirection.Y > 12.56f) m_angularMotorDirection.Y = 12.56f;
if (m_angularMotorDirection.Y < - 12.56f) m_angularMotorDirection.Y = - 12.56f;
if (m_angularMotorDirection.Z > 12.56f) m_angularMotorDirection.Z = 12.56f;
if (m_angularMotorDirection.Z < - 12.56f) m_angularMotorDirection.Z = - 12.56f;
m_angularMotorApply = 10;
break;
case Vehicle.LINEAR_FRICTION_TIMESCALE:
m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.LINEAR_MOTOR_DIRECTION:
m_linearMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
m_linearMotorDirectionLASTSET = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.LINEAR_MOTOR_OFFSET:
// m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.BLOCK_EXIT:
m_BlockingEndPoint = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
}
}//end ProcessVectorVehicleParam
internal void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue)
{
switch (pParam)
{
case Vehicle.REFERENCE_FRAME:
// m_referenceFrame = pValue;
break;
case Vehicle.ROLL_FRAME:
m_RollreferenceFrame = pValue;
break;
}
}//end ProcessRotationVehicleParam
internal void ProcessVehicleFlags(int pParam, bool remove)
{
if (remove)
{
if (pParam == -1)
{
m_flags = (VehicleFlag)0;
m_Hoverflags = (VehicleFlag)0;
return;
}
if ((pParam & (int)VehicleFlag.HOVER_GLOBAL_HEIGHT) == (int)VehicleFlag.HOVER_GLOBAL_HEIGHT)
{
if ((m_Hoverflags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != (VehicleFlag)0)
m_Hoverflags &= ~(VehicleFlag.HOVER_GLOBAL_HEIGHT);
}
if ((pParam & (int)VehicleFlag.HOVER_TERRAIN_ONLY) == (int)VehicleFlag.HOVER_TERRAIN_ONLY)
{
if ((m_Hoverflags & VehicleFlag.HOVER_TERRAIN_ONLY) != (VehicleFlag)0)
m_Hoverflags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY);
}
if ((pParam & (int)VehicleFlag.HOVER_UP_ONLY) == (int)VehicleFlag.HOVER_UP_ONLY)
{
if ((m_Hoverflags & VehicleFlag.HOVER_UP_ONLY) != (VehicleFlag)0)
m_Hoverflags &= ~(VehicleFlag.HOVER_UP_ONLY);
}
if ((pParam & (int)VehicleFlag.HOVER_WATER_ONLY) == (int)VehicleFlag.HOVER_WATER_ONLY)
{
if ((m_Hoverflags & VehicleFlag.HOVER_WATER_ONLY) != (VehicleFlag)0)
m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY);
}
if ((pParam & (int)VehicleFlag.LIMIT_MOTOR_UP) == (int)VehicleFlag.LIMIT_MOTOR_UP)
{
if ((m_flags & VehicleFlag.LIMIT_MOTOR_UP) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.LIMIT_MOTOR_UP);
}
if ((pParam & (int)VehicleFlag.LIMIT_ROLL_ONLY) == (int)VehicleFlag.LIMIT_ROLL_ONLY)
{
if ((m_flags & VehicleFlag.LIMIT_ROLL_ONLY) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.LIMIT_ROLL_ONLY);
}
if ((pParam & (int)VehicleFlag.MOUSELOOK_BANK) == (int)VehicleFlag.MOUSELOOK_BANK)
{
if ((m_flags & VehicleFlag.MOUSELOOK_BANK) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.MOUSELOOK_BANK);
}
if ((pParam & (int)VehicleFlag.MOUSELOOK_STEER) == (int)VehicleFlag.MOUSELOOK_STEER)
{
if ((m_flags & VehicleFlag.MOUSELOOK_STEER) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.MOUSELOOK_STEER);
}
if ((pParam & (int)VehicleFlag.NO_DEFLECTION_UP) == (int)VehicleFlag.NO_DEFLECTION_UP)
{
if ((m_flags & VehicleFlag.NO_DEFLECTION_UP) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP);
}
if ((pParam & (int)VehicleFlag.CAMERA_DECOUPLED) == (int)VehicleFlag.CAMERA_DECOUPLED)
{
if ((m_flags & VehicleFlag.CAMERA_DECOUPLED) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.CAMERA_DECOUPLED);
}
if ((pParam & (int)VehicleFlag.NO_X) == (int)VehicleFlag.NO_X)
{
if ((m_flags & VehicleFlag.NO_X) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.NO_X);
}
if ((pParam & (int)VehicleFlag.NO_Y) == (int)VehicleFlag.NO_Y)
{
if ((m_flags & VehicleFlag.NO_Y) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.NO_Y);
}
if ((pParam & (int)VehicleFlag.NO_Z) == (int)VehicleFlag.NO_Z)
{
if ((m_flags & VehicleFlag.NO_Z) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.NO_Z);
}
if ((pParam & (int)VehicleFlag.LOCK_HOVER_HEIGHT) == (int)VehicleFlag.LOCK_HOVER_HEIGHT)
{
if ((m_Hoverflags & VehicleFlag.LOCK_HOVER_HEIGHT) != (VehicleFlag)0)
m_Hoverflags &= ~(VehicleFlag.LOCK_HOVER_HEIGHT);
}
if ((pParam & (int)VehicleFlag.NO_DEFLECTION) == (int)VehicleFlag.NO_DEFLECTION)
{
if ((m_flags & VehicleFlag.NO_DEFLECTION) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.NO_DEFLECTION);
}
if ((pParam & (int)VehicleFlag.LOCK_ROTATION) == (int)VehicleFlag.LOCK_ROTATION)
{
if ((m_flags & VehicleFlag.LOCK_ROTATION) != (VehicleFlag)0)
m_flags &= ~(VehicleFlag.LOCK_ROTATION);
}
}
else
{
if ((pParam & (int)VehicleFlag.HOVER_GLOBAL_HEIGHT) == (int)VehicleFlag.HOVER_GLOBAL_HEIGHT)
{
m_Hoverflags |= (VehicleFlag.HOVER_GLOBAL_HEIGHT | m_flags);
}
if ((pParam & (int)VehicleFlag.HOVER_TERRAIN_ONLY) == (int)VehicleFlag.HOVER_TERRAIN_ONLY)
{
m_Hoverflags |= (VehicleFlag.HOVER_TERRAIN_ONLY | m_flags);
}
if ((pParam & (int)VehicleFlag.HOVER_UP_ONLY) == (int)VehicleFlag.HOVER_UP_ONLY)
{
m_Hoverflags |= (VehicleFlag.HOVER_UP_ONLY | m_flags);
}
if ((pParam & (int)VehicleFlag.HOVER_WATER_ONLY) == (int)VehicleFlag.HOVER_WATER_ONLY)
{
m_Hoverflags |= (VehicleFlag.HOVER_WATER_ONLY | m_flags);
}
if ((pParam & (int)VehicleFlag.LIMIT_MOTOR_UP) == (int)VehicleFlag.LIMIT_MOTOR_UP)
{
m_flags |= (VehicleFlag.LIMIT_MOTOR_UP | m_flags);
}
if ((pParam & (int)VehicleFlag.MOUSELOOK_BANK) == (int)VehicleFlag.MOUSELOOK_BANK)
{
m_flags |= (VehicleFlag.MOUSELOOK_BANK | m_flags);
}
if ((pParam & (int)VehicleFlag.MOUSELOOK_STEER) == (int)VehicleFlag.MOUSELOOK_STEER)
{
m_flags |= (VehicleFlag.MOUSELOOK_STEER | m_flags);
}
if ((pParam & (int)VehicleFlag.NO_DEFLECTION_UP) == (int)VehicleFlag.NO_DEFLECTION_UP)
{
m_flags |= (VehicleFlag.NO_DEFLECTION_UP | m_flags);
}
if ((pParam & (int)VehicleFlag.CAMERA_DECOUPLED) == (int)VehicleFlag.CAMERA_DECOUPLED)
{
m_flags |= (VehicleFlag.CAMERA_DECOUPLED | m_flags);
}
if ((pParam & (int)VehicleFlag.NO_X) == (int)VehicleFlag.NO_X)
{
m_flags |= (VehicleFlag.NO_X);
}
if ((pParam & (int)VehicleFlag.NO_Y) == (int)VehicleFlag.NO_Y)
{
m_flags |= (VehicleFlag.NO_Y);
}
if ((pParam & (int)VehicleFlag.NO_Z) == (int)VehicleFlag.NO_Z)
{
m_flags |= (VehicleFlag.NO_Z);
}
if ((pParam & (int)VehicleFlag.LOCK_HOVER_HEIGHT) == (int)VehicleFlag.LOCK_HOVER_HEIGHT)
{
m_Hoverflags |= (VehicleFlag.LOCK_HOVER_HEIGHT);
}
if ((pParam & (int)VehicleFlag.NO_DEFLECTION) == (int)VehicleFlag.NO_DEFLECTION)
{
m_flags |= (VehicleFlag.NO_DEFLECTION);
}
if ((pParam & (int)VehicleFlag.LOCK_ROTATION) == (int)VehicleFlag.LOCK_ROTATION)
{
m_flags |= (VehicleFlag.LOCK_ROTATION);
}
}
}//end ProcessVehicleFlags
internal void ProcessTypeChange(Vehicle pType)
{
// Set Defaults For Type
m_type = pType;
switch (pType)
{
case Vehicle.TYPE_NONE:
m_linearFrictionTimescale = new Vector3(0, 0, 0);
m_angularFrictionTimescale = new Vector3(0, 0, 0);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 0;
m_linearMotorDecayTimescale = 0;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 0;
m_angularMotorDecayTimescale = 0;
m_VhoverHeight = 0;
m_VhoverTimescale = 0;
m_VehicleBuoyancy = 0;
m_flags = (VehicleFlag)0;
break;
case Vehicle.TYPE_SLED:
m_linearFrictionTimescale = new Vector3(30, 1, 1000);
m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 1000;
m_linearMotorDecayTimescale = 120;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 1000;
m_angularMotorDecayTimescale = 120;
m_VhoverHeight = 0;
// m_VhoverEfficiency = 1;
m_VhoverTimescale = 10;
m_VehicleBuoyancy = 0;
// m_linearDeflectionEfficiency = 1;
// m_linearDeflectionTimescale = 1;
// m_angularDeflectionEfficiency = 1;
// m_angularDeflectionTimescale = 1000;
// m_bankingEfficiency = 0;
// m_bankingMix = 1;
// m_bankingTimescale = 10;
// m_referenceFrame = Quaternion.Identity;
m_Hoverflags &=
~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP);
break;
case Vehicle.TYPE_CAR:
m_linearFrictionTimescale = new Vector3(100, 2, 1000);
m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 1;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 1;
m_angularMotorDecayTimescale = 0.8f;
m_VhoverHeight = 0;
// m_VhoverEfficiency = 0;
m_VhoverTimescale = 1000;
m_VehicleBuoyancy = 0;
// // m_linearDeflectionEfficiency = 1;
// // m_linearDeflectionTimescale = 2;
// // m_angularDeflectionEfficiency = 0;
// m_angularDeflectionTimescale = 10;
m_verticalAttractionEfficiency = 1f;
m_verticalAttractionTimescale = 10f;
// m_bankingEfficiency = -0.2f;
// m_bankingMix = 1;
// m_bankingTimescale = 1;
// m_referenceFrame = Quaternion.Identity;
m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT);
m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY |
VehicleFlag.LIMIT_MOTOR_UP);
m_Hoverflags |= (VehicleFlag.HOVER_UP_ONLY);
break;
case Vehicle.TYPE_BOAT:
m_linearFrictionTimescale = new Vector3(10, 3, 2);
m_angularFrictionTimescale = new Vector3(10,10,10);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 5;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 4;
m_angularMotorDecayTimescale = 4;
m_VhoverHeight = 0;
// m_VhoverEfficiency = 0.5f;
m_VhoverTimescale = 2;
m_VehicleBuoyancy = 1;
// m_linearDeflectionEfficiency = 0.5f;
// m_linearDeflectionTimescale = 3;
// m_angularDeflectionEfficiency = 0.5f;
// m_angularDeflectionTimescale = 5;
m_verticalAttractionEfficiency = 0.5f;
m_verticalAttractionTimescale = 5f;
// m_bankingEfficiency = -0.3f;
// m_bankingMix = 0.8f;
// m_bankingTimescale = 1;
// m_referenceFrame = Quaternion.Identity;
m_Hoverflags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
m_flags &= ~(VehicleFlag.LIMIT_ROLL_ONLY);
m_flags |= (VehicleFlag.NO_DEFLECTION_UP |
VehicleFlag.LIMIT_MOTOR_UP);
m_Hoverflags |= (VehicleFlag.HOVER_WATER_ONLY);
break;
case Vehicle.TYPE_AIRPLANE:
m_linearFrictionTimescale = new Vector3(200, 10, 5);
m_angularFrictionTimescale = new Vector3(20, 20, 20);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 2;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 4;
m_angularMotorDecayTimescale = 4;
m_VhoverHeight = 0;
// m_VhoverEfficiency = 0.5f;
m_VhoverTimescale = 1000;
m_VehicleBuoyancy = 0;
// m_linearDeflectionEfficiency = 0.5f;
// m_linearDeflectionTimescale = 3;
// m_angularDeflectionEfficiency = 1;
// m_angularDeflectionTimescale = 2;
m_verticalAttractionEfficiency = 0.9f;
m_verticalAttractionTimescale = 2f;
// m_bankingEfficiency = 1;
// m_bankingMix = 0.7f;
// m_bankingTimescale = 2;
// m_referenceFrame = Quaternion.Identity;
m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP);
m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY);
break;
case Vehicle.TYPE_BALLOON:
m_linearFrictionTimescale = new Vector3(5, 5, 5);
m_angularFrictionTimescale = new Vector3(10, 10, 10);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 5;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 6;
m_angularMotorDecayTimescale = 10;
m_VhoverHeight = 5;
// m_VhoverEfficiency = 0.8f;
m_VhoverTimescale = 10;
m_VehicleBuoyancy = 1;
// m_linearDeflectionEfficiency = 0;
// m_linearDeflectionTimescale = 5;
// m_angularDeflectionEfficiency = 0;
// m_angularDeflectionTimescale = 5;
m_verticalAttractionEfficiency = 1f;
m_verticalAttractionTimescale = 100f;
// m_bankingEfficiency = 0;
// m_bankingMix = 0.7f;
// m_bankingTimescale = 5;
// m_referenceFrame = Quaternion.Identity;
m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_UP_ONLY);
m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP);
m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY);
m_Hoverflags |= (VehicleFlag.HOVER_GLOBAL_HEIGHT);
break;
}
}//end SetDefaultsForType
internal void Enable(IntPtr pBody, OdeScene pParentScene)
{
if (m_type == Vehicle.TYPE_NONE)
return;
m_body = pBody;
}
internal void Step(float pTimestep, OdeScene pParentScene)
{
if (m_body == IntPtr.Zero || m_type == Vehicle.TYPE_NONE)
return;
frcount++; // used to limit debug comment output
if (frcount > 100)
frcount = 0;
MoveLinear(pTimestep, pParentScene);
MoveAngular(pTimestep);
LimitRotation(pTimestep);
}// end Step
private void MoveLinear(float pTimestep, OdeScene _pParentScene)
{
if (!m_linearMotorDirection.ApproxEquals(Vector3.Zero, 0.01f)) // requested m_linearMotorDirection is significant
{
if (!d.BodyIsEnabled(Body))
d.BodyEnable(Body);
// add drive to body
Vector3 addAmount = m_linearMotorDirection/(m_linearMotorTimescale/pTimestep);
m_lastLinearVelocityVector += (addAmount*10); // lastLinearVelocityVector is the current body velocity vector?
// This will work temporarily, but we really need to compare speed on an axis
// KF: Limit body velocity to applied velocity?
if (Math.Abs(m_lastLinearVelocityVector.X) > Math.Abs(m_linearMotorDirectionLASTSET.X))
m_lastLinearVelocityVector.X = m_linearMotorDirectionLASTSET.X;
if (Math.Abs(m_lastLinearVelocityVector.Y) > Math.Abs(m_linearMotorDirectionLASTSET.Y))
m_lastLinearVelocityVector.Y = m_linearMotorDirectionLASTSET.Y;
if (Math.Abs(m_lastLinearVelocityVector.Z) > Math.Abs(m_linearMotorDirectionLASTSET.Z))
m_lastLinearVelocityVector.Z = m_linearMotorDirectionLASTSET.Z;
// decay applied velocity
Vector3 decayfraction = ((Vector3.One/(m_linearMotorDecayTimescale/pTimestep)));
//Console.WriteLine("decay: " + decayfraction);
m_linearMotorDirection -= m_linearMotorDirection * decayfraction * 0.5f;
//Console.WriteLine("actual: " + m_linearMotorDirection);
}
else
{ // requested is not significant
// if what remains of applied is small, zero it.
if (m_lastLinearVelocityVector.ApproxEquals(Vector3.Zero, 0.01f))
m_lastLinearVelocityVector = Vector3.Zero;
}
// convert requested object velocity to world-referenced vector
m_dir = m_lastLinearVelocityVector;
d.Quaternion rot = d.BodyGetQuaternion(Body);
Quaternion rotq = new Quaternion(rot.X, rot.Y, rot.Z, rot.W); // rotq = rotation of object
m_dir *= rotq; // apply obj rotation to velocity vector
// add Gravity andBuoyancy
// KF: So far I have found no good method to combine a script-requested
// .Z velocity and gravity. Therefore only 0g will used script-requested
// .Z velocity. >0g (m_VehicleBuoyancy < 1) will used modified gravity only.
Vector3 grav = Vector3.Zero;
// There is some gravity, make a gravity force vector
// that is applied after object velocity.
d.Mass objMass;
d.BodyGetMass(Body, out objMass);
// m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g;
grav.Z = _pParentScene.gravityz * objMass.mass * (1f - m_VehicleBuoyancy);
// Preserve the current Z velocity
d.Vector3 vel_now = d.BodyGetLinearVel(Body);
m_dir.Z = vel_now.Z; // Preserve the accumulated falling velocity
d.Vector3 pos = d.BodyGetPosition(Body);
Vector3 accel = new Vector3(-(m_dir.X - m_lastLinearVelocityVector.X / 0.1f), -(m_dir.Y - m_lastLinearVelocityVector.Y / 0.1f), m_dir.Z - m_lastLinearVelocityVector.Z / 0.1f);
Vector3 posChange = new Vector3();
posChange.X = pos.X - m_lastPositionVector.X;
posChange.Y = pos.Y - m_lastPositionVector.Y;
posChange.Z = pos.Z - m_lastPositionVector.Z;
double Zchange = Math.Abs(posChange.Z);
if (m_BlockingEndPoint != Vector3.Zero)
{
if (pos.X >= (m_BlockingEndPoint.X - (float)1))
{
pos.X -= posChange.X + 1;
d.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
if (pos.Y >= (m_BlockingEndPoint.Y - (float)1))
{
pos.Y -= posChange.Y + 1;
d.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
if (pos.Z >= (m_BlockingEndPoint.Z - (float)1))
{
pos.Z -= posChange.Z + 1;
d.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
if (pos.X <= 0)
{
pos.X += posChange.X + 1;
d.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
if (pos.Y <= 0)
{
pos.Y += posChange.Y + 1;
d.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
}
if (pos.Z < _pParentScene.GetTerrainHeightAtXY(pos.X, pos.Y))
{
pos.Z = _pParentScene.GetTerrainHeightAtXY(pos.X, pos.Y) + 2;
d.BodySetPosition(Body, pos.X, pos.Y, pos.Z);
}
// Check if hovering
if ((m_Hoverflags & (VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT)) != 0)
{
// We should hover, get the target height
if ((m_Hoverflags & VehicleFlag.HOVER_WATER_ONLY) != 0)
{
m_VhoverTargetHeight = _pParentScene.GetWaterLevel() + m_VhoverHeight;
}
if ((m_Hoverflags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0)
{
m_VhoverTargetHeight = _pParentScene.GetTerrainHeightAtXY(pos.X, pos.Y) + m_VhoverHeight;
}
if ((m_Hoverflags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != 0)
{
m_VhoverTargetHeight = m_VhoverHeight;
}
if ((m_Hoverflags & VehicleFlag.HOVER_UP_ONLY) != 0)
{
// If body is aready heigher, use its height as target height
if (pos.Z > m_VhoverTargetHeight) m_VhoverTargetHeight = pos.Z;
}
if ((m_Hoverflags & VehicleFlag.LOCK_HOVER_HEIGHT) != 0)
{
if ((pos.Z - m_VhoverTargetHeight) > .2 || (pos.Z - m_VhoverTargetHeight) < -.2)
{
d.BodySetPosition(Body, pos.X, pos.Y, m_VhoverTargetHeight);
}
}
else
{
float herr0 = pos.Z - m_VhoverTargetHeight;
// Replace Vertical speed with correction figure if significant
if (Math.Abs(herr0) > 0.01f)
{
m_dir.Z = -((herr0 * pTimestep * 50.0f) / m_VhoverTimescale);
//KF: m_VhoverEfficiency is not yet implemented
}
else
{
m_dir.Z = 0f;
}
}
// m_VhoverEfficiency = 0f; // 0=boucy, 1=Crit.damped
// m_VhoverTimescale = 0f; // time to acheive height
// pTimestep is time since last frame,in secs
}
if ((m_flags & (VehicleFlag.LIMIT_MOTOR_UP)) != 0)
{
//Start Experimental Values
if (Zchange > .3)
{
grav.Z = (float)(grav.Z * 3);
}
if (Zchange > .15)
{
grav.Z = (float)(grav.Z * 2);
}
if (Zchange > .75)
{
grav.Z = (float)(grav.Z * 1.5);
}
if (Zchange > .05)
{
grav.Z = (float)(grav.Z * 1.25);
}
if (Zchange > .025)
{
grav.Z = (float)(grav.Z * 1.125);
}
float terraintemp = _pParentScene.GetTerrainHeightAtXY(pos.X, pos.Y);
float postemp = (pos.Z - terraintemp);
if (postemp > 2.5f)
{
grav.Z = (float)(grav.Z * 1.037125);
}
//End Experimental Values
}
if ((m_flags & (VehicleFlag.NO_X)) != 0)
{
m_dir.X = 0;
}
if ((m_flags & (VehicleFlag.NO_Y)) != 0)
{
m_dir.Y = 0;
}
if ((m_flags & (VehicleFlag.NO_Z)) != 0)
{
m_dir.Z = 0;
}
m_lastPositionVector = d.BodyGetPosition(Body);
// Apply velocity
d.BodySetLinearVel(Body, m_dir.X, m_dir.Y, m_dir.Z);
// apply gravity force
d.BodyAddForce(Body, grav.X, grav.Y, grav.Z);
// apply friction
Vector3 decayamount = Vector3.One / (m_linearFrictionTimescale / pTimestep);
m_lastLinearVelocityVector -= m_lastLinearVelocityVector * decayamount;
} // end MoveLinear()
private void MoveAngular(float pTimestep)
{
/*
private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor
private int m_angularMotorApply = 0; // application frame counter
private float m_angularMotorVelocity = 0; // current angular motor velocity (ramps up and down)
private float m_angularMotorTimescale = 0; // motor angular velocity ramp up rate
private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate
private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate
private Vector3 m_lastAngularVelocity = Vector3.Zero; // what was last applied to body
*/
// Get what the body is doing, this includes 'external' influences
d.Vector3 angularVelocity = d.BodyGetAngularVel(Body);
// Vector3 angularVelocity = Vector3.Zero;
if (m_angularMotorApply > 0)
{
// ramp up to new value
// current velocity += error / (time to get there / step interval)
// requested speed - last motor speed
m_angularMotorVelocity.X += (m_angularMotorDirection.X - m_angularMotorVelocity.X) / (m_angularMotorTimescale / pTimestep);
m_angularMotorVelocity.Y += (m_angularMotorDirection.Y - m_angularMotorVelocity.Y) / (m_angularMotorTimescale / pTimestep);
m_angularMotorVelocity.Z += (m_angularMotorDirection.Z - m_angularMotorVelocity.Z) / (m_angularMotorTimescale / pTimestep);
m_angularMotorApply--; // This is done so that if script request rate is less than phys frame rate the expected
// velocity may still be acheived.
}
else
{
// no motor recently applied, keep the body velocity
/* m_angularMotorVelocity.X = angularVelocity.X;
m_angularMotorVelocity.Y = angularVelocity.Y;
m_angularMotorVelocity.Z = angularVelocity.Z; */
// and decay the velocity
m_angularMotorVelocity -= m_angularMotorVelocity / (m_angularMotorDecayTimescale / pTimestep);
} // end motor section
// Vertical attractor section
Vector3 vertattr = Vector3.Zero;
if (m_verticalAttractionTimescale < 300)
{
float VAservo = 0.2f / (m_verticalAttractionTimescale * pTimestep);
// get present body rotation
d.Quaternion rot = d.BodyGetQuaternion(Body);
Quaternion rotq = new Quaternion(rot.X, rot.Y, rot.Z, rot.W);
// make a vector pointing up
Vector3 verterr = Vector3.Zero;
verterr.Z = 1.0f;
// rotate it to Body Angle
verterr = verterr * rotq;
// verterr.X and .Y are the World error ammounts. They are 0 when there is no error (Vehicle Body is 'vertical'), and .Z will be 1.
// As the body leans to its side |.X| will increase to 1 and .Z fall to 0. As body inverts |.X| will fall and .Z will go
// negative. Similar for tilt and |.Y|. .X and .Y must be modulated to prevent a stable inverted body.
if (verterr.Z < 0.0f)
{
verterr.X = 2.0f - verterr.X;
verterr.Y = 2.0f - verterr.Y;
}
// Error is 0 (no error) to +/- 2 (max error)
// scale it by VAservo
verterr = verterr * VAservo;
//if (frcount == 0) Console.WriteLine("VAerr=" + verterr);
// As the body rotates around the X axis, then verterr.Y increases; Rotated around Y then .X increases, so
// Change Body angular velocity X based on Y, and Y based on X. Z is not changed.
vertattr.X = verterr.Y;
vertattr.Y = - verterr.X;
vertattr.Z = 0f;
// scaling appears better usingsquare-law
float bounce = 1.0f - (m_verticalAttractionEfficiency * m_verticalAttractionEfficiency);
vertattr.X += bounce * angularVelocity.X;
vertattr.Y += bounce * angularVelocity.Y;
} // else vertical attractor is off
// m_lastVertAttractor = vertattr;
// Bank section tba
// Deflection section tba
// Sum velocities
m_lastAngularVelocity = m_angularMotorVelocity + vertattr; // + bank + deflection
if ((m_flags & (VehicleFlag.NO_DEFLECTION_UP)) != 0)
{
m_lastAngularVelocity.X = 0;
m_lastAngularVelocity.Y = 0;
}
if (!m_lastAngularVelocity.ApproxEquals(Vector3.Zero, 0.01f))
{
if (!d.BodyIsEnabled (Body)) d.BodyEnable (Body);
}
else
{
m_lastAngularVelocity = Vector3.Zero; // Reduce small value to zero.
}
// apply friction
Vector3 decayamount = Vector3.One / (m_angularFrictionTimescale / pTimestep);
m_lastAngularVelocity -= m_lastAngularVelocity * decayamount;
// Apply to the body
d.BodySetAngularVel (Body, m_lastAngularVelocity.X, m_lastAngularVelocity.Y, m_lastAngularVelocity.Z);
} //end MoveAngular
internal void LimitRotation(float timestep)
{
d.Quaternion rot = d.BodyGetQuaternion(Body);
Quaternion rotq = new Quaternion(rot.X, rot.Y, rot.Z, rot.W); // rotq = rotation of object
d.Quaternion m_rot = new d.Quaternion();
bool changed = false;
m_rot.X = rotq.X;
m_rot.Y = rotq.Y;
m_rot.Z = rotq.Z;
m_rot.W = rotq.W;
if (m_RollreferenceFrame != Quaternion.Identity)
{
if (rotq.X >= m_RollreferenceFrame.X)
{
m_rot.X = rotq.X - (m_RollreferenceFrame.X / 2);
}
if (rotq.Y >= m_RollreferenceFrame.Y)
{
m_rot.Y = rotq.Y - (m_RollreferenceFrame.Y / 2);
}
if (rotq.X <= -m_RollreferenceFrame.X)
{
m_rot.X = rotq.X + (m_RollreferenceFrame.X / 2);
}
if (rotq.Y <= -m_RollreferenceFrame.Y)
{
m_rot.Y = rotq.Y + (m_RollreferenceFrame.Y / 2);
}
changed = true;
}
if ((m_flags & VehicleFlag.LOCK_ROTATION) != 0)
{
m_rot.X = 0;
m_rot.Y = 0;
changed = true;
}
if (changed)
d.BodySetQuaternion(Body, ref m_rot);
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Model=UnityEngine.AssetGraph.DataModel.Version2;
namespace UnityEngine.AssetGraph {
[System.Serializable]
[CustomAssetGenerator("Texture Scaler", "v1.0", 1)]
public class TextureScaler : IAssetGenerator {
public enum TextureOutputType
{
PNG,
JPG,
#if UNITY_5_6_OR_NEWER
EXR,
#endif
}
public enum TextureFilterType
{
Point,
Bilinear,
}
[SerializeField] private TextureOutputType m_outputType;
[SerializeField] private TextureFilterType m_filterType;
[SerializeField] private float m_scale = 1.0f;
[SerializeField] private int m_jpgQuality = 100;
#if UNITY_5_6_OR_NEWER
[SerializeField] private Texture2D.EXRFlags m_exrFlags = Texture2D.EXRFlags.CompressZIP;
#endif
public void OnValidate () {
}
public string GetAssetExtension (AssetReference asset) {
switch (m_outputType) {
case TextureOutputType.PNG:
return ".png";
case TextureOutputType.JPG:
return ".jpg";
#if UNITY_5_6_OR_NEWER
case TextureOutputType.EXR:
return ".exr";
#endif
}
return "";
}
public Type GetAssetType(AssetReference asset) {
return typeof(TextureImporter);
}
public bool CanGenerateAsset (AssetReference asset) {
if (asset.importerType != typeof(TextureImporter)) {
throw new NodeException ("Texture Scaler needs texture for source asset.", string.Format("Remove {0} from input.", asset.fileNameAndExtension));
}
var importer = AssetImporter.GetAtPath (asset.importFrom) as TextureImporter;
return importer != null;
}
public bool GenerateAsset (AssetReference asset, string generateAssetPath) {
var tex = AssetDatabase.LoadAssetAtPath<Texture2D>(asset.importFrom);
if (tex == null) {
return false;
}
Texture2D output = null;
switch (m_filterType) {
case TextureFilterType.Bilinear:
output = CreateScaledTextureBL (tex);
break;
case TextureFilterType.Point:
output = CreateScaledTexturePT (tex);
break;
}
Resources.UnloadAsset(tex);
// Encode texture into the EXR
byte[] bytes = null;
switch (m_outputType) {
case TextureOutputType.JPG:
bytes = output.EncodeToJPG();
break;
case TextureOutputType.PNG:
bytes = output.EncodeToPNG();
break;
#if UNITY_5_6_OR_NEWER
case TextureOutputType.EXR:
bytes = output.EncodeToEXR(m_exrFlags);
break;
#endif
}
string fullPath = FileUtility.PathCombine (Directory.GetParent(Application.dataPath).ToString(), generateAssetPath);
File.WriteAllBytes(fullPath, bytes);
Object.DestroyImmediate(output);
return true;
}
private Texture2D CreateDstTexture(Texture2D src) {
int width = (int)(src.width * m_scale);
int height = (int)(src.height * m_scale);
#if UNITY_5_6_OR_NEWER
if (m_outputType == TextureOutputType.EXR) {
return new Texture2D (width, height, TextureFormat.RGBAHalf, false);
} else {
return new Texture2D (width, height);
}
#else
return new Texture2D (width, height);
#endif
}
private Texture2D CreateScaledTexturePT(Texture2D src){
var dst = CreateDstTexture (src);
var dstPix = new Color[dst.width * dst.height];
int y = 0;
while (y < dst.height) {
int x = 0;
while (x < dst.width) {
int srcX = Mathf.FloorToInt(x / m_scale);
int srcY = Mathf.FloorToInt(y / m_scale);
dstPix[y * dst.width + x] = src.GetPixel((int)srcX, (int)srcY);
++x;
}
++y;
}
dst.SetPixels(dstPix);
dst.Apply();
return dst;
}
private Texture2D CreateScaledTextureBL(Texture2D src){
var dst = CreateDstTexture (src);
var dstPix = new Color[dst.width * dst.height];
int y = 0;
while (y < dst.height) {
int x = 0;
while (x < dst.width) {
float xFrac = x * 1.0F / (dst.width - 1);
float yFrac = y * 1.0F / (dst.height - 1);
dstPix[y * dst.width + x] = src.GetPixelBilinear(xFrac, yFrac);
++x;
}
++y;
}
dst.SetPixels(dstPix);
dst.Apply();
return dst;
}
public void OnInspectorGUI (Action onValueChanged) {
var newOutputType = (TextureOutputType)EditorGUILayout.EnumPopup ("Output Format", m_outputType);
if (newOutputType != m_outputType) {
m_outputType = newOutputType;
onValueChanged();
}
if (m_outputType == TextureOutputType.JPG) {
var newQuality = EditorGUILayout.IntSlider ("JPG Quality", m_jpgQuality, 1, 100);
if (newQuality != m_jpgQuality) {
m_jpgQuality = newQuality;
onValueChanged ();
}
}
#if UNITY_5_6_OR_NEWER
if (m_outputType == TextureOutputType.EXR) {
var exrOpt = (Texture2D.EXRFlags)EditorGUILayout.EnumPopup ("EXR Option", m_exrFlags);
if (exrOpt != m_exrFlags) {
m_exrFlags = exrOpt;
onValueChanged ();
}
}
#endif
var newScaleType = (TextureFilterType)EditorGUILayout.EnumPopup ("Filter Mode", m_filterType);
if (newScaleType != m_filterType) {
m_filterType = newScaleType;
onValueChanged();
}
var newScale = EditorGUILayout.Slider ("Scale(%)", m_scale * 100f, 1.0f, 100.0f);
newScale = newScale / 100f;
if (m_scale != newScale) {
m_scale = newScale;
onValueChanged();
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** File: MarshalByRefObject.cs
**
**
**
** Purpose: Defines the root type for all marshal by reference aka
** AppDomain bound types
**
**
**
===========================================================*/
namespace System {
using System;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.Remoting;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Remoting.Services;
#endif
using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MarshalByRefObject
{
#if FEATURE_REMOTING
private Object __identity;
private Object Identity { get { return __identity; } set { __identity = value; } }
#if FEATURE_COMINTEROP
[System.Security.SecuritySafeCritical] // auto-generated
internal IntPtr GetComIUnknown(bool fIsBeingMarshalled)
{
IntPtr pUnk;
if(RemotingServices.IsTransparentProxy(this))
{
pUnk = RemotingServices.GetRealProxy(this).GetCOMIUnknown(fIsBeingMarshalled);
}
else
{
pUnk = Marshal.GetIUnknownForObject(this);
}
return pUnk;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ResourceExposure(ResourceScope.None)]
internal static extern IntPtr GetComIUnknown(MarshalByRefObject o);
#endif // FEATURE_COMINTEROP
// (1) for remote COM objects IsInstance of can't be executed on
// the proxies, so we need this method to be executed on the
// actual object.
// (2) for remote objects that do not have the complete type information
// we intercept calls to check the type and execute it on the actual
// object
internal bool IsInstanceOfType(Type T)
{
return T.IsInstanceOfType(this);
}
// for remote COM Objects the late binding methods can't be
// executed on proxies, so we need this method to execute on
// the real object
internal Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder,
Object[] args,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters)
{
Type t = GetType();
// Sanity check
if(!t.IsCOMObject)
throw new InvalidOperationException(Environment.GetResourceString("Arg_InvokeMember"));
// Call into the runtime to invoke on the COM object.
return t.InvokeMember(name, invokeAttr, binder, this, args, modifiers, culture, namedParameters);
}
// Returns a new cloned MBR instance that is a memberwise copy of this
// with the identity nulled out, so there are no identity conflicts
// when the cloned object is marshalled
protected MarshalByRefObject MemberwiseClone(bool cloneIdentity)
{
MarshalByRefObject mbr = (MarshalByRefObject)base.MemberwiseClone();
// set the identity on the cloned object to null
if (!cloneIdentity)
mbr.Identity = null;
return mbr;
}
// A helper routine to extract the identity either from the marshalbyrefobject base
// class if it is not a proxy, otherwise from the real proxy.
// A flag is set to indicate whether the object passed in is a server or a proxy
[System.Security.SecuritySafeCritical] // auto-generated
internal static Identity GetIdentity(MarshalByRefObject obj, out bool fServer)
{
fServer = true;
Identity id = null;
if(null != obj)
{
if(!RemotingServices.IsTransparentProxy(obj))
{
id = (Identity)obj.Identity;
}
else
{
// Toggle flag to indicate that we have a proxy
fServer = false;
id = RemotingServices.GetRealProxy(obj).IdentityObject;
}
}
return id;
}
// Another helper that delegates to the helper above
internal static Identity GetIdentity(MarshalByRefObject obj)
{
Contract.Assert(!RemotingServices.IsTransparentProxy(obj), "Use this method for server objects only");
bool fServer;
return GetIdentity(obj, out fServer);
}
internal ServerIdentity __RaceSetServerIdentity(ServerIdentity id)
{
if (__identity == null)
{
// For strictly MBR types, the TP field in the identity
// holds the real server
if (!id.IsContextBound)
{
id.RaceSetTransparentProxy(this);
}
Interlocked.CompareExchange(ref __identity, id, null);
}
return (ServerIdentity)__identity;
}
internal void __ResetServerIdentity()
{
__identity = null;
}
// This method is used return a lifetime service object which
// is used to control the lifetime policy to the object.
// For the default Lifetime service this will be an object of typoe ILease.
//
[System.Security.SecurityCritical] // auto-generated_required
public Object GetLifetimeService()
{
return LifetimeServices.GetLease(this);
}
// This method is used return lifetime service object. This method
// can be overridden to return a LifetimeService object with properties unique to
// this object.
// For the default Lifetime service this will be an object of type ILease.
//
[System.Security.SecurityCritical] // auto-generated_required
public virtual Object InitializeLifetimeService()
{
return LifetimeServices.GetLeaseInitial(this);
}
[System.Security.SecurityCritical] // auto-generated_required
public virtual ObjRef CreateObjRef(Type requestedType)
{
if(__identity == null)
{
throw new RemotingException(Environment.GetResourceString(
"Remoting_NoIdentityEntry"));
}
return new ObjRef(this, requestedType);
}
// This is for casting interop ObjRefLite's.
// ObjRefLite's have been deprecated. These methods are not exposed
// through any user APIs and would be removed in the future
[System.Security.SecuritySafeCritical] // auto-generated
internal bool CanCastToXmlType(String xmlTypeName, String xmlTypeNamespace)
{
Type castType = SoapServices.GetInteropTypeFromXmlType(xmlTypeName, xmlTypeNamespace);
if (castType == null)
{
String typeNamespace;
String assemblyName;
if (!SoapServices.DecodeXmlNamespaceForClrTypeNamespace(xmlTypeNamespace,
out typeNamespace, out assemblyName))
return false;
String typeName;
if ((typeNamespace != null) && (typeNamespace.Length > 0))
typeName = typeNamespace + "." + xmlTypeName;
else
typeName = xmlTypeName;
try
{
Assembly asm = Assembly.Load(assemblyName);
castType = asm.GetType(typeName, false, false);
}
catch
{
return false;
}
}
if (castType != null)
return castType.IsAssignableFrom(this.GetType());
return false;
} // CanCastToXmlType
// helper method for calling CanCastToXmlType
// ObjRefLite's have been deprecated. These methods are not exposed
// through any user APIs and would be removed in the future
[System.Security.SecuritySafeCritical] // auto-generated
internal static bool CanCastToXmlTypeHelper(RuntimeType castType, MarshalByRefObject o)
{
if (castType == null)
throw new ArgumentNullException("castType");
Contract.EndContractBlock();
// MarshalByRefObject's can only be casted to MarshalByRefObject's or interfaces.
if (!castType.IsInterface && !castType.IsMarshalByRef)
return false;
// figure out xml type name
String xmlTypeName = null;
String xmlTypeNamespace = null;
if (!SoapServices.GetXmlTypeForInteropType(castType, out xmlTypeName, out xmlTypeNamespace))
{
// There's no registered interop type name, so just use the default.
xmlTypeName = castType.Name;
xmlTypeNamespace =
SoapServices.CodeXmlNamespaceForClrTypeNamespace(
castType.Namespace, castType.GetRuntimeAssembly().GetSimpleName());
}
return o.CanCastToXmlType(xmlTypeName, xmlTypeNamespace);
} // CanCastToXmlType
#endif // FEATURE_REMOTING
}
} // namespace
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace ERY.EMath
{
internal class AGRWriter : IDisposable
{
private System.IO.TextWriter mFile = null;
private string mFilename;
private struct ColorStruct
{
public System.Drawing.Color Color;
public string Name;
public ColorStruct(System.Drawing.Color clr, string colorName)
{
Color = clr;
Name = colorName;
}
}
private List<ColorStruct> mColors = new List<ColorStruct>();
public List<GraphDataSet> mDataSets = new List<GraphDataSet>();
public double xmin = 0;
public double xmax = 1;
public double ymin = 0;
public double ymax = 1;
public double xMajorTick = 0.1;
public double yMajorTick = 0.1;
public int xMinorTicks = 1;
public int yMinorTicks = 1;
public string yAxisLabel = "Y";
public string xAxisLabel = "X";
public string title = "";
public string subtitle = "";
bool mUseSpecialXTicks = false;
Dictionary<int, string> mSpecialXTicks = new Dictionary<int, string>();
public AGRWriter()
{
SetColors();
}
public AGRWriter(string filename)
{
Open(filename);
SetColors();
}
private void SetColors()
{
//"@map color 0 to (255, 255, 255), \"white\"\n" +
//"@map color 1 to (0, 0, 0), \"black\"\n" +
//"@map color 2 to (255, 0, 0), \"red\"\n" +
//"@map color 3 to (0, 255, 0), \"green\"\n" +
//"@map color 4 to (0, 0, 255), \"blue\"\n" +
//"@map color 5 to (255, 255, 0), \"yellow\"\n" +
//"@map color 6 to (188, 143, 143), \"brown\"\n" +
//"@map color 7 to (220, 220, 220), \"grey\"\n" +
//"@map color 8 to (148, 0, 211), \"violet\"\n" +
//"@map color 9 to (0, 255, 255), \"cyan\"\n" +
//"@map color 10 to (255, 0, 255), \"magenta\"\n" +
//"@map color 11 to (255, 165, 0), \"orange\"\n" +
//"@map color 12 to (114, 33, 188), \"indigo\"\n" +
//"@map color 13 to (103, 7, 72), \"maroon\"\n" +
//"@map color 14 to (64, 224, 208), \"turquoise\"\n" +
//"@map color 15 to (0, 139, 0), \"green4\"\n" +
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(255, 255, 255), "white"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(0, 0, 0), "black"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(255, 0, 0), "red"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(0, 255, 0), "green"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(0, 0, 255), "blue"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(255, 255, 0), "yellow"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(188, 143, 143), "brown"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(220, 220, 220), "grey"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(148, 0, 211), "violet"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(0, 255, 255), "cyan"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(255, 0, 255), "magenta"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(255, 165, 0), "orange"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(114, 33, 188), "indigo"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(103, 7, 72), "maroon"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(64, 224, 208), "turquoise"));
mColors.Add(new ColorStruct(System.Drawing.Color.FromArgb(0, 139, 0), "green4"));
}
~AGRWriter()
{
}
public bool Open(string filename)
{
mFilename = filename;
mFile = new System.IO.StreamWriter(mFilename);
if (mFile != null)
return true;
else
return false;
}
public void Write()
{
if (mFile == null)
throw new System.NullReferenceException();
string header =
"# Grace project file \n" +
"#\n" +
"@version 50114\n" +
"@page size 504, 576\n" +
"@page scroll 5%\n" +
"@page inout 5%\n" +
"@link page off\n" +
"@map font 0 to \"Times-Roman\", \"Times-Roman\"\n" +
"@map font 1 to \"Times-Italic\", \"Times-Italic\"\n" +
"@map font 2 to \"Times-Bold\", \"Times-Bold\"\n" +
"@map font 3 to \"Times-BoldItalic\", \"Times-BoldItalic\"\n" +
"@map font 4 to \"Helvetica\", \"Helvetica\"\n" +
"@map font 5 to \"Helvetica-Oblique\", \"Helvetica-Oblique\"\n" +
"@map font 6 to \"Helvetica-Bold\", \"Helvetica-Bold\"\n" +
"@map font 7 to \"Helvetica-BoldOblique\", \"Helvetica-BoldOblique\"\n" +
"@map font 8 to \"Courier\", \"Courier\"\n" +
"@map font 9 to \"Courier-Oblique\", \"Courier-Oblique\"\n" +
"@map font 10 to \"Courier-Bold\", \"Courier-Bold\"\n" +
"@map font 11 to \"Courier-BoldOblique\", \"Courier-BoldOblique\"\n" +
"@map font 12 to \"Symbol\", \"Symbol\"\n" +
"@map font 13 to \"ZapfDingbats\", \"ZapfDingbats\"\n";
for (int i = 0; i < mColors.Count; i++)
{
ColorStruct clr = mColors[i];
header += string.Format("@map color {0} to ({1}, {2}, {3}), \"{4}\"\n",
i, clr.Color.R, clr.Color.G, clr.Color.B, clr.Name);
}
/* "@map color 0 to (255, 255, 255), \"white\"\n" +
"@map color 1 to (0, 0, 0), \"black\"\n" +
"@map color 2 to (255, 0, 0), \"red\"\n" +
"@map color 3 to (0, 255, 0), \"green\"\n" +
"@map color 4 to (0, 0, 255), \"blue\"\n" +
"@map color 5 to (255, 255, 0), \"yellow\"\n" +
"@map color 6 to (188, 143, 143), \"brown\"\n" +
"@map color 7 to (220, 220, 220), \"grey\"\n" +
"@map color 8 to (148, 0, 211), \"violet\"\n" +
"@map color 9 to (0, 255, 255), \"cyan\"\n" +
"@map color 10 to (255, 0, 255), \"magenta\"\n" +
"@map color 11 to (255, 165, 0), \"orange\"\n" +
"@map color 12 to (114, 33, 188), \"indigo\"\n" +
"@map color 13 to (103, 7, 72), \"maroon\"\n" +
"@map color 14 to (64, 224, 208), \"turquoise\"\n" +
"@map color 15 to (0, 139, 0), \"green4\"\n" +
* */
header +=
"@reference date 0\n" +
"@date wrap off\n" +
"@date wrap year 1950\n" +
"@default linewidth 1.0\n" +
"@default linestyle 1\n" +
"@default color 1\n" +
"@default pattern 1\n" +
"@default font 0\n" +
"@default char size 1.000000\n" +
"@default symbol size 1.000000\n" +
"@default sformat \"%.8g\"\n" +
"@background color 0\n" +
"@page background fill on\n" +
"@timestamp off\n" +
"@timestamp 0.03, 0.03\n" +
"@timestamp color 1\n" +
"@timestamp rot 0\n" +
"@timestamp font 0\n" +
"@timestamp char size 1.000000\n" +
"@timestamp def \"Thu Jan 12 16:44:25 2006\"\n" +
"@r0 off\n" +
"@link r0 to g0\n" +
"@r0 type above\n" +
"@r0 linestyle 1\n" +
"@r0 linewidth 1.0\n" +
"@r0 color 1\n" +
"@r0 line 0, 0, 0, 0\n" +
"@r1 off\n" +
"@link r1 to g0\n" +
"@r1 type above\n" +
"@r1 linestyle 1\n" +
"@r1 linewidth 1.0\n" +
"@r1 color 1\n" +
"@r1 line 0, 0, 0, 0\n" +
"@r2 off\n" +
"@link r2 to g0\n" +
"@r2 type above\n" +
"@r2 linestyle 1\n" +
"@r2 linewidth 1.0\n" +
"@r2 color 1\n" +
"@r2 line 0, 0, 0, 0\n" +
"@r3 off\n" +
"@link r3 to g0\n" +
"@r3 type above\n" +
"@r3 linestyle 1\n" +
"@r3 linewidth 1.0\n" +
"@r3 color 1\n" +
"@r3 line 0, 0, 0, 0\n" +
"@r4 off\n" +
"@link r4 to g0\n" +
"@r4 type above\n" +
"@r4 linestyle 1\n" +
"@r4 linewidth 1.0\n" +
"@r4 color 1\n" +
"@r4 line 0, 0, 0, 0\n" +
"@g0 on\n" +
"@g0 hidden false\n" +
"@g0 type XY\n" +
"@g0 stacked false\n" +
"@g0 bar hgap 0.000000\n" +
"@g0 fixedpoint off\n" +
"@g0 fixedpoint type 0\n" +
"@g0 fixedpoint xy 0.000000, 0.000000\n" +
"@g0 fixedpoint format general general\n" +
"@g0 fixedpoint prec 6, 6\n"
;
mFile.Write(header);
// now do the first graph
mFile.Write("@with g0\n");
string graphinfo =
"@ world xmin " + xmin + "\n" +
"@ world xmax " + xmax + "\n" +
"@ world ymin " + ymin + "\n" +
"@ world ymax " + ymax + "\n";
graphinfo +=
"@ stack world 0, 0, 0, 0\n" +
"@ znorm 1\n" +
"@ view xmin 0.120000\n" +
"@ view xmax 0.950000\n" +
"@ view ymin 0.100000\n" +
"@ view ymax 1.030000\n" +
"@ title \"" + title + "\"\n" +
"@ title font 0\n" +
"@ title size 1.500000\n" +
"@ title color 1\n" +
"@ subtitle \"" + subtitle + "\"\n" +
"@ subtitle font 0\n" +
"@ subtitle size 1.000000\n" +
"@ subtitle color 1\n" +
"@ xaxes scale Normal\n" +
"@ yaxes scale Normal\n" +
"@ xaxes invert off\n" +
"@ yaxes invert off\n" +
"@ xaxis on\n" +
"@ xaxis type zero false\n" +
"@ xaxis offset 0.000000 , 0.000000\n" +
"@ xaxis bar on\n" +
"@ xaxis bar color 1\n" +
"@ xaxis bar linestyle 1\n" +
"@ xaxis bar linewidth 1.0\n" +
"@ xaxis label \"" + xAxisLabel + "\"\n" +
"@ xaxis label layout para\n" +
"@ xaxis label place auto\n" +
"@ xaxis label char size 1.000000\n" +
"@ xaxis label font 0\n" +
"@ xaxis label color 1\n" +
"@ xaxis label place normal\n" +
"@ xaxis tick on\n" +
"@ xaxis tick major " + xMajorTick + "\n" +
"@ xaxis tick minor ticks " + xMinorTicks + "\n" +
"@ xaxis tick default 6\n" +
"@ xaxis tick place rounded true\n" +
"@ xaxis tick in\n" +
"@ xaxis tick major size 1.000000\n" +
"@ xaxis tick major color 1\n" +
"@ xaxis tick major linewidth 1.0\n" +
"@ xaxis tick major linestyle 1\n" +
"@ xaxis tick major grid off\n" +
"@ xaxis tick minor color 1\n" +
"@ xaxis tick minor linewidth 1.0\n" +
"@ xaxis tick minor linestyle 1\n" +
"@ xaxis tick minor grid off\n" +
"@ xaxis tick minor size 0.500000\n" +
"@ xaxis ticklabel on\n" +
"@ xaxis ticklabel format general\n" +
"@ xaxis ticklabel prec 5\n" +
"@ xaxis ticklabel formula \"\"\n" +
"@ xaxis ticklabel append \"\"\n" +
"@ xaxis ticklabel prepend \"\"\n" +
"@ xaxis ticklabel angle 0\n" +
"@ xaxis ticklabel skip 0\n" +
"@ xaxis ticklabel stagger 0\n" +
"@ xaxis ticklabel place normal\n" +
"@ xaxis ticklabel offset auto\n" +
"@ xaxis ticklabel offset 0.000000 , 0.010000\n" +
"@ xaxis ticklabel start type auto\n" +
"@ xaxis ticklabel start 0.000000\n" +
"@ xaxis ticklabel stop type auto\n" +
"@ xaxis ticklabel stop 0.000000\n" +
"@ xaxis ticklabel char size 1.000000\n" +
"@ xaxis ticklabel font 0\n" +
"@ xaxis ticklabel color 1\n" +
"@ xaxis tick place both\n";
if (!mUseSpecialXTicks)
{
graphinfo +=
"@ xaxis tick spec type none\n";
}
else
{
graphinfo +=
"@ xaxis tick spec type both\n" +
"@ xaxis tick spec " + mSpecialXTicks.Count + "\n";
int j = 0;
foreach (KeyValuePair<int, string> kvp in mSpecialXTicks)
{
graphinfo +=
"@ xaxis tick major " + j.ToString() + ", " + kvp.Key.ToString() + "\n" +
"@ xaxis ticklabel " + j.ToString() + ", \"" + kvp.Value + "\"\n";
j++;
}
}
graphinfo +=
"@ yaxis on\n" +
"@ yaxis type zero false\n" +
"@ yaxis offset 0.000000 , 0.000000\n" +
"@ yaxis bar on\n" +
"@ yaxis bar color 1\n" +
"@ yaxis bar linestyle 1\n" +
"@ yaxis bar linewidth 1.0\n" +
"@ yaxis label \"" + yAxisLabel + "\"\n" +
"@ yaxis label layout para\n" +
"@ yaxis label place auto\n" +
"@ yaxis label char size 1.000000\n" +
"@ yaxis label font 0\n" +
"@ yaxis label color 1\n" +
"@ yaxis label place normal\n" +
"@ yaxis tick on\n" +
"@ yaxis tick major " + yMajorTick + "\n" +
"@ yaxis tick minor ticks " + yMinorTicks + "\n" +
"@ yaxis tick default 6\n" +
"@ yaxis tick place rounded true\n" +
"@ yaxis tick in\n" +
"@ yaxis tick major size 1.000000\n" +
"@ yaxis tick major color 1\n" +
"@ yaxis tick major linewidth 1.0\n" +
"@ yaxis tick major linestyle 1\n" +
"@ yaxis tick major grid off\n" +
"@ yaxis tick minor color 1\n" +
"@ yaxis tick minor linewidth 1.0\n" +
"@ yaxis tick minor linestyle 1\n" +
"@ yaxis tick minor grid off\n" +
"@ yaxis tick minor size 0.500000\n" +
"@ yaxis ticklabel on\n" +
"@ yaxis ticklabel format general\n" +
"@ yaxis ticklabel prec 5\n" +
"@ yaxis ticklabel formula \"\"\n" +
"@ yaxis ticklabel append \"\"\n" +
"@ yaxis ticklabel prepend \"\"\n" +
"@ yaxis ticklabel angle 0\n" +
"@ yaxis ticklabel skip 0\n" +
"@ yaxis ticklabel stagger 0\n" +
"@ yaxis ticklabel place normal\n" +
"@ yaxis ticklabel offset auto\n" +
"@ yaxis ticklabel offset 0.000000 , 0.010000\n" +
"@ yaxis ticklabel start type auto\n" +
"@ yaxis ticklabel start 0.000000\n" +
"@ yaxis ticklabel stop type auto\n" +
"@ yaxis ticklabel stop 0.000000\n" +
"@ yaxis ticklabel char size 1.000000\n" +
"@ yaxis ticklabel font 0\n" +
"@ yaxis ticklabel color 1\n" +
"@ yaxis tick place both\n" +
"@ yaxis tick spec type none\n" +
"@ altxaxis off\n" +
"@ altyaxis off\n" +
"@ legend on\n" +
"@ legend loctype view\n" +
"@ legend 0.85, 0.8\n" +
"@ legend box color 1\n" +
"@ legend box pattern 1\n" +
"@ legend box linewidth 1.0\n" +
"@ legend box linestyle 1\n" +
"@ legend box fill color 0\n" +
"@ legend box fill pattern 1\n" +
"@ legend font 0\n" +
"@ legend char size 1.000000\n" +
"@ legend color 1\n" +
"@ legend length 4\n" +
"@ legend vgap 1\n" +
"@ legend hgap 1\n" +
"@ legend invert false\n" +
"@ frame type 0\n" +
"@ frame linestyle 1\n" +
"@ frame linewidth 1.0\n" +
"@ frame color 1\n" +
"@ frame pattern 1\n" +
"@ frame background color 0\n" +
"@ frame background pattern 0\n"
;
mFile.Write(graphinfo);
for (int i = 0; i < mDataSets.Count; i++)
{
WriteDataSetHeader(i, mDataSets[i]);
}
for (int i = 0; i < mDataSets.Count; i++)
{
WriteDataSet(i, mDataSets[i]);
}
}
void WriteDataSetHeader(int index, GraphDataSet set)
{
string indexString = "s" + index.ToString();
string colorString = ColorIndex(set.Color).ToString();
int symbol = 0;
if (set.DrawPoints)
{
switch (set.PointType)
{
case GraphDataSet.SymbolType.Square: symbol = 2; break;
case GraphDataSet.SymbolType.Circle: symbol = 1; break;
case GraphDataSet.SymbolType.Point: symbol = 3; break;
}
}
int lineType = 0;
if (set.DrawLine)
{
switch (set.LineStyle)
{
case GraphDataSet.LineType.Solid: lineType = 1; break;
case GraphDataSet.LineType.Dashed: lineType = 2; break;
case GraphDataSet.LineType.Dotted: lineType = 3; break;
}
}
string header =
"@ " + indexString + " hidden false\n" +
"@ " + indexString + " type xy\n" +
"@ " + indexString + " symbol " + symbol + "\n" +
"@ " + indexString + " symbol size 1.000000\n" +
"@ " + indexString + " symbol color " + colorString + "\n" +
"@ " + indexString + " symbol pattern 1\n" +
"@ " + indexString + " symbol fill color 1\n" +
"@ " + indexString + " symbol fill pattern 0\n" +
"@ " + indexString + " symbol linewidth " + set.LineWeight + "\n" +
"@ " + indexString + " symbol linestyle 1\n" +
"@ " + indexString + " symbol char 65\n" +
"@ " + indexString + " symbol char font 0\n" +
"@ " + indexString + " symbol skip 0\n" +
"@ " + indexString + " line type " + lineType + "\n" +
"@ " + indexString + " line linestyle 1\n" +
"@ " + indexString + " line linewidth " + set.LineWeight + "\n" +
"@ " + indexString + " line color " + colorString + "\n" +
"@ " + indexString + " line pattern 1\n" +
"@ " + indexString + " baseline type 0\n" +
"@ " + indexString + " baseline off\n" +
"@ " + indexString + " dropline off\n" +
"@ " + indexString + " fill type 0\n" +
"@ " + indexString + " fill rule 0\n" +
"@ " + indexString + " fill color " + colorString + "\n" +
"@ " + indexString + " fill pattern 1\n" +
"@ " + indexString + " avalue off\n" +
"@ " + indexString + " avalue type 2\n" +
"@ " + indexString + " avalue char size 1.000000\n" +
"@ " + indexString + " avalue font 0\n" +
"@ " + indexString + " avalue color " + colorString + "\n" +
"@ " + indexString + " avalue rot 0\n" +
"@ " + indexString + " avalue format general\n" +
"@ " + indexString + " avalue prec 3\n" +
"@ " + indexString + " avalue prepend \"\"\n" +
"@ " + indexString + " avalue append \"\"\n" +
"@ " + indexString + " avalue offset 0.000000 , 0.000000\n" +
"@ " + indexString + " errorbar on\n" +
"@ " + indexString + " errorbar place both\n" +
"@ " + indexString + " errorbar color " + colorString + "\n" +
"@ " + indexString + " errorbar pattern 1\n" +
"@ " + indexString + " errorbar size 1.000000\n" +
"@ " + indexString + " errorbar linewidth 1.0\n" +
"@ " + indexString + " errorbar linestyle 1\n" +
"@ " + indexString + " errorbar riser linewidth 1.0\n" +
"@ " + indexString + " errorbar riser linestyle 1\n" +
"@ " + indexString + " errorbar riser clip off\n" +
"@ " + indexString + " errorbar riser clip length 0.100000\n" +
"@ " + indexString + " comment \"\"\n" +
"@ " + indexString + " legend \"\"\n"
;
mFile.Write(header);
}
private int ColorIndex(System.Drawing.Color color)
{
// first see if there is an exact match
for (int i = 0; i < mColors.Count; i++)
{
ColorStruct clr = mColors[i];
if (color.Equals(clr.Color))
{
return i;
}
}
// now find best match
int index = 1;
double distance = ColorDistance(mColors[1].Color, color);
for (int i = 2; i < mColors.Count; i++)
{
ColorStruct clr = mColors[i];
if (ColorDistance(color, clr.Color) < distance)
{
distance = ColorDistance(color, clr.Color);
index = i;
}
}
return index;
}
private double ColorDistance(System.Drawing.Color color, System.Drawing.Color color_2)
{
int r = Math.Abs(color.R - color_2.R);
int g = Math.Abs(color.G - color_2.G);
int b = Math.Abs(color.B - color_2.B);
// weight green differences heavier, because of the human eye's sensitivity towards it.
return Math.Sqrt(r * r + 1.5 * g * g + b * b);
}
void WriteDataSet(int index, GraphDataSet set)
{
string indexString = "S" + index.ToString();
mFile.Write("@target G0.{0}\n@type xy\n", indexString);
for (int i = 0; i < set.Count; i++)
{
if (float.IsNaN(set[i].X) || float.IsNaN(set[i].Y))
continue;
if (float.IsInfinity(set[i].X) || float.IsInfinity(set[i].Y))
continue;
mFile.Write("{0} {1}\n", set[i].X, set[i].Y);
}
mFile.Write("&\n");
}
public void AddSpecialXTick(int value, string label)
{
mSpecialXTicks[value] = label;
}
#region IDisposable Members
public void Dispose()
{
if (mFile != null)
mFile.Close();
mFile = null;
}
#endregion
}
}
| |
#pragma warning disable 649
using System;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
[Serializable]
class Window : BaseWindow
{
private const float DefaultNotificationTimeout = 4f;
private const string Title = "GitHub";
private const string LaunchMenu = "Window/GitHub";
private const string BadNotificationDelayError = "A delay of {0} is shorter than the default delay and thus would get pre-empted.";
private const string InitializeTitle = "Initialize";
private const string HistoryTitle = "History";
private const string ChangesTitle = "Changes";
private const string BranchesTitle = "Branches";
private const string SettingsTitle = "Settings";
private const string DefaultRepoUrl = "No remote configured";
private const string Window_RepoUrlTooltip = "Url of the {0} remote";
private const string Window_RepoNoUrlTooltip = "Add a remote in the Settings tab";
private const string Window_RepoBranchTooltip = "Active branch";
[NonSerialized] private double notificationClearTime = -1;
[SerializeField] private SubTab changeTab = SubTab.History;
[SerializeField] private SubTab activeTab = SubTab.History;
[SerializeField] private InitProjectView initProjectView = new InitProjectView();
[SerializeField] private BranchesView branchesView = new BranchesView();
[SerializeField] private ChangesView changesView = new ChangesView();
[SerializeField] private HistoryView historyView = new HistoryView();
[SerializeField] private SettingsView settingsView = new SettingsView();
[SerializeField] private string repoBranch;
[SerializeField] private string repoUrl;
[SerializeField] private GUIContent repoBranchContent;
[SerializeField] private GUIContent repoUrlContent;
[MenuItem(LaunchMenu)]
public static void Window_GitHub()
{
ShowWindow(EntryPoint.ApplicationManager);
}
[MenuItem("GitHub/Show Window")]
public static void GitHub_ShowWindow()
{
ShowWindow(EntryPoint.ApplicationManager);
}
[MenuItem("GitHub/Command Line")]
public static void GitHub_CommandLine()
{
EntryPoint.ApplicationManager.ProcessManager.RunCommandLineWindow(NPath.CurrentDirectory);
}
public static void ShowWindow(IApplicationManager applicationManager)
{
var type = typeof(EditorWindow).Assembly.GetType("UnityEditor.InspectorWindow");
var window = GetWindow<Window>(type);
window.InitializeWindow(applicationManager);
window.Show();
}
public static Window GetWindow()
{
return Resources.FindObjectsOfTypeAll(typeof(Window)).FirstOrDefault() as Window;
}
public override void Initialize(IApplicationManager applicationManager)
{
base.Initialize(applicationManager);
if (!HasRepository && activeTab != SubTab.InitProject && activeTab != SubTab.Settings)
changeTab = activeTab = SubTab.InitProject;
HistoryView.InitializeView(this);
ChangesView.InitializeView(this);
BranchesView.InitializeView(this);
SettingsView.InitializeView(this);
InitProjectView.InitializeView(this);
}
public override void OnEnable()
{
base.OnEnable();
#if DEVELOPER_BUILD
Selection.activeObject = this;
#endif
// Set window title
titleContent = new GUIContent(Title, Styles.SmallLogo);
if (ActiveView != null)
ActiveView.OnEnable();
}
public override void OnDisable()
{
base.OnDisable();
if (ActiveView != null)
ActiveView.OnDisable();
}
public override void OnDataUpdate()
{
base.OnDataUpdate();
string repoRemote = null;
if (MaybeUpdateData(out repoRemote))
{
repoBranchContent = new GUIContent(repoBranch, Window_RepoBranchTooltip);
if (repoUrl != null)
{
repoUrlContent = new GUIContent(repoUrl, string.Format(Window_RepoUrlTooltip, repoRemote));
}
else
{
repoUrlContent = new GUIContent(repoUrl, Window_RepoNoUrlTooltip);
}
}
if (ActiveView != null)
ActiveView.OnDataUpdate();
}
public override void OnRepositoryChanged(IRepository oldRepository)
{
base.OnRepositoryChanged(oldRepository);
DetachHandlers(oldRepository);
AttachHandlers(Repository);
if (Repository != null && activeTab == SubTab.InitProject)
{
changeTab = SubTab.History;
}
UpdateActiveTab();
if (ActiveView != null)
ActiveView.OnRepositoryChanged(oldRepository);
}
public override void OnSelectionChange()
{
base.OnSelectionChange();
if (ActiveView != null)
ActiveView.OnSelectionChange();
}
public override void Refresh()
{
base.Refresh();
if (ActiveView != null)
ActiveView.Refresh();
Repaint();
}
public override void OnUI()
{
base.OnUI();
if (HasRepository)
{
DoHeaderGUI();
}
DoToolbarGUI();
// GUI for the active tab
if (ActiveView != null)
{
ActiveView.OnGUI();
}
}
public override void Update()
{
base.Update();
// Notification auto-clear timer override
if (notificationClearTime > 0f && EditorApplication.timeSinceStartup > notificationClearTime)
{
notificationClearTime = -1f;
RemoveNotification();
Redraw();
}
}
private void RefreshOnMainThread()
{
new ActionTask(TaskManager.Token, Refresh) { Affinity = TaskAffinity.UI }.Start();
}
private bool MaybeUpdateData(out string repoRemote)
{
repoRemote = null;
bool repoDataChanged = false;
if (Repository != null)
{
var currentBranchString = (Repository.CurrentBranch.HasValue ? Repository.CurrentBranch.Value.Name : null);
if (repoBranch != currentBranchString)
{
repoBranch = currentBranchString;
repoDataChanged = true;
}
var url = Repository.CloneUrl != null ? Repository.CloneUrl.ToString() : DefaultRepoUrl;
if (repoUrl != url)
{
repoUrl = url;
repoDataChanged = true;
}
if (Repository.CurrentRemote.HasValue)
repoRemote = Repository.CurrentRemote.Value.Name;
}
else
{
if (repoBranch != null)
{
repoBranch = null;
repoDataChanged = true;
}
if (repoUrl != DefaultRepoUrl)
{
repoUrl = DefaultRepoUrl;
repoDataChanged = true;
}
}
return repoDataChanged;
}
private void AttachHandlers(IRepository repository)
{
if (repository == null)
return;
repository.OnRepositoryInfoChanged += RefreshOnMainThread;
}
private void DetachHandlers(IRepository repository)
{
if (repository == null)
return;
repository.OnRepositoryInfoChanged -= RefreshOnMainThread;
}
private void DoHeaderGUI()
{
GUILayout.BeginHorizontal(Styles.HeaderBoxStyle);
{
GUILayout.Space(3);
GUILayout.BeginVertical(GUILayout.Width(16));
{
GUILayout.Space(9);
GUILayout.Label(Styles.RepoIcon, GUILayout.Height(20), GUILayout.Width(20));
}
GUILayout.EndVertical();
GUILayout.BeginVertical();
{
GUILayout.Space(3);
GUILayout.Label(repoUrlContent, Styles.HeaderRepoLabelStyle);
GUILayout.Space(-2);
GUILayout.Label(repoBranchContent, Styles.HeaderBranchLabelStyle);
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
}
private void DoToolbarGUI()
{
// Subtabs & toolbar
Rect mainNavRect = EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
{
changeTab = activeTab;
EditorGUI.BeginChangeCheck();
{
if (HasRepository)
{
changeTab = TabButton(SubTab.Changes, ChangesTitle, changeTab);
changeTab = TabButton(SubTab.History, HistoryTitle, changeTab);
changeTab = TabButton(SubTab.Branches, BranchesTitle, changeTab);
}
else
{
changeTab = TabButton(SubTab.InitProject, InitializeTitle, changeTab);
}
changeTab = TabButton(SubTab.Settings, SettingsTitle, changeTab);
}
if (EditorGUI.EndChangeCheck())
{
UpdateActiveTab();
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("Account", EditorStyles.toolbarDropDown))
DoAccountDropdown();
}
EditorGUILayout.EndHorizontal();
}
private void UpdateActiveTab()
{
if (changeTab != activeTab)
{
var fromView = ActiveView;
activeTab = changeTab;
SwitchView(fromView, ActiveView);
}
}
private void SwitchView(Subview fromView, Subview toView)
{
GUI.FocusControl(null);
if (fromView != null)
fromView.OnDisable();
toView.OnEnable();
// this triggers a repaint
Repaint();
}
private void DoAccountDropdown()
{
GenericMenu accountMenu = new GenericMenu();
if (!Platform.Keychain.HasKeys)
{
accountMenu.AddItem(new GUIContent("Sign in"), false, SignIn, "sign in");
}
else
{
accountMenu.AddItem(new GUIContent("Go to Profile"), false, GoToProfile, "profile");
accountMenu.AddSeparator("");
accountMenu.AddItem(new GUIContent("Sign out"), false, SignOut, "sign out");
}
accountMenu.ShowAsContext();
}
private void SignIn(object obj)
{
PopupWindow.Open(PopupWindow.PopupViewType.AuthenticationView);
}
private void GoToProfile(object obj)
{
Application.OpenURL(Platform.CredentialManager.CachedCredentials.Host.Combine(Platform.CredentialManager.CachedCredentials.Username));
}
private void SignOut(object obj)
{
UriString host;
if (Repository != null && Repository.CloneUrl != null && Repository.CloneUrl.IsValidUri)
{
host = new UriString(Repository.CloneUrl.ToRepositoryUri()
.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped));
}
else
{
host = UriString.ToUriString(HostAddress.GitHubDotComHostAddress.WebUri);
}
var apiClient = ApiClient.Create(host, Platform.Keychain);
apiClient.Logout(host);
}
public new void ShowNotification(GUIContent content)
{
ShowNotification(content, DefaultNotificationTimeout);
}
public void ShowNotification(GUIContent content, float timeout)
{
Debug.Assert(timeout <= DefaultNotificationTimeout, String.Format(BadNotificationDelayError, timeout));
notificationClearTime = timeout < DefaultNotificationTimeout ? EditorApplication.timeSinceStartup + timeout : -1f;
base.ShowNotification(content);
}
private static SubTab TabButton(SubTab tab, string title, SubTab activeTab)
{
return GUILayout.Toggle(activeTab == tab, title, EditorStyles.toolbarButton) ? tab : activeTab;
}
private Subview ToView(SubTab tab)
{
switch (tab)
{
case SubTab.InitProject:
return initProjectView;
case SubTab.History:
return historyView;
case SubTab.Changes:
return changesView;
case SubTab.Branches:
return branchesView;
case SubTab.Settings:
return settingsView;
default:
throw new ArgumentOutOfRangeException();
}
}
public HistoryView HistoryView
{
get { return historyView; }
}
public ChangesView ChangesView
{
get { return changesView; }
}
public BranchesView BranchesView
{
get { return branchesView; }
}
public SettingsView SettingsView
{
get { return settingsView; }
}
public InitProjectView InitProjectView
{
get { return initProjectView; }
}
private Subview ActiveView
{
get { return ToView(activeTab); }
}
public override bool IsBusy
{
get { return false; }
}
private enum SubTab
{
None,
InitProject,
History,
Changes,
Branches,
Settings
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
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 static partial class ApplicationGatewayOperationsExtensions
{
/// <summary>
/// The Put ApplicationGateway operation creates/updates a
/// ApplicationGateway
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create/delete
/// ApplicationGateway operation
/// </param>
/// <returns>
/// Response of Put ApplicationGateway operation
/// </returns>
public static ApplicationGatewayPutResponse BeginCreateOrUpdating(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).BeginCreateOrUpdatingAsync(resourceGroupName, applicationGatewayName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put ApplicationGateway operation creates/updates a
/// ApplicationGateway
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create/delete
/// ApplicationGateway operation
/// </param>
/// <returns>
/// Response of Put ApplicationGateway operation
/// </returns>
public static Task<ApplicationGatewayPutResponse> BeginCreateOrUpdatingAsync(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters)
{
return operations.BeginCreateOrUpdatingAsync(resourceGroupName, applicationGatewayName, parameters, CancellationToken.None);
}
/// <summary>
/// The delete applicationgateway operation deletes the specified
/// applicationgateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the applicationgateway.
/// </param>
/// <returns>
/// If the resource provide needs to return an error to any operation,
/// it should return the appropriate HTTP error code and a message
/// body as can be seen below.The message should be localized per the
/// Accept-Language header specified in the original request such
/// thatit could be directly be exposed to users
/// </returns>
public static UpdateOperationResponse BeginDeleting(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).BeginDeletingAsync(resourceGroupName, applicationGatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete applicationgateway operation deletes the specified
/// applicationgateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the applicationgateway.
/// </param>
/// <returns>
/// If the resource provide needs to return an error to any operation,
/// it should return the appropriate HTTP error code and a message
/// body as can be seen below.The message should be localized per the
/// Accept-Language header specified in the original request such
/// thatit could be directly be exposed to users
/// </returns>
public static Task<UpdateOperationResponse> BeginDeletingAsync(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return operations.BeginDeletingAsync(resourceGroupName, applicationGatewayName, CancellationToken.None);
}
/// <summary>
/// The Start ApplicationGateway operation starts application gatewayin
/// the specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the application gateway.
/// </param>
/// <returns>
/// Response for PutVirtualNetworkGateway Api servive call
/// </returns>
public static VirtualNetworkGatewayPutResponse BeginStart(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).BeginStartAsync(resourceGroupName, applicationGatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Start ApplicationGateway operation starts application gatewayin
/// the specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the application gateway.
/// </param>
/// <returns>
/// Response for PutVirtualNetworkGateway Api servive call
/// </returns>
public static Task<VirtualNetworkGatewayPutResponse> BeginStartAsync(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return operations.BeginStartAsync(resourceGroupName, applicationGatewayName, CancellationToken.None);
}
/// <summary>
/// The STOP ApplicationGateway operation stops application gatewayin
/// the specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the application gateway.
/// </param>
/// <returns>
/// Response for PutVirtualNetworkGateway Api servive call
/// </returns>
public static VirtualNetworkGatewayPutResponse BeginStop(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).BeginStopAsync(resourceGroupName, applicationGatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The STOP ApplicationGateway operation stops application gatewayin
/// the specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the application gateway.
/// </param>
/// <returns>
/// Response for PutVirtualNetworkGateway Api servive call
/// </returns>
public static Task<VirtualNetworkGatewayPutResponse> BeginStopAsync(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return operations.BeginStopAsync(resourceGroupName, applicationGatewayName, CancellationToken.None);
}
/// <summary>
/// The Put ApplicationGateway operation creates/updates a
/// ApplicationGateway
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create/update
/// ApplicationGateway operation
/// </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 static AzureAsyncOperationResponse CreateOrUpdate(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).CreateOrUpdateAsync(resourceGroupName, applicationGatewayName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put ApplicationGateway operation creates/updates a
/// ApplicationGateway
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create/update
/// ApplicationGateway operation
/// </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 static Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, applicationGatewayName, parameters, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the applicationgateway.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).DeleteAsync(resourceGroupName, applicationGatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the applicationgateway.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return operations.DeleteAsync(resourceGroupName, applicationGatewayName, CancellationToken.None);
}
/// <summary>
/// The Get applicationgateway operation retreives information about
/// the specified applicationgateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the applicationgateway.
/// </param>
/// <returns>
/// Response of a GET ApplicationGateway operation
/// </returns>
public static ApplicationGatewayGetResponse Get(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).GetAsync(resourceGroupName, applicationGatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get applicationgateway operation retreives information about
/// the specified applicationgateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the applicationgateway.
/// </param>
/// <returns>
/// Response of a GET ApplicationGateway operation
/// </returns>
public static Task<ApplicationGatewayGetResponse> GetAsync(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return operations.GetAsync(resourceGroupName, applicationGatewayName, CancellationToken.None);
}
/// <summary>
/// The List ApplicationGateway opertion retrieves all the
/// applicationgateways in a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <returns>
/// Response for ListLoadBalancers Api service call
/// </returns>
public static ApplicationGatewayListResponse List(this IApplicationGatewayOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).ListAsync(resourceGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List ApplicationGateway opertion retrieves all the
/// applicationgateways in a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <returns>
/// Response for ListLoadBalancers Api service call
/// </returns>
public static Task<ApplicationGatewayListResponse> ListAsync(this IApplicationGatewayOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName, CancellationToken.None);
}
/// <summary>
/// The List applicationgateway opertion retrieves all the
/// applicationgateways in a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <returns>
/// Response for ListLoadBalancers Api service call
/// </returns>
public static ApplicationGatewayListResponse ListAll(this IApplicationGatewayOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).ListAllAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List applicationgateway opertion retrieves all the
/// applicationgateways in a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <returns>
/// Response for ListLoadBalancers Api service call
/// </returns>
public static Task<ApplicationGatewayListResponse> ListAllAsync(this IApplicationGatewayOperations operations)
{
return operations.ListAllAsync(CancellationToken.None);
}
/// <summary>
/// The Start ApplicationGateway operation starts application gatewayin
/// the specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the application gateway.
/// </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 static AzureAsyncOperationResponse Start(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).StartAsync(resourceGroupName, applicationGatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Start ApplicationGateway operation starts application gatewayin
/// the specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the application gateway.
/// </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 static Task<AzureAsyncOperationResponse> StartAsync(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return operations.StartAsync(resourceGroupName, applicationGatewayName, CancellationToken.None);
}
/// <summary>
/// The STOP ApplicationGateway operation stops application gatewayin
/// the specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the application gateway.
/// </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 static AzureAsyncOperationResponse Stop(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApplicationGatewayOperations)s).StopAsync(resourceGroupName, applicationGatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The STOP ApplicationGateway operation stops application gatewayin
/// the specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.IApplicationGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// Required. The name of the application gateway.
/// </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 static Task<AzureAsyncOperationResponse> StopAsync(this IApplicationGatewayOperations operations, string resourceGroupName, string applicationGatewayName)
{
return operations.StopAsync(resourceGroupName, applicationGatewayName, CancellationToken.None);
}
}
}
| |
/*
* 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.
*/
// Distributed under the Thrift Software License
//
// See accompanying file LICENSE or visit the Thrift site at:
// http://developers.facebook.com/thrift/
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using Thrift.Collections;
using Thrift.Test; //generated code
using Thrift.Transport;
using Thrift.Protocol;
using Thrift.Server;
namespace Test
{
public class TestServer
{
public class TradeServerEventHandler : TServerEventHandler
{
public int callCount = 0;
public void preServe()
{
callCount++;
}
public Object createContext(Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output)
{
callCount++;
return null;
}
public void deleteContext(Object serverContext, Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output)
{
callCount++;
}
public void processContext(Object serverContext, Thrift.Transport.TTransport transport)
{
callCount++;
}
};
public class TestHandler : ThriftTest.Iface
{
public TServer server;
public TestHandler() { }
public void testVoid()
{
Console.WriteLine("testVoid()");
}
public string testString(string thing)
{
Console.WriteLine("testString(\"" + thing + "\")");
return thing;
}
public bool testBool(bool thing)
{
Console.WriteLine("testBool(" + thing + ")");
return thing;
}
public sbyte testByte(sbyte thing)
{
Console.WriteLine("testByte(" + thing + ")");
return thing;
}
public int testI32(int thing)
{
Console.WriteLine("testI32(" + thing + ")");
return thing;
}
public long testI64(long thing)
{
Console.WriteLine("testI64(" + thing + ")");
return thing;
}
public double testDouble(double thing)
{
Console.WriteLine("testDouble(" + thing + ")");
return thing;
}
public byte[] testBinary(byte[] thing)
{
string hex = BitConverter.ToString(thing).Replace("-", string.Empty);
Console.WriteLine("testBinary(" + hex + ")");
return thing;
}
public Xtruct testStruct(Xtruct thing)
{
Console.WriteLine("testStruct({" +
"\"" + thing.String_thing + "\", " +
thing.Byte_thing + ", " +
thing.I32_thing + ", " +
thing.I64_thing + "})");
return thing;
}
public Xtruct2 testNest(Xtruct2 nest)
{
Xtruct thing = nest.Struct_thing;
Console.WriteLine("testNest({" +
nest.Byte_thing + ", {" +
"\"" + thing.String_thing + "\", " +
thing.Byte_thing + ", " +
thing.I32_thing + ", " +
thing.I64_thing + "}, " +
nest.I32_thing + "})");
return nest;
}
public Dictionary<int, int> testMap(Dictionary<int, int> thing)
{
Console.WriteLine("testMap({");
bool first = true;
foreach (int key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + thing[key]);
}
Console.WriteLine("})");
return thing;
}
public Dictionary<string, string> testStringMap(Dictionary<string, string> thing)
{
Console.WriteLine("testStringMap({");
bool first = true;
foreach (string key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + thing[key]);
}
Console.WriteLine("})");
return thing;
}
public THashSet<int> testSet(THashSet<int> thing)
{
Console.WriteLine("testSet({");
bool first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(elem);
}
Console.WriteLine("})");
return thing;
}
public List<int> testList(List<int> thing)
{
Console.WriteLine("testList({");
bool first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(elem);
}
Console.WriteLine("})");
return thing;
}
public Numberz testEnum(Numberz thing)
{
Console.WriteLine("testEnum(" + thing + ")");
return thing;
}
public long testTypedef(long thing)
{
Console.WriteLine("testTypedef(" + thing + ")");
return thing;
}
public Dictionary<int, Dictionary<int, int>> testMapMap(int hello)
{
Console.WriteLine("testMapMap(" + hello + ")");
Dictionary<int, Dictionary<int, int>> mapmap =
new Dictionary<int, Dictionary<int, int>>();
Dictionary<int, int> pos = new Dictionary<int, int>();
Dictionary<int, int> neg = new Dictionary<int, int>();
for (int i = 1; i < 5; i++)
{
pos[i] = i;
neg[-i] = -i;
}
mapmap[4] = pos;
mapmap[-4] = neg;
return mapmap;
}
public Dictionary<long, Dictionary<Numberz, Insanity>> testInsanity(Insanity argument)
{
Console.WriteLine("testInsanity()");
Xtruct hello = new Xtruct();
hello.String_thing = "Hello2";
hello.Byte_thing = 2;
hello.I32_thing = 2;
hello.I64_thing = 2;
Xtruct goodbye = new Xtruct();
goodbye.String_thing = "Goodbye4";
goodbye.Byte_thing = (sbyte)4;
goodbye.I32_thing = 4;
goodbye.I64_thing = (long)4;
Insanity crazy = new Insanity();
crazy.UserMap = new Dictionary<Numberz, long>();
crazy.UserMap[Numberz.EIGHT] = (long)8;
crazy.Xtructs = new List<Xtruct>();
crazy.Xtructs.Add(goodbye);
Insanity looney = new Insanity();
crazy.UserMap[Numberz.FIVE] = (long)5;
crazy.Xtructs.Add(hello);
Dictionary<Numberz, Insanity> first_map = new Dictionary<Numberz, Insanity>();
Dictionary<Numberz, Insanity> second_map = new Dictionary<Numberz, Insanity>(); ;
first_map[Numberz.TWO] = crazy;
first_map[Numberz.THREE] = crazy;
second_map[Numberz.SIX] = looney;
Dictionary<long, Dictionary<Numberz, Insanity>> insane =
new Dictionary<long, Dictionary<Numberz, Insanity>>();
insane[(long)1] = first_map;
insane[(long)2] = second_map;
return insane;
}
public Xtruct testMulti(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5)
{
Console.WriteLine("testMulti()");
Xtruct hello = new Xtruct(); ;
hello.String_thing = "Hello2";
hello.Byte_thing = arg0;
hello.I32_thing = arg1;
hello.I64_thing = arg2;
return hello;
}
/**
* Print 'testException(%s)' with arg as '%s'
* @param string arg - a string indication what type of exception to throw
* if arg == "Xception" throw Xception with errorCode = 1001 and message = arg
* elsen if arg == "TException" throw TException
* else do not throw anything
*/
public void testException(string arg)
{
Console.WriteLine("testException(" + arg + ")");
if (arg == "Xception")
{
Xception x = new Xception();
x.ErrorCode = 1001;
x.Message = arg;
throw x;
}
if (arg == "TException")
{
throw new Thrift.TException();
}
return;
}
public Xtruct testMultiException(string arg0, string arg1)
{
Console.WriteLine("testMultiException(" + arg0 + ", " + arg1 + ")");
if (arg0 == "Xception")
{
Xception x = new Xception();
x.ErrorCode = 1001;
x.Message = "This is an Xception";
throw x;
}
else if (arg0 == "Xception2")
{
Xception2 x = new Xception2();
x.ErrorCode = 2002;
x.Struct_thing = new Xtruct();
x.Struct_thing.String_thing = "This is an Xception2";
throw x;
}
Xtruct result = new Xtruct();
result.String_thing = arg1;
return result;
}
public void testStop()
{
if (server != null)
{
server.Stop();
}
}
public void testOneway(int arg)
{
Console.WriteLine("testOneway(" + arg + "), sleeping...");
System.Threading.Thread.Sleep(arg * 1000);
Console.WriteLine("testOneway finished");
}
} // class TestHandler
public static bool Execute(string[] args)
{
try
{
bool useBufferedSockets = false, useFramed = false, useEncryption = false, compact = false, json = false;
int port = 9090;
string pipe = null;
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-pipe") // -pipe name
{
pipe = args[++i];
}
else if (args[i].Contains("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
useBufferedSockets = true;
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
useFramed = true;
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
compact = true;
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
json = true;
}
else if (args[i] == "--ssl")
{
useEncryption = true;
}
}
// Processor
TestHandler testHandler = new TestHandler();
ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler);
// Transport
TServerTransport trans;
if( pipe != null)
{
trans = new TNamedPipeServerTransport(pipe);
}
else
{
if (useEncryption)
{
string certPath = "../../../../test/keys/server.p12";
trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath, "thrift"));
}
else
{
trans = new TServerSocket(port, 0, useBufferedSockets);
}
}
TProtocolFactory proto;
if ( compact )
proto = new TCompactProtocol.Factory();
else if ( json )
proto = new TJSONProtocol.Factory();
else
proto = new TBinaryProtocol.Factory();
// Simple Server
TServer serverEngine;
if ( useFramed )
serverEngine = new TSimpleServer(testProcessor, trans, new TFramedTransport.Factory(), proto);
else
serverEngine = new TSimpleServer(testProcessor, trans, new TTransportFactory(), proto);
// ThreadPool Server
// serverEngine = new TThreadPoolServer(testProcessor, tServerSocket);
// Threaded Server
// serverEngine = new TThreadedServer(testProcessor, tServerSocket);
//Server event handler
TradeServerEventHandler serverEvents = new TradeServerEventHandler();
serverEngine.setEventHandler(serverEvents);
testHandler.server = serverEngine;
// Run it
string where = ( pipe != null ? "on pipe "+pipe : "on port " + port);
Console.WriteLine("Starting the server " + where +
(useBufferedSockets ? " with buffered socket" : "") +
(useFramed ? " with framed transport" : "") +
(useEncryption ? " with encryption" : "") +
(compact ? " with compact protocol" : "") +
(json ? " with json protocol" : "") +
"...");
serverEngine.Serve();
}
catch (Exception x)
{
Console.Error.Write(x);
return false;
}
Console.WriteLine("done.");
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ServiceModel.Description
{
using System;
using Microsoft.CodeDom;
using Microsoft.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Net.Security;
using System.Reflection;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
public class ServiceContractGenerator
{
private CodeCompileUnit _compileUnit;
private NamespaceHelper _namespaceManager;
// options
private OptionsHelper _options = new OptionsHelper(ServiceContractGenerationOptions.ChannelInterface |
ServiceContractGenerationOptions.ClientClass);
private Dictionary<ContractDescription, Type> _referencedTypes;
private Dictionary<ContractDescription, ServiceContractGenerationContext> _generatedTypes;
private Dictionary<OperationDescription, OperationContractGenerationContext> _generatedOperations;
private Dictionary<MessageDescription, CodeTypeReference> _generatedTypedMessages;
private Collection<MetadataConversionError> _errors = new Collection<MetadataConversionError>();
public ServiceContractGenerator()
: this(null)
{
}
public ServiceContractGenerator(CodeCompileUnit targetCompileUnit)
{
_compileUnit = targetCompileUnit ?? new CodeCompileUnit();
_namespaceManager = new NamespaceHelper(_compileUnit.Namespaces);
AddReferencedAssembly(typeof(ServiceContractGenerator).GetTypeInfo().Assembly);
_generatedTypes = new Dictionary<ContractDescription, ServiceContractGenerationContext>();
_generatedOperations = new Dictionary<OperationDescription, OperationContractGenerationContext>();
_referencedTypes = new Dictionary<ContractDescription, Type>();
}
internal CodeTypeReference GetCodeTypeReference(Type type)
{
AddReferencedAssembly(type.GetTypeInfo().Assembly);
return new CodeTypeReference(type);
}
internal void AddReferencedAssembly(Assembly assembly)
{
string assemblyName = assembly.GetName().Name;
bool alreadyExisting = false;
foreach (string existingName in _compileUnit.ReferencedAssemblies)
{
if (String.Compare(existingName, assemblyName, StringComparison.OrdinalIgnoreCase) == 0)
{
alreadyExisting = true;
break;
}
}
if (!alreadyExisting)
_compileUnit.ReferencedAssemblies.Add(assemblyName);
}
// options
public ServiceContractGenerationOptions Options
{
get { return _options.Options; }
set { _options = new OptionsHelper(value); }
}
internal OptionsHelper OptionsInternal
{
get { return _options; }
}
public Dictionary<ContractDescription, Type> ReferencedTypes
{
get { return _referencedTypes; }
}
public CodeCompileUnit TargetCompileUnit
{
get { return _compileUnit; }
}
public Dictionary<string, string> NamespaceMappings
{
get { return this.NamespaceManager.NamespaceMappings; }
}
public Collection<MetadataConversionError> Errors
{
get { return _errors; }
}
internal NamespaceHelper NamespaceManager
{
get { return _namespaceManager; }
}
public CodeTypeReference GenerateServiceContractType(ContractDescription contractDescription)
{
CodeTypeReference retVal = GenerateServiceContractTypeInternal(contractDescription);
Microsoft.CodeDom.Compiler.CodeGenerator.ValidateIdentifiers(TargetCompileUnit);
return retVal;
}
private CodeTypeReference GenerateServiceContractTypeInternal(ContractDescription contractDescription)
{
if (contractDescription == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractDescription");
Type existingType;
if (_referencedTypes.TryGetValue(contractDescription, out existingType))
{
return GetCodeTypeReference(existingType);
}
ServiceContractGenerationContext context;
CodeNamespace ns = this.NamespaceManager.EnsureNamespace(contractDescription.Namespace);
if (!_generatedTypes.TryGetValue(contractDescription, out context))
{
context = new ContextInitializer(this, new CodeTypeFactory(this, _options.IsSet(ServiceContractGenerationOptions.InternalTypes))).CreateContext(contractDescription);
ExtensionsHelper.CallContractExtensions(GetBeforeExtensionsBuiltInContractGenerators(), context);
ExtensionsHelper.CallOperationExtensions(GetBeforeExtensionsBuiltInOperationGenerators(), context);
ExtensionsHelper.CallBehaviorExtensions(context);
ExtensionsHelper.CallContractExtensions(GetAfterExtensionsBuiltInContractGenerators(), context);
ExtensionsHelper.CallOperationExtensions(GetAfterExtensionsBuiltInOperationGenerators(), context);
_generatedTypes.Add(contractDescription, context);
}
return context.ContractTypeReference;
}
private IEnumerable<IServiceContractGenerationExtension> GetBeforeExtensionsBuiltInContractGenerators()
{
return EmptyArray<IServiceContractGenerationExtension>.Allocate(0);
}
private IEnumerable<IOperationContractGenerationExtension> GetBeforeExtensionsBuiltInOperationGenerators()
{
yield return new FaultContractAttributeGenerator();
yield return new TransactionFlowAttributeGenerator();
}
private IEnumerable<IServiceContractGenerationExtension> GetAfterExtensionsBuiltInContractGenerators()
{
if (_options.IsSet(ServiceContractGenerationOptions.ChannelInterface))
{
yield return new ChannelInterfaceGenerator();
}
if (_options.IsSet(ServiceContractGenerationOptions.ClientClass))
{
// unless the caller explicitly asks for TM we try to generate a helpful overload if we end up with TM
bool tryAddHelperMethod = !_options.IsSet(ServiceContractGenerationOptions.TypedMessages);
bool generateEventAsyncMethods = _options.IsSet(ServiceContractGenerationOptions.EventBasedAsynchronousMethods);
yield return new ClientClassGenerator(tryAddHelperMethod, generateEventAsyncMethods);
}
}
private IEnumerable<IOperationContractGenerationExtension> GetAfterExtensionsBuiltInOperationGenerators()
{
return EmptyArray<IOperationContractGenerationExtension>.Allocate(0);
}
internal static CodeExpression GetEnumReference<EnumType>(EnumType value)
{
return new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(EnumType)), Enum.Format(typeof(EnumType), value, "G"));
}
internal Dictionary<MessageDescription, CodeTypeReference> GeneratedTypedMessages
{
get
{
if (_generatedTypedMessages == null)
_generatedTypedMessages = new Dictionary<MessageDescription, CodeTypeReference>(MessageDescriptionComparer.Singleton);
return _generatedTypedMessages;
}
}
internal class ContextInitializer
{
private readonly ServiceContractGenerator _parent;
private readonly CodeTypeFactory _typeFactory;
private readonly bool _asyncMethods;
private readonly bool _taskMethod;
private ServiceContractGenerationContext _context;
private UniqueCodeIdentifierScope _contractMemberScope;
private UniqueCodeIdentifierScope _callbackMemberScope;
internal ContextInitializer(ServiceContractGenerator parent, CodeTypeFactory typeFactory)
{
_parent = parent;
_typeFactory = typeFactory;
_asyncMethods = parent.OptionsInternal.IsSet(ServiceContractGenerationOptions.AsynchronousMethods);
_taskMethod = parent.OptionsInternal.IsSet(ServiceContractGenerationOptions.TaskBasedAsynchronousMethod);
}
public ServiceContractGenerationContext CreateContext(ContractDescription contractDescription)
{
VisitContract(contractDescription);
Fx.Assert(_context != null, "context was not initialized");
return _context;
}
// this could usefully be factored into a base class for use by WSDL export and others
private void VisitContract(ContractDescription contract)
{
this.Visit(contract);
foreach (OperationDescription operation in contract.Operations)
{
this.Visit(operation);
// not used in this case
//foreach (MessageDescription message in operation.Messages)
//{
// this.Visit(message);
//}
}
}
private void Visit(ContractDescription contractDescription)
{
bool isDuplex = IsDuplex(contractDescription);
_contractMemberScope = new UniqueCodeIdentifierScope();
_callbackMemberScope = isDuplex ? new UniqueCodeIdentifierScope() : null;
UniqueCodeNamespaceScope codeNamespaceScope = new UniqueCodeNamespaceScope(_parent.NamespaceManager.EnsureNamespace(contractDescription.Namespace));
CodeTypeDeclaration contract = _typeFactory.CreateInterfaceType();
CodeTypeReference contractReference = codeNamespaceScope.AddUnique(contract, contractDescription.CodeName, Strings.DefaultContractName);
CodeTypeDeclaration callbackContract = null;
CodeTypeReference callbackContractReference = null;
if (isDuplex)
{
callbackContract = _typeFactory.CreateInterfaceType();
callbackContractReference = codeNamespaceScope.AddUnique(callbackContract, contractDescription.CodeName + Strings.CallbackTypeSuffix, Strings.DefaultContractName);
}
_context = new ServiceContractGenerationContext(_parent, contractDescription, contract, callbackContract);
_context.Namespace = codeNamespaceScope.CodeNamespace;
_context.TypeFactory = _typeFactory;
_context.ContractTypeReference = contractReference;
_context.DuplexCallbackTypeReference = callbackContractReference;
AddServiceContractAttribute(_context);
}
private void Visit(OperationDescription operationDescription)
{
bool isCallback = operationDescription.IsServerInitiated();
CodeTypeDeclaration declaringType = isCallback ? _context.DuplexCallbackType : _context.ContractType;
UniqueCodeIdentifierScope memberScope = isCallback ? _callbackMemberScope : _contractMemberScope;
Fx.Assert(declaringType != null, "missing callback type");
string syncMethodName = memberScope.AddUnique(operationDescription.CodeName, Strings.DefaultOperationName);
CodeMemberMethod syncMethod = new CodeMemberMethod();
syncMethod.Name = syncMethodName;
declaringType.Members.Add(syncMethod);
OperationContractGenerationContext operationContext;
CodeMemberMethod beginMethod = null;
CodeMemberMethod endMethod = null;
if (_asyncMethods)
{
beginMethod = new CodeMemberMethod();
beginMethod.Name = ServiceReflector.BeginMethodNamePrefix + syncMethodName;
beginMethod.Parameters.Add(new CodeParameterDeclarationExpression(_context.ServiceContractGenerator.GetCodeTypeReference(typeof(AsyncCallback)), Strings.AsyncCallbackArgName));
beginMethod.Parameters.Add(new CodeParameterDeclarationExpression(_context.ServiceContractGenerator.GetCodeTypeReference(typeof(object)), Strings.AsyncStateArgName));
beginMethod.ReturnType = _context.ServiceContractGenerator.GetCodeTypeReference(typeof(IAsyncResult));
declaringType.Members.Add(beginMethod);
endMethod = new CodeMemberMethod();
endMethod.Name = ServiceReflector.EndMethodNamePrefix + syncMethodName;
endMethod.Parameters.Add(new CodeParameterDeclarationExpression(_context.ServiceContractGenerator.GetCodeTypeReference(typeof(IAsyncResult)), Strings.AsyncResultArgName));
declaringType.Members.Add(endMethod);
operationContext = new OperationContractGenerationContext(_parent, _context, operationDescription, declaringType, syncMethod, beginMethod, endMethod);
}
else
{
operationContext = new OperationContractGenerationContext(_parent, _context, operationDescription, declaringType, syncMethod);
}
if (_taskMethod)
{
if (isCallback)
{
if (beginMethod == null)
{
operationContext = new OperationContractGenerationContext(_parent, _context, operationDescription, declaringType, syncMethod);
}
else
{
operationContext = new OperationContractGenerationContext(_parent, _context, operationDescription, declaringType, syncMethod, beginMethod, endMethod);
}
}
else
{
CodeMemberMethod taskBasedAsyncMethod = new CodeMemberMethod { Name = syncMethodName + ServiceReflector.AsyncMethodNameSuffix };
declaringType.Members.Add(taskBasedAsyncMethod);
if (beginMethod == null)
{
operationContext = new OperationContractGenerationContext(_parent, _context, operationDescription, declaringType, syncMethod, taskBasedAsyncMethod);
}
else
{
operationContext = new OperationContractGenerationContext(_parent, _context, operationDescription, declaringType, syncMethod, beginMethod, endMethod, taskBasedAsyncMethod);
}
}
}
operationContext.DeclaringTypeReference = operationDescription.IsServerInitiated() ? _context.DuplexCallbackTypeReference : _context.ContractTypeReference;
_context.Operations.Add(operationContext);
AddOperationContractAttributes(operationContext);
}
private void AddServiceContractAttribute(ServiceContractGenerationContext context)
{
CodeAttributeDeclaration serviceContractAttr = new CodeAttributeDeclaration(context.ServiceContractGenerator.GetCodeTypeReference(typeof(ServiceContractAttribute)));
if (context.ContractType.Name != context.Contract.CodeName)
{
// make sure that decoded Contract name can be used, if not, then override name with encoded value
// specified in wsdl; this only works beacuse our Encoding algorithm will leave alredy encoded names untouched
string friendlyName = NamingHelper.XmlName(context.Contract.CodeName) == context.Contract.Name ? context.Contract.CodeName : context.Contract.Name;
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("Name", new CodePrimitiveExpression(friendlyName)));
}
if (NamingHelper.DefaultNamespace != context.Contract.Namespace)
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(context.Contract.Namespace)));
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("ConfigurationName", new CodePrimitiveExpression(NamespaceHelper.GetCodeTypeReference(context.Namespace, context.ContractType).BaseType)));
if (context.Contract.HasProtectionLevel)
{
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("ProtectionLevel",
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(ProtectionLevel)), context.Contract.ProtectionLevel.ToString())));
}
if (context.DuplexCallbackType != null)
{
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("CallbackContract", new CodeTypeOfExpression(context.DuplexCallbackTypeReference)));
}
if (context.Contract.SessionMode != SessionMode.Allowed)
{
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("SessionMode",
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(SessionMode)), context.Contract.SessionMode.ToString())));
}
context.ContractType.CustomAttributes.Add(serviceContractAttr);
}
private void AddOperationContractAttributes(OperationContractGenerationContext context)
{
if (context.SyncMethod != null)
{
context.SyncMethod.CustomAttributes.Add(CreateOperationContractAttributeDeclaration(context.Operation, false));
}
if (context.BeginMethod != null)
{
context.BeginMethod.CustomAttributes.Add(CreateOperationContractAttributeDeclaration(context.Operation, true));
}
if (context.TaskMethod != null)
{
context.TaskMethod.CustomAttributes.Add(CreateOperationContractAttributeDeclaration(context.Operation, false));
}
}
private CodeAttributeDeclaration CreateOperationContractAttributeDeclaration(OperationDescription operationDescription, bool asyncPattern)
{
CodeAttributeDeclaration serviceOperationAttr = new CodeAttributeDeclaration(_context.ServiceContractGenerator.GetCodeTypeReference(typeof(OperationContractAttribute)));
if (operationDescription.IsOneWay)
{
serviceOperationAttr.Arguments.Add(new CodeAttributeArgument("IsOneWay", new CodePrimitiveExpression(true)));
}
if ((operationDescription.DeclaringContract.SessionMode == SessionMode.Required) && operationDescription.IsTerminating)
{
serviceOperationAttr.Arguments.Add(new CodeAttributeArgument("IsTerminating", new CodePrimitiveExpression(true)));
}
if ((operationDescription.DeclaringContract.SessionMode == SessionMode.Required) && !operationDescription.IsInitiating)
{
serviceOperationAttr.Arguments.Add(new CodeAttributeArgument("IsInitiating", new CodePrimitiveExpression(false)));
}
if (asyncPattern)
{
serviceOperationAttr.Arguments.Add(new CodeAttributeArgument("AsyncPattern", new CodePrimitiveExpression(true)));
}
if (operationDescription.HasProtectionLevel)
{
serviceOperationAttr.Arguments.Add(new CodeAttributeArgument("ProtectionLevel",
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(ProtectionLevel)), operationDescription.ProtectionLevel.ToString())));
}
return serviceOperationAttr;
}
private static bool IsDuplex(ContractDescription contract)
{
foreach (OperationDescription operation in contract.Operations)
if (operation.IsServerInitiated())
return true;
return false;
}
}
private class ChannelInterfaceGenerator : IServiceContractGenerationExtension
{
void IServiceContractGenerationExtension.GenerateContract(ServiceContractGenerationContext context)
{
CodeTypeDeclaration channelType = context.TypeFactory.CreateInterfaceType();
channelType.BaseTypes.Add(context.ContractTypeReference);
channelType.BaseTypes.Add(context.ServiceContractGenerator.GetCodeTypeReference(typeof(IClientChannel)));
new UniqueCodeNamespaceScope(context.Namespace).AddUnique(channelType, context.ContractType.Name + Strings.ChannelTypeSuffix, Strings.ChannelTypeSuffix);
}
}
internal class CodeTypeFactory
{
private ServiceContractGenerator _parent;
private bool _internalTypes;
public CodeTypeFactory(ServiceContractGenerator parent, bool internalTypes)
{
_parent = parent;
_internalTypes = internalTypes;
}
public CodeTypeDeclaration CreateClassType()
{
return CreateCodeType(false);
}
private CodeTypeDeclaration CreateCodeType(bool isInterface)
{
CodeTypeDeclaration codeType = new CodeTypeDeclaration();
codeType.IsClass = !isInterface;
codeType.IsInterface = isInterface;
RunDecorators(codeType);
return codeType;
}
public CodeTypeDeclaration CreateInterfaceType()
{
return CreateCodeType(true);
}
private void RunDecorators(CodeTypeDeclaration codeType)
{
AddPartial(codeType);
AddInternal(codeType);
AddDebuggerStepThroughAttribute(codeType);
AddGeneratedCodeAttribute(codeType);
}
#region CodeTypeDeclaration decorators
private void AddDebuggerStepThroughAttribute(CodeTypeDeclaration codeType)
{
if (codeType.IsClass)
{
codeType.CustomAttributes.Add(new CodeAttributeDeclaration(_parent.GetCodeTypeReference(typeof(DebuggerStepThroughAttribute))));
}
}
private void AddGeneratedCodeAttribute(CodeTypeDeclaration codeType)
{
CodeAttributeDeclaration generatedCodeAttribute = new CodeAttributeDeclaration(_parent.GetCodeTypeReference(typeof(GeneratedCodeAttribute)));
AssemblyName assemblyName = this.GetType().GetTypeInfo().Assembly.GetName();
generatedCodeAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(assemblyName.Name)));
generatedCodeAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(assemblyName.Version.ToString())));
codeType.CustomAttributes.Add(generatedCodeAttribute);
}
private void AddInternal(CodeTypeDeclaration codeType)
{
if (_internalTypes)
{
codeType.TypeAttributes &= ~TypeAttributes.Public;
}
}
private void AddPartial(CodeTypeDeclaration codeType)
{
if (codeType.IsClass)
{
codeType.IsPartial = true;
}
}
#endregion
}
internal static class ExtensionsHelper
{
// calls the behavior extensions
static internal void CallBehaviorExtensions(ServiceContractGenerationContext context)
{
CallContractExtensions(EnumerateBehaviorExtensions(context.Contract), context);
foreach (OperationContractGenerationContext operationContext in context.Operations)
{
CallOperationExtensions(EnumerateBehaviorExtensions(operationContext.Operation), operationContext);
}
}
// calls a specific set of contract-level extensions
static internal void CallContractExtensions(IEnumerable<IServiceContractGenerationExtension> extensions, ServiceContractGenerationContext context)
{
foreach (IServiceContractGenerationExtension extension in extensions)
{
extension.GenerateContract(context);
}
}
// calls a specific set of operation-level extensions on each operation in the contract
static internal void CallOperationExtensions(IEnumerable<IOperationContractGenerationExtension> extensions, ServiceContractGenerationContext context)
{
foreach (OperationContractGenerationContext operationContext in context.Operations)
{
CallOperationExtensions(extensions, operationContext);
}
}
// calls a specific set of operation-level extensions
private static void CallOperationExtensions(IEnumerable<IOperationContractGenerationExtension> extensions, OperationContractGenerationContext context)
{
foreach (IOperationContractGenerationExtension extension in extensions)
{
extension.GenerateOperation(context);
}
}
private static IEnumerable<IServiceContractGenerationExtension> EnumerateBehaviorExtensions(ContractDescription contract)
{
foreach (IContractBehavior behavior in contract.Behaviors)
{
if (behavior is IServiceContractGenerationExtension)
{
yield return (IServiceContractGenerationExtension)behavior;
}
}
}
private static IEnumerable<IOperationContractGenerationExtension> EnumerateBehaviorExtensions(OperationDescription operation)
{
foreach (IOperationBehavior behavior in operation.Behaviors)
{
if (behavior is IOperationContractGenerationExtension)
{
yield return (IOperationContractGenerationExtension)behavior;
}
}
}
}
private class FaultContractAttributeGenerator : IOperationContractGenerationExtension
{
private static CodeTypeReference s_voidTypeReference = new CodeTypeReference(typeof(void));
void IOperationContractGenerationExtension.GenerateOperation(OperationContractGenerationContext context)
{
CodeMemberMethod methodDecl = context.SyncMethod ?? context.BeginMethod;
foreach (FaultDescription fault in context.Operation.Faults)
{
CodeAttributeDeclaration faultAttr = CreateAttrDecl(context, fault);
if (faultAttr != null)
methodDecl.CustomAttributes.Add(faultAttr);
}
}
private static CodeAttributeDeclaration CreateAttrDecl(OperationContractGenerationContext context, FaultDescription fault)
{
CodeTypeReference exceptionTypeReference = fault.DetailType != null ? context.Contract.ServiceContractGenerator.GetCodeTypeReference(fault.DetailType) : fault.DetailTypeReference;
if (exceptionTypeReference == null || exceptionTypeReference == s_voidTypeReference)
return null;
CodeAttributeDeclaration faultContractAttr = new CodeAttributeDeclaration(context.ServiceContractGenerator.GetCodeTypeReference(typeof(FaultContractAttribute)));
faultContractAttr.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(exceptionTypeReference)));
if (fault.Action != null)
faultContractAttr.Arguments.Add(new CodeAttributeArgument("Action", new CodePrimitiveExpression(fault.Action)));
if (fault.HasProtectionLevel)
{
faultContractAttr.Arguments.Add(new CodeAttributeArgument("ProtectionLevel",
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(ProtectionLevel)), fault.ProtectionLevel.ToString())));
}
// override name with encoded value specified in wsdl; this only works beacuse
// our Encoding algorithm will leave alredy encoded names untouched
if (!XmlName.IsNullOrEmpty(fault.ElementName))
faultContractAttr.Arguments.Add(new CodeAttributeArgument("Name", new CodePrimitiveExpression(fault.ElementName.EncodedName)));
if (fault.Namespace != context.Contract.Contract.Namespace)
faultContractAttr.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(fault.Namespace)));
return faultContractAttr;
}
}
private class MessageDescriptionComparer : IEqualityComparer<MessageDescription>
{
static internal MessageDescriptionComparer Singleton = new MessageDescriptionComparer();
private MessageDescriptionComparer() { }
bool IEqualityComparer<MessageDescription>.Equals(MessageDescription x, MessageDescription y)
{
if (x.XsdTypeName != y.XsdTypeName)
return false;
// compare headers
if (x.Headers.Count != y.Headers.Count)
return false;
MessageHeaderDescription[] xHeaders = new MessageHeaderDescription[x.Headers.Count];
x.Headers.CopyTo(xHeaders, 0);
MessageHeaderDescription[] yHeaders = new MessageHeaderDescription[y.Headers.Count];
y.Headers.CopyTo(yHeaders, 0);
if (x.Headers.Count > 1)
{
Array.Sort((MessagePartDescription[])xHeaders, MessagePartDescriptionComparer.Singleton);
Array.Sort((MessagePartDescription[])yHeaders, MessagePartDescriptionComparer.Singleton);
}
for (int i = 0; i < xHeaders.Length; i++)
{
if (MessagePartDescriptionComparer.Singleton.Compare(xHeaders[i], yHeaders[i]) != 0)
return false;
}
return true;
}
int IEqualityComparer<MessageDescription>.GetHashCode(MessageDescription obj)
{
return obj.XsdTypeName.GetHashCode();
}
private class MessagePartDescriptionComparer : IComparer<MessagePartDescription>
{
static internal MessagePartDescriptionComparer Singleton = new MessagePartDescriptionComparer();
private MessagePartDescriptionComparer() { }
public int Compare(MessagePartDescription p1, MessagePartDescription p2)
{
if (null == p1)
{
return (null == p2) ? 0 : -1;
}
if (null == p2)
{
return 1;
}
int i = String.CompareOrdinal(p1.Namespace, p2.Namespace);
if (i == 0)
{
i = String.CompareOrdinal(p1.Name, p2.Name);
}
return i;
}
}
}
internal class NamespaceHelper
{
private static readonly object s_referenceKey = new object();
private const string WildcardNamespaceMapping = "*";
private readonly CodeNamespaceCollection _codeNamespaces;
private Dictionary<string, string> _namespaceMappings;
public NamespaceHelper(CodeNamespaceCollection namespaces)
{
_codeNamespaces = namespaces;
}
public Dictionary<string, string> NamespaceMappings
{
get
{
if (_namespaceMappings == null)
_namespaceMappings = new Dictionary<string, string>();
return _namespaceMappings;
}
}
private string DescriptionToCode(string descriptionNamespace)
{
string target = String.Empty;
// use field to avoid init'ing dictionary if possible
if (_namespaceMappings != null)
{
if (!_namespaceMappings.TryGetValue(descriptionNamespace, out target))
{
// try to fall back to wildcard
if (!_namespaceMappings.TryGetValue(WildcardNamespaceMapping, out target))
{
return String.Empty;
}
}
}
return target;
}
public CodeNamespace EnsureNamespace(string descriptionNamespace)
{
string ns = DescriptionToCode(descriptionNamespace);
CodeNamespace codeNamespace = FindNamespace(ns);
if (codeNamespace == null)
{
codeNamespace = new CodeNamespace(ns);
_codeNamespaces.Add(codeNamespace);
}
return codeNamespace;
}
private CodeNamespace FindNamespace(string ns)
{
foreach (CodeNamespace codeNamespace in _codeNamespaces)
{
if (codeNamespace.Name == ns)
return codeNamespace;
}
return null;
}
public static CodeTypeDeclaration GetCodeType(CodeTypeReference codeTypeReference)
{
return codeTypeReference.UserData[s_referenceKey] as CodeTypeDeclaration;
}
static internal CodeTypeReference GetCodeTypeReference(CodeNamespace codeNamespace, CodeTypeDeclaration codeType)
{
CodeTypeReference codeTypeReference = new CodeTypeReference(String.IsNullOrEmpty(codeNamespace.Name) ? codeType.Name : codeNamespace.Name + '.' + codeType.Name);
codeTypeReference.UserData[s_referenceKey] = codeType;
return codeTypeReference;
}
}
internal struct OptionsHelper
{
public readonly ServiceContractGenerationOptions Options;
public OptionsHelper(ServiceContractGenerationOptions options)
{
this.Options = options;
}
public bool IsSet(ServiceContractGenerationOptions option)
{
Fx.Assert(IsSingleBit((int)option), "");
return ((this.Options & option) != ServiceContractGenerationOptions.None);
}
private static bool IsSingleBit(int x)
{
//figures out if the mode has a single bit set ( is a power of 2)
return (x != 0) && ((x & (x + ~0)) == 0);
}
}
private static class Strings
{
public const string AsyncCallbackArgName = "callback";
public const string AsyncStateArgName = "asyncState";
public const string AsyncResultArgName = "result";
public const string CallbackTypeSuffix = "Callback";
public const string ChannelTypeSuffix = "Channel";
public const string DefaultContractName = "IContract";
public const string DefaultOperationName = "Method";
public const string InterfaceTypePrefix = "I";
}
// ideally this one would appear on TransactionFlowAttribute
private class TransactionFlowAttributeGenerator : IOperationContractGenerationExtension
{
void IOperationContractGenerationExtension.GenerateOperation(OperationContractGenerationContext context)
{
System.ServiceModel.TransactionFlowAttribute attr = context.Operation.Behaviors.Find<System.ServiceModel.TransactionFlowAttribute>();
if (attr != null && attr.Transactions != TransactionFlowOption.NotAllowed)
{
CodeMemberMethod methodDecl = context.SyncMethod ?? context.BeginMethod;
methodDecl.CustomAttributes.Add(CreateAttrDecl(context, attr));
}
}
private static CodeAttributeDeclaration CreateAttrDecl(OperationContractGenerationContext context, TransactionFlowAttribute attr)
{
CodeAttributeDeclaration attrDecl = new CodeAttributeDeclaration(context.Contract.ServiceContractGenerator.GetCodeTypeReference(typeof(TransactionFlowAttribute)));
attrDecl.Arguments.Add(new CodeAttributeArgument(ServiceContractGenerator.GetEnumReference<TransactionFlowOption>(attr.Transactions)));
return attrDecl;
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// Describes a lifecycle hook, which tells Auto Scaling that you want to perform an action
/// when an instance launches or terminates. When you have a lifecycle hook in place,
/// the Auto Scaling group will either:
///
/// <ul> <li>Pause the instance after it launches, but before it is put into service</li>
/// <li>Pause the instance as it terminates, but before it is fully terminated</li> </ul>
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/AutoScalingPendingState.html">Auto
/// Scaling Pending State</a> and <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/AutoScalingTerminatingState.html">Auto
/// Scaling Terminating State</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
/// </summary>
public partial class LifecycleHook
{
private string _autoScalingGroupName;
private string _defaultResult;
private int? _globalTimeout;
private int? _heartbeatTimeout;
private string _lifecycleHookName;
private string _lifecycleTransition;
private string _notificationMetadata;
private string _notificationTargetARN;
private string _roleARN;
/// <summary>
/// Gets and sets the property AutoScalingGroupName.
/// <para>
/// The name of the Auto Scaling group for the lifecycle hook.
/// </para>
/// </summary>
public string AutoScalingGroupName
{
get { return this._autoScalingGroupName; }
set { this._autoScalingGroupName = value; }
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this._autoScalingGroupName != null;
}
/// <summary>
/// Gets and sets the property DefaultResult.
/// <para>
/// Defines the action the Auto Scaling group should take when the lifecycle hook timeout
/// elapses or if an unexpected failure occurs. The valid values are <code>CONTINUE</code>
/// and <code>ABANDON</code>. The default value is <code>CONTINUE</code>.
/// </para>
/// </summary>
public string DefaultResult
{
get { return this._defaultResult; }
set { this._defaultResult = value; }
}
// Check to see if DefaultResult property is set
internal bool IsSetDefaultResult()
{
return this._defaultResult != null;
}
/// <summary>
/// Gets and sets the property GlobalTimeout.
/// <para>
/// The maximum length of time an instance can remain in a <code>Pending:Wait</code> or
/// <code>Terminating:Wait</code> state. Currently, this value is set at 48 hours.
/// </para>
/// </summary>
public int GlobalTimeout
{
get { return this._globalTimeout.GetValueOrDefault(); }
set { this._globalTimeout = value; }
}
// Check to see if GlobalTimeout property is set
internal bool IsSetGlobalTimeout()
{
return this._globalTimeout.HasValue;
}
/// <summary>
/// Gets and sets the property HeartbeatTimeout.
/// <para>
/// The amount of time that can elapse before the lifecycle hook times out. When the lifecycle
/// hook times out, Auto Scaling performs the action defined in the <code>DefaultResult</code>
/// parameter. You can prevent the lifecycle hook from timing out by calling <a>RecordLifecycleActionHeartbeat</a>.
/// </para>
/// </summary>
public int HeartbeatTimeout
{
get { return this._heartbeatTimeout.GetValueOrDefault(); }
set { this._heartbeatTimeout = value; }
}
// Check to see if HeartbeatTimeout property is set
internal bool IsSetHeartbeatTimeout()
{
return this._heartbeatTimeout.HasValue;
}
/// <summary>
/// Gets and sets the property LifecycleHookName.
/// <para>
/// The name of the lifecycle hook.
/// </para>
/// </summary>
public string LifecycleHookName
{
get { return this._lifecycleHookName; }
set { this._lifecycleHookName = value; }
}
// Check to see if LifecycleHookName property is set
internal bool IsSetLifecycleHookName()
{
return this._lifecycleHookName != null;
}
/// <summary>
/// Gets and sets the property LifecycleTransition.
/// <para>
/// The state of the EC2 instance to which you want to attach the lifecycle hook. For
/// a list of lifecycle hook types, see <a>DescribeLifecycleHooks</a>.
/// </para>
/// </summary>
public string LifecycleTransition
{
get { return this._lifecycleTransition; }
set { this._lifecycleTransition = value; }
}
// Check to see if LifecycleTransition property is set
internal bool IsSetLifecycleTransition()
{
return this._lifecycleTransition != null;
}
/// <summary>
/// Gets and sets the property NotificationMetadata.
/// <para>
/// Additional information that you want to include any time Auto Scaling sends a message
/// to the notification target.
/// </para>
/// </summary>
public string NotificationMetadata
{
get { return this._notificationMetadata; }
set { this._notificationMetadata = value; }
}
// Check to see if NotificationMetadata property is set
internal bool IsSetNotificationMetadata()
{
return this._notificationMetadata != null;
}
/// <summary>
/// Gets and sets the property NotificationTargetARN.
/// <para>
/// The ARN of the notification target that Auto Scaling uses to notify you when an instance
/// is in the transition state for the lifecycle hook. This ARN target can be either an
/// SQS queue or an SNS topic. The notification message sent to the target includes the
/// following:
/// </para>
/// <ul> <li>Lifecycle action token</li> <li>User account ID</li> <li>Name of the Auto
/// Scaling group</li> <li>Lifecycle hook name</li> <li>EC2 instance ID</li> <li>Lifecycle
/// transition</li> <li>Notification metadata</li> </ul>
/// </summary>
public string NotificationTargetARN
{
get { return this._notificationTargetARN; }
set { this._notificationTargetARN = value; }
}
// Check to see if NotificationTargetARN property is set
internal bool IsSetNotificationTargetARN()
{
return this._notificationTargetARN != null;
}
/// <summary>
/// Gets and sets the property RoleARN.
/// <para>
/// The ARN of the IAM role that allows the Auto Scaling group to publish to the specified
/// notification target.
/// </para>
/// </summary>
public string RoleARN
{
get { return this._roleARN; }
set { this._roleARN = value; }
}
// Check to see if RoleARN property is set
internal bool IsSetRoleARN()
{
return this._roleARN != null;
}
}
}
| |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Copyright (c) 2011 Andy Pickett
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Text;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
namespace YamlDotNet.RepresentationModel
{
/// <summary>
/// Represents a mapping node in the YAML document.
/// </summary>
[Serializable]
public class YamlMappingNode : YamlNode, IEnumerable<KeyValuePair<YamlNode, YamlNode>>
{
private readonly IDictionary<YamlNode, YamlNode> children = new Dictionary<YamlNode, YamlNode>();
/// <summary>
/// Gets the children of the current node.
/// </summary>
/// <value>The children.</value>
public IDictionary<YamlNode, YamlNode> Children
{
get
{
return children;
}
}
/// <summary>
/// Gets or sets the style of the node.
/// </summary>
/// <value>The style.</value>
public MappingStyle Style {get;set;}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
/// <param name="events">The events.</param>
/// <param name="state">The state.</param>
internal YamlMappingNode(EventReader events, DocumentLoadingState state)
{
MappingStart mapping = events.Expect<MappingStart>();
Load(mapping, state);
bool hasUnresolvedAliases = false;
while (!events.Accept<MappingEnd>())
{
YamlNode key = ParseNode(events, state);
YamlNode value = ParseNode(events, state);
try
{
children.Add(key, value);
}
catch (ArgumentException err)
{
throw new YamlException(key.Start, key.End, "Duplicate key", err);
}
hasUnresolvedAliases |= key is YamlAliasNode || value is YamlAliasNode;
}
if (hasUnresolvedAliases)
{
state.AddNodeWithUnresolvedAliases(this);
}
#if DEBUG
else
{
foreach (var child in children)
{
if (child.Key is YamlAliasNode)
{
throw new InvalidOperationException("Error in alias resolution.");
}
if (child.Value is YamlAliasNode)
{
throw new InvalidOperationException("Error in alias resolution.");
}
}
}
#endif
events.Expect<MappingEnd>();
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
public YamlMappingNode()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
public YamlMappingNode(params KeyValuePair<YamlNode, YamlNode>[] children)
: this((IEnumerable<KeyValuePair<YamlNode, YamlNode>>)children)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
public YamlMappingNode(IEnumerable<KeyValuePair<YamlNode, YamlNode>> children)
{
foreach (var child in children)
{
this.children.Add(child);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
/// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param>
public YamlMappingNode(params YamlNode[] children)
: this((IEnumerable<YamlNode>)children)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
/// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param>
public YamlMappingNode(IEnumerable<YamlNode> children)
{
using (var enumerator = children.GetEnumerator())
{
while (enumerator.MoveNext())
{
var key = enumerator.Current;
if (!enumerator.MoveNext())
{
throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even.");
}
Add(key, enumerator.Current);
}
}
}
/// <summary>
/// Adds the specified mapping to the <see cref="Children"/> collection.
/// </summary>
/// <param name="key">The key node.</param>
/// <param name="value">The value node.</param>
public void Add(YamlNode key, YamlNode value)
{
children.Add(key, value);
}
/// <summary>
/// Adds the specified mapping to the <see cref="Children"/> collection.
/// </summary>
/// <param name="key">The key node.</param>
/// <param name="value">The value node.</param>
public void Add(string key, YamlNode value)
{
children.Add(new YamlScalarNode(key), value);
}
/// <summary>
/// Adds the specified mapping to the <see cref="Children"/> collection.
/// </summary>
/// <param name="key">The key node.</param>
/// <param name="value">The value node.</param>
public void Add(YamlNode key, string value)
{
children.Add(key, new YamlScalarNode(value));
}
/// <summary>
/// Adds the specified mapping to the <see cref="Children"/> collection.
/// </summary>
/// <param name="key">The key node.</param>
/// <param name="value">The value node.</param>
public void Add(string key, string value)
{
children.Add(new YamlScalarNode(key), new YamlScalarNode(value));
}
/// <summary>
/// Resolves the aliases that could not be resolved when the node was created.
/// </summary>
/// <param name="state">The state of the document.</param>
internal override void ResolveAliases(DocumentLoadingState state)
{
Dictionary<YamlNode, YamlNode> keysToUpdate = null;
Dictionary<YamlNode, YamlNode> valuesToUpdate = null;
foreach (var entry in children)
{
if (entry.Key is YamlAliasNode)
{
if (keysToUpdate == null)
{
keysToUpdate = new Dictionary<YamlNode, YamlNode>();
}
keysToUpdate.Add(entry.Key, state.GetNode(entry.Key.Anchor, true, entry.Key.Start, entry.Key.End));
}
if (entry.Value is YamlAliasNode)
{
if (valuesToUpdate == null)
{
valuesToUpdate = new Dictionary<YamlNode, YamlNode>();
}
valuesToUpdate.Add(entry.Key, state.GetNode(entry.Value.Anchor, true, entry.Value.Start, entry.Value.End));
}
}
if (valuesToUpdate != null)
{
foreach (var entry in valuesToUpdate)
{
children[entry.Key] = entry.Value;
}
}
if (keysToUpdate != null)
{
foreach (var entry in keysToUpdate)
{
YamlNode value = children[entry.Key];
children.Remove(entry.Key);
children.Add(entry.Value, value);
}
}
}
/// <summary>
/// Saves the current node to the specified emitter.
/// </summary>
/// <param name="emitter">The emitter where the node is to be saved.</param>
/// <param name="state">The state.</param>
internal override void Emit(IEmitter emitter, EmitterState state)
{
emitter.Emit(new MappingStart(Anchor, Tag, true, Style));
foreach (var entry in children)
{
entry.Key.Save(emitter, state);
entry.Value.Save(emitter, state);
}
emitter.Emit(new MappingEnd());
}
/// <summary>
/// Accepts the specified visitor by calling the appropriate Visit method on it.
/// </summary>
/// <param name="visitor">
/// A <see cref="IYamlVisitor"/>.
/// </param>
public override void Accept(IYamlVisitor visitor)
{
visitor.Visit(this);
}
/// <summary />
public override bool Equals(object other)
{
var obj = other as YamlMappingNode;
if (obj == null || !Equals(obj) || children.Count != obj.children.Count)
{
return false;
}
foreach (var entry in children)
{
YamlNode otherNode;
if (!obj.children.TryGetValue(entry.Key, out otherNode) || !SafeEquals(entry.Value, otherNode))
{
return false;
}
}
return true;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
var hashCode = base.GetHashCode();
foreach (var entry in children)
{
hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Key));
hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Value));
}
return hashCode;
}
/// <summary>
/// Gets all nodes from the document, starting on the current node.
/// </summary>
public override IEnumerable<YamlNode> AllNodes
{
get
{
yield return this;
foreach (var child in children)
{
foreach (var node in child.Key.AllNodes)
{
yield return node;
}
foreach (var node in child.Value.AllNodes)
{
yield return node;
}
}
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var text = new StringBuilder("{ ");
foreach (var child in children)
{
if (text.Length > 2)
{
text.Append(", ");
}
text.Append("{ ").Append(child.Key).Append(", ").Append(child.Value).Append(" }");
}
text.Append(" }");
return text.ToString();
}
#region IEnumerable<KeyValuePair<YamlNode,YamlNode>> Members
/// <summary />
public IEnumerator<KeyValuePair<YamlNode, YamlNode>> GetEnumerator()
{
return children.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Corelicious.Serialization {
public class BinaryFormatterStreamReader {
public ObjectValues Read(Stream stream) {
var context = new ParsingContextImpl(stream);
while(!context.Eof) {
context.ReadRecord(null);
}
Check.That(context.RootId != -1, "Missing RootId");
var rootObject = context.GetObject(context.RootId) as ClassWithMembersAndTypes;
Check.NotNull(rootObject, "rootObject is null. Incorrect type?");
return Build(context, rootObject, rootObject.ClassInfo, rootObject.Values, new Dictionary<Int32, ObjectValues>());
}
private ObjectValues Build(IParsingContext context, Object current, ClassInfo type, Object[] values, IDictionary<Int32, ObjectValues> cache) {
// Check (and return) cached values early so we don't enter an infinite
// loop while resolving references to ourself.
var hasObjectId = current as ISerializedObject;
if (hasObjectId != null && cache.ContainsKey(hasObjectId.ObjectId)) {
return cache[hasObjectId.ObjectId];
}
String libraryName = null;
var hasLibraryId = current as IHasLibraryId;
if (hasLibraryId != null) {
var library = context.GetLibrary(hasLibraryId.LibraryId);
libraryName = library.LibraryName;
}
var target = new ObjectValues(libraryName, type.Name);
if (hasObjectId != null) {
// Store the item in the cache early to avoid infinite loops if
// we have a reference to ourself.
cache[hasObjectId.ObjectId] = target;
}
for(var i = 0; i < values.Length; ++i){
var memberName = type.Members[i];
var value = values[i];
while(value is IValueHolder) {
value = ((IValueHolder)value).GetValue(context);
}
var nestedTypeHolder = value as ITypeHolder;
if (nestedTypeHolder != null) {
var nestedType = nestedTypeHolder.GetClassInfo(context);
var nestedValues = ((ClassRecordBase)value).Values;
Object result;
if (TryBuildSystemType(context, nestedType, nestedValues, out result))
target[memberName] = result;
else
target[memberName] = Build(context, value, nestedType, nestedValues, cache);
} else {
target[memberName] = value;
}
}
return target;
}
private Boolean TryBuildSystemType(IParsingContext context, ClassInfo classInfo, Object[] values, out Object result) {
Func<String, Object> V = name => classInfo.GetValue(name, values);
if (classInfo.Name == "System.Guid") {
result = new Guid((Int32)V("_a"), (Int16)V("_b"), (Int16)V("_c"), (Byte)V("_d"), (Byte)V("_e"), (Byte)V("_f"), (Byte)V("_g"), (Byte)V("_h"), (Byte)V("_i"), (Byte)V("_j"), (Byte)V("_k"));
return true;
}
result = null;
return false;
}
private class ParsingContextImpl : IParsingContext {
private readonly BinaryReader _reader;
private readonly IDictionary<Int32, BinaryLibrary> _libraries;
private readonly IDictionary<Int32, ISerializedObject> _objects;
private readonly SerializationHeaderRecord _headerRecord;
private Boolean _eof;
public Boolean Eof {
get { return _eof; }
}
public Int32 HeaderId {
get { return _headerRecord.HeaderId; }
}
public Int32 RootId {
get { return _headerRecord.RootId; }
}
public ParsingContextImpl(Stream stream) {
_reader = new BinaryReader(stream, Encoding.UTF8);
var recordType = (RecordTypeEnumeration)_reader.ReadByte();
Check.That(recordType == RecordTypeEnumeration.SerializedStreamHeader, "Missing SerializedStreamHeader, got " + recordType);
_headerRecord = new SerializationHeaderRecord(this);
Check.That(_headerRecord.MajorVersion == 1, "MajorVersion must be 1.");
Check.That(_headerRecord.MinorVersion == 0, "MinorVersion must be 0.");
_libraries = new Dictionary<Int32, BinaryLibrary>();
_objects = new Dictionary<Int32, ISerializedObject>();
}
public void AddObject(ISerializedObject obj) {
_objects.Add(obj.ObjectId, obj);
}
public ISerializedObject GetObject(Int32 objectId) {
return _objects[objectId];
}
public BinaryLibrary GetLibrary(Int32 libraryId) {
return _libraries[libraryId];
}
public Object ReadRecord(ISerializedObject parent) {
var recordType = (RecordTypeEnumeration)ReadByte();
switch(recordType) {
case RecordTypeEnumeration.SerializedStreamHeader:
throw new InvalidOperationException("Unexpected record type SerializedStreamHeader at position " + (_reader.BaseStream.Position - 1));
case RecordTypeEnumeration.ClassWithId: { // 1
var obj = new ClassWithId(this);
AddObject(obj);
return obj;
}
case RecordTypeEnumeration.SystemClassWithMembersAndTypes: { // 4
var obj = new SystemClassWithMembersAndTypes(this);
AddObject(obj);
return obj;
}
case RecordTypeEnumeration.ClassWithMembersAndTypes: { // 5
var obj = new ClassWithMembersAndTypes(this);
Check.That(_libraries.ContainsKey(obj.LibraryId), "LibraryId not yet seen.");
AddObject(obj);
return obj;
}
case RecordTypeEnumeration.BinaryObjectString: { // 6
var obj = new BinaryObjectString(this);
AddObject(obj);
return obj;
}
case RecordTypeEnumeration.MemberPrimitiveTyped: { // 8
var obj = new MemberPrimitiveTyped(this);
return obj;
}
case RecordTypeEnumeration.MemberReference: { // 9
var obj = new MemberReference(this);
return obj;
}
case RecordTypeEnumeration.BinaryLibrary: { // 12
var obj = new BinaryLibrary(this);
_libraries.Add(obj.LibraryId, obj);
return null;
}
case RecordTypeEnumeration.ArraySinglePrimitive: { // 15
var obj = new ArraySinglePrimitive(this);
AddObject(obj);
return obj;
}
case RecordTypeEnumeration.ObjectNull: { // 16
return null;
}
case RecordTypeEnumeration.MessageEnd: { // 17
_eof = true;
return null;
}
default:
throw new NotSupportedException("Unsupported record type " + recordType + " at position " + (_reader.BaseStream.Position - 1));
}
}
#region Read* methods
public Boolean ReadBoolean() {
return _reader.ReadBoolean();
}
public SByte ReadSByte() {
return _reader.ReadSByte();
}
public Byte ReadByte() {
return _reader.ReadByte();
}
public Int16 ReadInt16() {
return _reader.ReadInt16();
}
public UInt16 ReadUInt16() {
return _reader.ReadUInt16();
}
public Int32 ReadInt32() {
return _reader.ReadInt32();
}
public UInt32 ReadUInt32() {
return _reader.ReadUInt32();
}
public Int64 ReadInt64() {
return _reader.ReadInt64();
}
public UInt64 ReadUInt64() {
return _reader.ReadUInt64();
}
public Single ReadSingle() {
return _reader.ReadSingle();
}
public Double ReadDouble() {
return _reader.ReadDouble();
}
public Char ReadChar() {
return _reader.ReadChar();
}
public String ReadString() {
return _reader.ReadString();
}
#endregion
}
}
internal interface ISerializedObject {
Int32 ObjectId { get; }
}
internal interface ITypeHolder {
ClassInfo GetClassInfo(IParsingContext context);
}
internal interface IValueHolder {
Object GetValue(IParsingContext context);
}
internal interface IHasLibraryId {
Int32 LibraryId { get; }
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// An HVAC service.
/// </summary>
public class HVACBusiness_Core : TypeCore, IHomeAndConstructionBusiness
{
public HVACBusiness_Core()
{
this._TypeId = 120;
this._Id = "HVACBusiness";
this._Schema_Org_Url = "http://schema.org/HVACBusiness";
string label = "";
GetLabel(out label, "HVACBusiness", typeof(HVACBusiness_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,128};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{128};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// Symbolic names of BCD Elements taken from Geoff Chappell's website:
// http://www.geoffchappell.com/viewer.htm?doc=notes/windows/boot/bcd/elements.htm
//
//
namespace DiscUtils.BootConfig
{
/// <summary>
/// Enumeration of known BCD elements.
/// </summary>
public enum WellKnownElement : int
{
/// <summary>
/// Not specified.
/// </summary>
None = 0,
/// <summary>
/// Device containing the application.
/// </summary>
LibraryApplicationDevice = 0x11000001,
/// <summary>
/// Path to the application.
/// </summary>
LibraryApplicationPath = 0x12000002,
/// <summary>
/// Description of the object.
/// </summary>
LibraryDescription = 0x12000004,
/// <summary>
/// Preferred locale of the object.
/// </summary>
LibraryPreferredLocale = 0x12000005,
/// <summary>
/// Objects containing elements inherited by the object.
/// </summary>
LibraryInheritedObjects = 0x14000006,
/// <summary>
/// Upper bound on physical addresses used by Windows.
/// </summary>
LibraryTruncatePhysicalMemory = 0x15000007,
/// <summary>
/// List of objects, indicating recovery sequence.
/// </summary>
LibraryRecoverySequence = 0x14000008,
/// <summary>
/// Enables auto recovery.
/// </summary>
LibraryAutoRecoveryEnabled = 0x16000009,
/// <summary>
/// List of bad memory regions.
/// </summary>
LibraryBadMemoryList = 0x1700000A,
/// <summary>
/// Allow use of bad memory regions.
/// </summary>
LibraryAllowBadMemoryAccess = 0x1600000B,
/// <summary>
/// Policy on use of first mega-byte of physical RAM.
/// </summary>
/// <remarks>0 = UseNone, 1 = UseAll, 2 = UsePrivate</remarks>
LibraryFirstMegaBytePolicy = 0x1500000C,
/// <summary>
/// Debugger enabled.
/// </summary>
LibraryDebuggerEnabled = 0x16000010,
/// <summary>
/// Debugger type.
/// </summary>
/// <remarks>0 = Serial, 1 = 1394, 2 = USB</remarks>
LibraryDebuggerType = 0x15000011,
/// <summary>
/// Debugger serial port address.
/// </summary>
LibraryDebuggerSerialAddress = 0x15000012,
/// <summary>
/// Debugger serial port.
/// </summary>
LibraryDebuggerSerialPort = 0x15000013,
/// <summary>
/// Debugger serial port baud rate.
/// </summary>
LibraryDebuggerSerialBaudRate = 0x15000014,
/// <summary>
/// Debugger 1394 channel.
/// </summary>
LibraryDebugger1394Channel = 0x15000015,
/// <summary>
/// Debugger USB target name.
/// </summary>
LibraryDebuggerUsbTargetName = 0x12000016,
/// <summary>
/// Debugger ignores user mode exceptions.
/// </summary>
LibraryDebuggerIgnoreUserModeExceptions = 0x16000017,
/// <summary>
/// Debugger start policy.
/// </summary>
/// <remarks>0 = Active, 1 = AutoEnable, 2 = Disable</remarks>
LibraryDebuggerStartPolicy = 0x15000018,
/// <summary>
/// Emergency Management System enabled.
/// </summary>
LibraryEmergencyManagementSystemEnabled = 0x16000020,
/// <summary>
/// Emergency Management System serial port.
/// </summary>
LibraryEmergencyManagementSystemPort = 0x15000022,
/// <summary>
/// Emergency Management System baud rate.
/// </summary>
LibraryEmergencyManagementSystemBaudRate = 0x15000023,
/// <summary>
/// Load options.
/// </summary>
LibraryLoadOptions = 0x12000030,
/// <summary>
/// Displays advanced options.
/// </summary>
LibraryDisplayAdvancedOptions = 0x16000040,
/// <summary>
/// Displays UI to edit advanced options.
/// </summary>
LibraryDisplayOptionsEdit = 0x16000041,
/// <summary>
/// FVE (Full Volume Encryption - aka BitLocker?) KeyRing address.
/// </summary>
LibraryFveKeyRingAddress = 0x16000042,
/// <summary>
/// Device to contain Boot Status Log.
/// </summary>
LibraryBootStatusLogDevice = 0x11000043,
/// <summary>
/// Path to Boot Status Log.
/// </summary>
LibraryBootStatusLogFile = 0x12000044,
/// <summary>
/// Whether to append to the existing Boot Status Log.
/// </summary>
LibraryBootStatusLogAppend = 0x12000045,
/// <summary>
/// Disables graphics mode.
/// </summary>
LibraryGraphicsModeDisabled = 0x16000046,
/// <summary>
/// Configure access policy.
/// </summary>
/// <remarks>0 = default, 1 = DisallowMmConfig</remarks>
LibraryConfigAccessPolicy = 0x15000047,
/// <summary>
/// Disables integrity checks.
/// </summary>
LibraryDisableIntegrityChecks = 0x16000048,
/// <summary>
/// Allows pre-release signatures (test signing).
/// </summary>
LibraryAllowPrereleaseSignatures = 0x16000049,
/// <summary>
/// Console extended input.
/// </summary>
LibraryConsoleExtendedInput = 0x16000050,
/// <summary>
/// Initial console input.
/// </summary>
LibraryInitialConsoleInput = 0x15000051,
/// <summary>
/// Application display order.
/// </summary>
BootMgrDisplayOrder = 0x24000001,
/// <summary>
/// Application boot sequence.
/// </summary>
BootMgrBootSequence = 0x24000002,
/// <summary>
/// Default application.
/// </summary>
BootMgrDefaultObject = 0x23000003,
/// <summary>
/// User input timeout.
/// </summary>
BootMgrTimeout = 0x25000004,
/// <summary>
/// Attempt to resume from hibernated state.
/// </summary>
BootMgrAttemptResume = 0x26000005,
/// <summary>
/// The resume application.
/// </summary>
BootMgrResumeObject = 0x23000006,
/// <summary>
/// The tools display order.
/// </summary>
BootMgrToolsDisplayOrder = 0x24000010,
/// <summary>
/// Displays the boot menu.
/// </summary>
BootMgrDisplayBootMenu = 0x26000020,
/// <summary>
/// No error display.
/// </summary>
BootMgrNoErrorDisplay = 0x26000021,
/// <summary>
/// The BCD device.
/// </summary>
BootMgrBcdDevice = 0x21000022,
/// <summary>
/// The BCD file path.
/// </summary>
BootMgrBcdFilePath = 0x22000023,
/// <summary>
/// The custom actions list.
/// </summary>
BootMgrCustomActionsList = 0x27000030,
/// <summary>
/// Device containing the Operating System.
/// </summary>
OsLoaderOsDevice = 0x21000001,
/// <summary>
/// System root on the OS device.
/// </summary>
OsLoaderSystemRoot = 0x22000002,
/// <summary>
/// The resume application associated with this OS.
/// </summary>
OsLoaderAssociatedResumeObject = 0x23000003,
/// <summary>
/// Auto-detect the correct kernel & HAL.
/// </summary>
OsLoaderDetectKernelAndHal = 0x26000010,
/// <summary>
/// The filename of the kernel.
/// </summary>
OsLoaderKernelPath = 0x22000011,
/// <summary>
/// The filename of the HAL.
/// </summary>
OsLoaderHalPath = 0x22000012,
/// <summary>
/// The debug transport path.
/// </summary>
OsLoaderDebugTransportPath = 0x22000013,
/// <summary>
/// NX (No-Execute) policy.
/// </summary>
/// <remarks>0 = OptIn, 1 = OptOut, 2 = AlwaysOff, 3 = AlwaysOn</remarks>
OsLoaderNxPolicy = 0x25000020,
/// <summary>
/// PAE policy.
/// </summary>
/// <remarks>0 = default, 1 = ForceEnable, 2 = ForceDisable</remarks>
OsLoaderPaePolicy = 0x25000021,
/// <summary>
/// WinPE mode.
/// </summary>
OsLoaderWinPeMode = 0x26000022,
/// <summary>
/// Disable automatic reboot on OS crash.
/// </summary>
OsLoaderDisableCrashAutoReboot = 0x26000024,
/// <summary>
/// Use the last known good settings.
/// </summary>
OsLoaderUseLastGoodSettings = 0x26000025,
/// <summary>
/// Disable integrity checks.
/// </summary>
OsLoaderDisableIntegrityChecks = 0x26000026,
/// <summary>
/// Allows pre-release signatures (test signing).
/// </summary>
OsLoaderAllowPrereleaseSignatures = 0x26000027,
/// <summary>
/// Loads all executables above 4GB boundary.
/// </summary>
OsLoaderNoLowMemory = 0x26000030,
/// <summary>
/// Excludes a given amount of memory from use by Windows.
/// </summary>
OsLoaderRemoveMemory = 0x25000031,
/// <summary>
/// Increases the User Mode virtual address space.
/// </summary>
OsLoaderIncreaseUserVa = 0x25000032,
/// <summary>
/// Size of buffer (in MB) for perfomance data logging.
/// </summary>
OsLoaderPerformanceDataMemory = 0x25000033,
/// <summary>
/// Uses the VGA display driver.
/// </summary>
OsLoaderUseVgaDriver = 0x26000040,
/// <summary>
/// Quiet boot.
/// </summary>
OsLoaderDisableBootDisplay = 0x26000041,
/// <summary>
/// Disables use of the VESA BIOS.
/// </summary>
OsLoaderDisableVesaBios = 0x26000042,
/// <summary>
/// Maximum processors in a single APIC cluster.
/// </summary>
OsLoaderClusterModeAddressing = 0x25000050,
/// <summary>
/// Forces the physical APIC to be used.
/// </summary>
OsLoaderUsePhysicalDestination = 0x26000051,
/// <summary>
/// The largest APIC cluster number the system can use.
/// </summary>
OsLoaderRestrictApicCluster = 0x25000052,
/// <summary>
/// Forces only the boot processor to be used.
/// </summary>
OsLoaderUseBootProcessorOnly = 0x26000060,
/// <summary>
/// The number of processors to be used.
/// </summary>
OsLoaderNumberOfProcessors = 0x25000061,
/// <summary>
/// Use maximum number of processors.
/// </summary>
OsLoaderForceMaxProcessors = 0x26000062,
/// <summary>
/// Processor specific configuration flags.
/// </summary>
OsLoaderProcessorConfigurationFlags = 0x25000063,
/// <summary>
/// Uses BIOS-configured PCI resources.
/// </summary>
OsLoaderUseFirmwarePciSettings = 0x26000070,
/// <summary>
/// Message Signalled Interrupt setting.
/// </summary>
OsLoaderMsiPolicy = 0x25000071,
/// <summary>
/// PCE Express Policy.
/// </summary>
OsLoaderPciExpressPolicy = 0x25000072,
/// <summary>
/// The safe boot option.
/// </summary>
/// <remarks>0 = Minimal, 1 = Network, 2 = DsRepair</remarks>
OsLoaderSafeBoot = 0x25000080,
/// <summary>
/// Loads the configured alternate shell during a safe boot.
/// </summary>
OsLoaderSafeBootAlternateShell = 0x26000081,
/// <summary>
/// Enables boot log.
/// </summary>
OsLoaderBootLogInitialization = 0x26000090,
/// <summary>
/// Displays diagnostic information during boot.
/// </summary>
OsLoaderVerboseObjectLoadMode = 0x26000091,
/// <summary>
/// Enables the kernel debugger.
/// </summary>
OsLoaderKernelDebuggerEnabled = 0x260000A0,
/// <summary>
/// Causes the kernal to halt early during boot.
/// </summary>
OsLoaderDebuggerHalBreakpoint = 0x260000A1,
/// <summary>
/// Enables Windows Emergency Management System.
/// </summary>
OsLoaderEmsEnabled = 0x260000B0,
/// <summary>
/// Forces a failure on boot.
/// </summary>
OsLoaderForceFailure = 0x250000C0,
/// <summary>
/// The OS failure policy.
/// </summary>
OsLoaderDriverLoadFailurePolicy = 0x250000C1,
/// <summary>
/// The OS boot status policy.
/// </summary>
OsLoaderBootStatusPolicy = 0x250000E0,
/// <summary>
/// The device containing the hibernation file.
/// </summary>
ResumeHiberFileDevice = 0x21000001,
/// <summary>
/// The path to the hibernation file.
/// </summary>
ResumeHiberFilePath = 0x22000002,
/// <summary>
/// Allows resume loader to use custom settings.
/// </summary>
ResumeUseCustomSettings = 0x26000003,
/// <summary>
/// PAE settings for resume application.
/// </summary>
ResumePaeMode = 0x26000004,
/// <summary>
/// An MS-DOS device with containing resume application
/// </summary>
ResumeAssociatedDosDevice = 0x21000005,
/// <summary>
/// Enables debug option.
/// </summary>
ResumeDebugOptionEnabled = 0x26000006,
/// <summary>
/// The number of iterations to run.
/// </summary>
MemDiagPassCount = 0x25000001,
/// <summary>
/// The test mix.
/// </summary>
MemDiagTestMix = 0x25000002,
/// <summary>
/// The failure count.
/// </summary>
MemDiagFailureCount = 0x25000003,
/// <summary>
/// The tests to fail.
/// </summary>
MemDiagTestToFail = 0x25000004,
/// <summary>
/// BPB string.
/// </summary>
LoaderBpbString = 0x22000001,
/// <summary>
/// Causes a soft PXE reboot.
/// </summary>
StartupPxeSoftReboot = 0x26000001,
/// <summary>
/// PXE application name.
/// </summary>
StartupPxeApplicationName = 0x22000002,
/// <summary>
/// Offset of the RAM disk image.
/// </summary>
DeviceRamDiskImageOffset = 0x35000001,
/// <summary>
/// Client port for TFTP.
/// </summary>
DeviceRamDiskTftpClientPort = 0x35000002,
/// <summary>
/// Device containing the SDI file.
/// </summary>
DeviceRamDiskSdiDevice = 0x31000003,
/// <summary>
/// Path to the SDI file.
/// </summary>
DeviceRamDiskSdiPath = 0x32000004,
/// <summary>
/// Length of the RAM disk image.
/// </summary>
DeviceRamDiskRamDiskImageLength = 0x35000005,
/// <summary>
/// Exports the image as a CD.
/// </summary>
DeviceRamDiskExportAsCd = 0x36000006,
/// <summary>
/// The TFTP transfer block size.
/// </summary>
DeviceRamDiskTftpBlockSize = 0x35000007,
/// <summary>
/// The device type.
/// </summary>
SetupDeviceType = 0x45000001,
/// <summary>
/// The application relative path.
/// </summary>
SetupAppRelativePath = 0x42000002,
/// <summary>
/// The device relative path.
/// </summary>
SetupRamDiskDeviceRelativePath = 0x42000003,
/// <summary>
/// Omit OS loader elements.
/// </summary>
SetupOmitOsLoaderElements = 0x46000004,
/// <summary>
/// Recovery OS flag.
/// </summary>
SetupRecoveryOs = 0x46000010,
}
}
| |
using J2N.Text;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using WritableArrayAttribute = Lucene.Net.Support.WritableArrayAttribute;
namespace Lucene.Net.Analysis.TokenAttributes
{
/*
* 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 ArrayUtil = Lucene.Net.Util.ArrayUtil;
using Attribute = Lucene.Net.Util.Attribute;
using BytesRef = Lucene.Net.Util.BytesRef;
using IAttribute = Lucene.Net.Util.IAttribute;
using IAttributeReflector = Lucene.Net.Util.IAttributeReflector;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
using UnicodeUtil = Lucene.Net.Util.UnicodeUtil;
/// <summary>
/// Default implementation of <see cref="ICharTermAttribute"/>. </summary>
public class CharTermAttribute : Attribute, ICharTermAttribute, ITermToBytesRefAttribute, IAppendable
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
private static int MIN_BUFFER_SIZE = 10;
private char[] termBuffer = CreateBuffer(MIN_BUFFER_SIZE);
private int termLength = 0;
/// <summary>
/// Initialize this attribute with empty term text </summary>
public CharTermAttribute()
{
}
// LUCENENET specific - ICharSequence member from J2N
bool ICharSequence.HasValue => termBuffer != null;
public void CopyBuffer(char[] buffer, int offset, int length)
{
GrowTermBuffer(length);
Array.Copy(buffer, offset, termBuffer, 0, length);
termLength = length;
}
char[] ICharTermAttribute.Buffer => termBuffer;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public char[] Buffer => termBuffer;
public char[] ResizeBuffer(int newSize)
{
if (termBuffer.Length < newSize)
{
// Not big enough; create a new array with slight
// over allocation and preserve content
// LUCENENET: Resize rather than copy
Array.Resize(ref termBuffer, ArrayUtil.Oversize(newSize, RamUsageEstimator.NUM_BYTES_CHAR));
}
return termBuffer;
}
private void GrowTermBuffer(int newSize)
{
if (termBuffer.Length < newSize)
{
// Not big enough; create a new array with slight
// over allocation:
termBuffer = new char[ArrayUtil.Oversize(newSize, RamUsageEstimator.NUM_BYTES_CHAR)];
}
}
int ICharTermAttribute.Length { get => Length; set => SetLength(value); }
int ICharSequence.Length => Length;
public int Length
{
get => termLength;
set => SetLength(value);
}
public CharTermAttribute SetLength(int length)
{
if (length > termBuffer.Length)
{
throw new ArgumentException("length " + length + " exceeds the size of the termBuffer (" + termBuffer.Length + ")");
}
termLength = length;
return this;
}
public CharTermAttribute SetEmpty()
{
termLength = 0;
return this;
}
// *** TermToBytesRefAttribute interface ***
private BytesRef bytes = new BytesRef(MIN_BUFFER_SIZE);
public virtual void FillBytesRef()
{
UnicodeUtil.UTF16toUTF8(termBuffer, 0, termLength, bytes);
}
public virtual BytesRef BytesRef => bytes;
// *** CharSequence interface ***
// LUCENENET specific: Replaced with this[int] to .NETify
//public char CharAt(int index)
//{
// if (index >= TermLength)
// {
// throw new IndexOutOfRangeException();
// }
// return TermBuffer[index];
//}
char ICharSequence.this[int index] => this[index];
char ICharTermAttribute.this[int index] { get => this[index]; set => this[index] = value; }
// LUCENENET specific indexer to make CharTermAttribute act more like a .NET type
public char this[int index]
{
get
{
if (index < 0 || index >= termLength) // LUCENENET: Added better bounds checking
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return termBuffer[index];
}
set
{
if (index < 0 || index >= termLength)
{
throw new ArgumentOutOfRangeException(nameof(index)); // LUCENENET: Added better bounds checking
}
termBuffer[index] = value;
}
}
public ICharSequence Subsequence(int startIndex, int length)
{
// From Apache Harmony String class
if (termBuffer == null || (startIndex == 0 && length == termBuffer.Length))
{
return new CharArrayCharSequence(termBuffer);
}
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex));
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length));
if (startIndex + length > Length)
throw new ArgumentOutOfRangeException("", $"{nameof(startIndex)} + {nameof(length)} > {nameof(Length)}");
char[] result = new char[length];
for (int i = 0, j = startIndex; i < length; i++, j++)
result[i] = termBuffer[j];
return new CharArrayCharSequence(result);
}
// *** Appendable interface ***
public CharTermAttribute Append(string value, int startIndex, int charCount)
{
// LUCENENET: Changed semantics to be the same as the StringBuilder in .NET
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex));
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount));
if (value == null)
{
if (startIndex == 0 && charCount == 0)
return this;
throw new ArgumentNullException(nameof(value));
}
if (charCount == 0)
return this;
if (startIndex > value.Length - charCount)
throw new ArgumentOutOfRangeException(nameof(startIndex));
value.CopyTo(startIndex, InternalResizeBuffer(termLength + charCount), termLength, charCount);
Length += charCount;
return this;
}
public CharTermAttribute Append(char value)
{
ResizeBuffer(termLength + 1)[termLength++] = value;
return this;
}
public CharTermAttribute Append(char[] value)
{
if (value == null)
//return AppendNull();
return this; // No-op
int len = value.Length;
value.CopyTo(InternalResizeBuffer(termLength + len), termLength);
Length += len;
return this;
}
public CharTermAttribute Append(char[] value, int startIndex, int charCount)
{
// LUCENENET: Changed semantics to be the same as the StringBuilder in .NET
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex));
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount));
if (value == null)
{
if (startIndex == 0 && charCount == 0)
return this;
throw new ArgumentNullException(nameof(value));
}
if (charCount == 0)
return this;
if (startIndex > value.Length - charCount)
throw new ArgumentOutOfRangeException(nameof(startIndex));
Array.Copy(value, startIndex, InternalResizeBuffer(termLength + charCount), termLength, charCount);
Length += charCount;
return this;
}
public CharTermAttribute Append(string value)
{
return Append(value, 0, value == null ? 0 : value.Length);
}
public CharTermAttribute Append(StringBuilder value)
{
if (value == null) // needed for Appendable compliance
{
//return AppendNull();
return this; // No-op
}
return Append(value.ToString());
}
public CharTermAttribute Append(StringBuilder value, int startIndex, int charCount)
{
// LUCENENET: Changed semantics to be the same as the StringBuilder in .NET
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex));
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount));
if (value == null)
{
if (startIndex == 0 && charCount == 0)
return this;
throw new ArgumentNullException(nameof(value));
}
if (charCount == 0)
return this;
if (startIndex > value.Length - charCount)
throw new ArgumentOutOfRangeException(nameof(startIndex));
return Append(value.ToString(startIndex, charCount));
}
public CharTermAttribute Append(ICharTermAttribute value)
{
if (value == null) // needed for Appendable compliance
{
//return AppendNull();
return this; // No-op
}
int len = value.Length;
Array.Copy(value.Buffer, 0, ResizeBuffer(termLength + len), termLength, len);
termLength += len;
return this;
}
public CharTermAttribute Append(ICharSequence value)
{
if (value == null)
//return AppendNull();
return this; // No-op
return Append(value, 0, value.Length);
}
public CharTermAttribute Append(ICharSequence value, int startIndex, int charCount)
{
// LUCENENET: Changed semantics to be the same as the StringBuilder in .NET
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex));
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount));
if (value == null)
{
if (startIndex == 0 && charCount == 0)
return this;
throw new ArgumentNullException(nameof(value));
}
if (charCount == 0)
return this;
if (startIndex > value.Length - charCount)
throw new ArgumentOutOfRangeException(nameof(startIndex));
ResizeBuffer(termLength + charCount);
for (int i = 0; i < charCount; i++)
termBuffer[termLength++] = value[startIndex + i];
return this;
}
private char[] InternalResizeBuffer(int length)
{
if (termBuffer.Length < length)
{
char[] newBuffer = CreateBuffer(length);
Array.Copy(termBuffer, 0, newBuffer, 0, termBuffer.Length);
this.termBuffer = newBuffer;
}
return termBuffer;
}
private static char[] CreateBuffer(int length)
{
return new char[ArrayUtil.Oversize(length, RamUsageEstimator.NUM_BYTES_CHAR)];
}
// LUCENENET: Not used - we are doing a no-op when the value is null
//private CharTermAttribute AppendNull()
//{
// ResizeBuffer(termLength + 4);
// termBuffer[termLength++] = 'n';
// termBuffer[termLength++] = 'u';
// termBuffer[termLength++] = 'l';
// termBuffer[termLength++] = 'l';
// return this;
//}
// *** Attribute ***
public override int GetHashCode()
{
int code = termLength;
code = code * 31 + ArrayUtil.GetHashCode(termBuffer, 0, termLength);
return code;
}
public override void Clear()
{
termLength = 0;
}
public override object Clone()
{
CharTermAttribute t = (CharTermAttribute)base.Clone();
// Do a deep clone
t.termBuffer = new char[this.termLength];
Array.Copy(this.termBuffer, 0, t.termBuffer, 0, this.termLength);
t.bytes = BytesRef.DeepCopyOf(bytes);
return t;
}
public override bool Equals(object other)
{
if (other == this)
{
return true;
}
if (other is CharTermAttribute o)
{
if (termLength != o.termLength)
{
return false;
}
for (int i = 0; i < termLength; i++)
{
if (termBuffer[i] != o.termBuffer[i])
{
return false;
}
}
return true;
}
return false;
}
/// <summary>
/// Returns solely the term text as specified by the
/// <see cref="ICharSequence"/> interface.
/// <para/>
/// this method changed the behavior with Lucene 3.1,
/// before it returned a String representation of the whole
/// term with all attributes.
/// this affects especially the
/// <see cref="Lucene.Net.Analysis.Token"/> subclass.
/// </summary>
public override string ToString()
{
return new string(termBuffer, 0, termLength);
}
public override void ReflectWith(IAttributeReflector reflector)
{
reflector.Reflect(typeof(ICharTermAttribute), "term", ToString());
FillBytesRef();
reflector.Reflect(typeof(ITermToBytesRefAttribute), "bytes", BytesRef.DeepCopyOf(bytes));
}
public override void CopyTo(IAttribute target)
{
CharTermAttribute t = (CharTermAttribute)target;
t.CopyBuffer(termBuffer, 0, termLength);
}
#region ICharTermAttribute Members
void ICharTermAttribute.CopyBuffer(char[] buffer, int offset, int length) => CopyBuffer(buffer, offset, length);
char[] ICharTermAttribute.ResizeBuffer(int newSize) => ResizeBuffer(newSize);
ICharTermAttribute ICharTermAttribute.SetLength(int length) => SetLength(length);
ICharTermAttribute ICharTermAttribute.SetEmpty() => SetEmpty();
ICharTermAttribute ICharTermAttribute.Append(ICharSequence value) => Append(value);
ICharTermAttribute ICharTermAttribute.Append(ICharSequence value, int startIndex, int count) => Append(value, startIndex, count);
ICharTermAttribute ICharTermAttribute.Append(char value) => Append(value);
ICharTermAttribute ICharTermAttribute.Append(char[] value) => Append(value);
ICharTermAttribute ICharTermAttribute.Append(char[] value, int startIndex, int count) => Append(value, startIndex, count);
ICharTermAttribute ICharTermAttribute.Append(string value) => Append(value);
ICharTermAttribute ICharTermAttribute.Append(string value, int startIndex, int count) => Append(value, startIndex, count);
ICharTermAttribute ICharTermAttribute.Append(StringBuilder value) => Append(value);
ICharTermAttribute ICharTermAttribute.Append(StringBuilder value, int startIndex, int count) => Append(value, startIndex, count);
ICharTermAttribute ICharTermAttribute.Append(ICharTermAttribute value) => Append(value);
#endregion
#region IAppendable Members
IAppendable IAppendable.Append(char value) => Append(value);
IAppendable IAppendable.Append(string value) => Append(value);
IAppendable IAppendable.Append(string value, int startIndex, int count) => Append(value, startIndex, count);
IAppendable IAppendable.Append(StringBuilder value) => Append(value);
IAppendable IAppendable.Append(StringBuilder value, int startIndex, int count) => Append(value, startIndex, count);
IAppendable IAppendable.Append(char[] value) => Append(value);
IAppendable IAppendable.Append(char[] value, int startIndex, int count) => Append(value, startIndex, count);
IAppendable IAppendable.Append(ICharSequence value) => Append(value);
IAppendable IAppendable.Append(ICharSequence value, int startIndex, int count) => Append(value, startIndex, count);
#endregion
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
[Serializable]
public sealed class TessellationOpHelper
{
public const string TessellationPortStr = "Tessellation";
public const string TessSurfParam = "tessellate:tessFunction";
public const string TessInclude = "Tessellation.cginc";
public const string CustomAppData = "\t\tstruct appdata\n" +
"\t\t{\n" +
"\t\t\tfloat4 vertex : POSITION;\n" +
"\t\t\tfloat4 tangent : TANGENT;\n" +
"\t\t\tfloat3 normal : NORMAL;\n" +
"\t\t\tfloat4 texcoord : TEXCOORD0;\n" +
"\t\t\tfloat4 texcoord1 : TEXCOORD1;\n" +
"\t\t\tfloat4 texcoord2 : TEXCOORD2;\n" +
"\t\t\tfloat4 texcoord3 : TEXCOORD3;\n" +
"\t\t\tfixed4 color : COLOR;\n" +
#if UNITY_5_5_OR_NEWER
"\t\t\tUNITY_VERTEX_INPUT_INSTANCE_ID\n" +
#else
"\t\t\tUNITY_INSTANCE_ID\n" +
#endif
"\t\t};\n\n";
private const string TessUniformName = "_TessValue";
private const string TessMinUniformName = "_TessMin";
private const string TessMaxUniformName = "_TessMax";
//private GUIContent EnableTessContent = new GUIContent( "Tessellation", "Activates the use of tessellation which subdivides polygons to increase geometry detail using a set of rules\nDefault: OFF" );
private GUIContent TessFactorContent = new GUIContent( "Tess", "Tessellation factor\nDefault: 4" );
private GUIContent TessMinDistanceContent = new GUIContent( "Min", "Minimum tessellation distance\nDefault: 10" );
private GUIContent TessMaxDistanceContent = new GUIContent( "Max", "Maximum tessellation distance\nDefault: 25" );
private readonly int[] TesselationTypeValues = { 0, 1, 2, 3 };
private readonly string[] TesselationTypeLabels = { "Distance-based", "Fixed", "Edge Length", "Edge Length Cull" };
private readonly string TesselationTypeStr = "Type";
private const string TessProperty = "_TessValue( \"Max Tessellation\", Range( 1, 32 ) ) = {0}";
private const string TessMinProperty = "_TessMin( \"Tess Min Distance\", Float ) = {0}";
private const string TessMaxProperty = "_TessMax( \"Tess Max Distance\", Float ) = {0}";
private const string TessFunctionOpen = "\t\tfloat4 tessFunction( appdata v0, appdata v1, appdata v2 )\n\t\t{\n";
private const string TessFunctionClose = "\t\t}\n";
// Custom function
private const string CustomFunctionBody = "\t\t\treturn {0};\n";
// Distance based function
private const string DistBasedTessFunctionBody = "\t\t\treturn UnityDistanceBasedTess( v0.vertex, v1.vertex, v2.vertex, _TessMin, _TessMax, _TessValue );\n";
// Fixed amount function
private const string FixedAmountTessFunctionOpen = "\t\tfloat4 tessFunction( )\n\t\t{\n";
private const string FixedAmountTessFunctionBody = "\t\t\treturn _TessValue;\n";
// Edge Length
private GUIContent EdgeLengthContent = new GUIContent( "Edge Length", "Tessellation levels ccomputed based on triangle edge length on the screen\nDefault: 4" );
private const string EdgeLengthTessProperty = "_EdgeLength ( \"Edge length\", Range( 2, 50 ) ) = {0}";
private const string EdgeLengthTessUniformName = "_EdgeLength";
private const string EdgeLengthTessFunctionBody = "\t\t\treturn UnityEdgeLengthBasedTess (v0.vertex, v1.vertex, v2.vertex, _EdgeLength);\n";
private const string EdgeLengthTessCullFunctionBody = "\t\t\treturn UnityEdgeLengthBasedTessCull (v0.vertex, v1.vertex, v2.vertex, _EdgeLength , _TessMaxDisp );\n";
private const string EdgeLengthTessMaxDispProperty = "_TessMaxDisp( \"Max Displacement\", Float ) = {0}";
private const string EdgeLengthTessMaxDispUniformName = "_TessMaxDisp";
private GUIContent EdgeLengthTessMaxDisplacementContent = new GUIContent( "Max Disp.", "Max Displacement" );
// Phong
private GUIContent PhongEnableContent = new GUIContent( "Phong", "Modifies positions of the subdivided faces so that the resulting surface follows the mesh normals a bit\nDefault: OFF" );
private GUIContent PhongStrengthContent = new GUIContent( "Strength", "Strength\nDefault: 0.5" );
public const string PhongStrengthParam = "tessphong:_TessPhongStrength";
private const string PhongStrengthProperty = "_TessPhongStrength( \"Phong Tess Strength\", Range( 0, 1 ) ) = {0}";
private const string PhongStrengthUniformName = "_TessPhongStrength";
[SerializeField]
private bool m_enabled = false;
//private bool m_expanded = false;
[SerializeField]
private int m_tessType = 0;
[SerializeField]
private float m_tessMinDistance = 10f;
[SerializeField]
private float m_tessMaxDistance = 25f;
[SerializeField]
private float m_tessFactor = 4f;
[SerializeField]
private float m_phongStrength = 0.5f;
[SerializeField]
private bool m_phongEnabled = false;
[SerializeField]
private string[] m_customData = { string.Empty, string.Empty, string.Empty };
[SerializeField]
private bool m_hasCustomFunction = false;
[SerializeField]
private string m_customFunction = String.Empty;
[SerializeField]
private string m_additionalData = string.Empty;
[SerializeField]
private StandardSurfaceOutputNode m_parentSurface;
private Dictionary<string, bool> m_additionalDataDict = new Dictionary<string, bool>();
private int m_masterNodeIndexPort = 0;
private int m_vertexOffsetIndexPort = 0;
//private int m_orderIndex = 1000;
public void Draw( UndoParentNode owner, GUIStyle toolbarstyle, Material mat, bool connectedInput )
{
Color cachedColor = GUI.color;
GUI.color = new Color( cachedColor.r, cachedColor.g, cachedColor.b, 0.5f );
EditorGUILayout.BeginHorizontal( toolbarstyle );
GUI.color = cachedColor;
EditorGUI.BeginChangeCheck();
m_parentSurface.ContainerGraph.ParentWindow.ExpandedTesselation = GUILayout.Toggle( m_parentSurface.ContainerGraph.ParentWindow.ExpandedTesselation, " Tessellation", UIUtils.MenuItemToggleStyle, GUILayout.ExpandWidth( true ) );
if ( EditorGUI.EndChangeCheck() )
{
EditorPrefs.SetBool( "ExpandedTesselation", m_parentSurface.ContainerGraph.ParentWindow.ExpandedTesselation );
}
EditorGUI.BeginChangeCheck();
m_enabled = owner.EditorGUILayoutToggle( string.Empty, m_enabled, UIUtils.MenuItemEnableStyle, GUILayout.Width( 16 ) );
if ( EditorGUI.EndChangeCheck() )
{
if ( m_enabled )
UpdateToMaterial( mat, !connectedInput );
UIUtils.RequestSave();
}
EditorGUILayout.EndHorizontal();
m_enabled = m_enabled || connectedInput;
if ( m_parentSurface.ContainerGraph.ParentWindow.ExpandedTesselation )
{
cachedColor = GUI.color;
GUI.color = new Color( cachedColor.r, cachedColor.g, cachedColor.b, ( EditorGUIUtility.isProSkin ? 0.5f : 0.25f ) );
EditorGUILayout.BeginVertical( UIUtils.MenuItemBackgroundStyle );
GUI.color = cachedColor;
EditorGUILayout.Separator();
EditorGUI.BeginDisabledGroup( !m_enabled );
EditorGUI.indentLevel += 1;
m_phongEnabled = owner.EditorGUILayoutToggle( PhongEnableContent, m_phongEnabled );
if ( m_phongEnabled )
{
EditorGUI.indentLevel += 1;
EditorGUI.BeginChangeCheck();
m_phongStrength = owner.EditorGUILayoutSlider( PhongStrengthContent, m_phongStrength, 0.0f, 1.0f );
if ( EditorGUI.EndChangeCheck() && mat != null )
{
if ( mat.HasProperty( PhongStrengthUniformName ) )
mat.SetFloat( PhongStrengthUniformName, m_phongStrength );
}
EditorGUI.indentLevel -= 1;
}
bool guiEnabled = GUI.enabled;
GUI.enabled = !connectedInput && m_enabled;
m_tessType = owner.EditorGUILayoutIntPopup( TesselationTypeStr, m_tessType, TesselationTypeLabels, TesselationTypeValues );
switch ( m_tessType )
{
case 0:
{
EditorGUI.BeginChangeCheck();
m_tessFactor = owner.EditorGUILayoutSlider( TessFactorContent, m_tessFactor, 1, 32 );
if ( EditorGUI.EndChangeCheck() && mat != null )
{
if ( mat.HasProperty( TessUniformName ) )
mat.SetFloat( TessUniformName, m_tessFactor );
}
EditorGUI.BeginChangeCheck();
m_tessMinDistance = owner.EditorGUILayoutFloatField( TessMinDistanceContent, m_tessMinDistance );
if ( EditorGUI.EndChangeCheck() && mat != null )
{
if ( mat.HasProperty( TessMinUniformName ) )
mat.SetFloat( TessMinUniformName, m_tessMinDistance );
}
EditorGUI.BeginChangeCheck();
m_tessMaxDistance = owner.EditorGUILayoutFloatField( TessMaxDistanceContent, m_tessMaxDistance );
if ( EditorGUI.EndChangeCheck() && mat != null )
{
if ( mat.HasProperty( TessMaxUniformName ) )
mat.SetFloat( TessMaxUniformName, m_tessMaxDistance );
}
}
break;
case 1:
{
EditorGUI.BeginChangeCheck();
m_tessFactor = owner.EditorGUILayoutSlider( TessFactorContent, m_tessFactor, 1, 32 );
if ( EditorGUI.EndChangeCheck() && mat != null )
{
if ( mat.HasProperty( TessUniformName ) )
mat.SetFloat( TessUniformName, m_tessFactor );
}
}
break;
case 2:
{
EditorGUI.BeginChangeCheck();
m_tessFactor = owner.EditorGUILayoutSlider( EdgeLengthContent, m_tessFactor, 2, 50 );
if ( EditorGUI.EndChangeCheck() && mat != null )
{
if ( mat.HasProperty( EdgeLengthTessUniformName ) )
mat.SetFloat( EdgeLengthTessUniformName, m_tessFactor );
}
}
break;
case 3:
{
EditorGUI.BeginChangeCheck();
m_tessFactor = owner.EditorGUILayoutSlider( EdgeLengthContent, m_tessFactor, 2, 50 );
if ( EditorGUI.EndChangeCheck() && mat != null )
{
if ( mat.HasProperty( EdgeLengthTessUniformName ) )
mat.SetFloat( EdgeLengthTessUniformName, m_tessFactor );
}
EditorGUI.BeginChangeCheck();
m_tessMaxDistance = owner.EditorGUILayoutFloatField( EdgeLengthTessMaxDisplacementContent, m_tessMaxDistance );
if ( EditorGUI.EndChangeCheck() && mat != null )
{
if ( mat.HasProperty( TessMinUniformName ) )
mat.SetFloat( TessMinUniformName, m_tessMaxDistance );
}
}
break;
}
GUI.enabled = guiEnabled;
EditorGUI.indentLevel -= 1;
EditorGUI.EndDisabledGroup();
EditorGUILayout.Separator();
EditorGUILayout.EndVertical();
}
}
public void UpdateToMaterial( Material mat, bool updateInternals )
{
if ( mat == null )
return;
if ( m_phongEnabled )
{
if ( mat.HasProperty( PhongStrengthUniformName ) )
mat.SetFloat( PhongStrengthUniformName, m_phongStrength );
}
if ( updateInternals )
{
switch ( m_tessType )
{
case 0:
{
if ( mat.HasProperty( TessUniformName ) )
mat.SetFloat( TessUniformName, m_tessFactor );
if ( mat.HasProperty( TessMinUniformName ) )
mat.SetFloat( TessMinUniformName, m_tessMinDistance );
if ( mat.HasProperty( TessMaxUniformName ) )
mat.SetFloat( TessMaxUniformName, m_tessMaxDistance );
}
break;
case 1:
{
if ( mat.HasProperty( TessUniformName ) )
mat.SetFloat( TessUniformName, m_tessFactor );
}
break;
case 2:
{
if ( mat.HasProperty( EdgeLengthTessUniformName ) )
mat.SetFloat( EdgeLengthTessUniformName, m_tessFactor );
}
break;
case 3:
{
if ( mat.HasProperty( EdgeLengthTessUniformName ) )
mat.SetFloat( EdgeLengthTessUniformName, m_tessFactor );
if ( mat.HasProperty( TessMinUniformName ) )
mat.SetFloat( TessMinUniformName, m_tessMaxDistance );
}
break;
}
}
}
public void ReadFromString( ref uint index, ref string[] nodeParams )
{
m_enabled = Convert.ToBoolean( nodeParams[ index++ ] );
m_tessType = Convert.ToInt32( nodeParams[ index++ ] );
m_tessFactor = Convert.ToSingle( nodeParams[ index++ ] );
m_tessMinDistance = Convert.ToSingle( nodeParams[ index++ ] );
m_tessMaxDistance = Convert.ToSingle( nodeParams[ index++ ] );
if ( UIUtils.CurrentShaderVersion() > 3001 )
{
m_phongEnabled = Convert.ToBoolean( nodeParams[ index++ ] );
m_phongStrength = Convert.ToSingle( nodeParams[ index++ ] );
}
}
public void WriteToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_enabled );
IOUtils.AddFieldValueToString( ref nodeInfo, m_tessType );
IOUtils.AddFieldValueToString( ref nodeInfo, m_tessFactor );
IOUtils.AddFieldValueToString( ref nodeInfo, m_tessMinDistance );
IOUtils.AddFieldValueToString( ref nodeInfo, m_tessMaxDistance );
IOUtils.AddFieldValueToString( ref nodeInfo, m_phongEnabled );
IOUtils.AddFieldValueToString( ref nodeInfo, m_phongStrength );
}
public void AddToDataCollector( ref MasterNodeDataCollector dataCollector, int reorder )
{
int orderIndex = reorder;
switch ( m_tessType )
{
case 0:
{
dataCollector.AddToIncludes( -1, TessellationOpHelper.TessInclude );
if ( !m_hasCustomFunction )
{
//Tess
dataCollector.AddToProperties( -1, string.Format( TessProperty, m_tessFactor ), orderIndex++ );
dataCollector.AddToUniforms( -1, "uniform " + UIUtils.FinalPrecisionWirePortToCgType( PrecisionType.Float, WirePortDataType.FLOAT ) + " " + TessUniformName + ";" );
//Min
dataCollector.AddToProperties( -1, string.Format( TessMinProperty, m_tessMinDistance ), orderIndex++ );
dataCollector.AddToUniforms( -1, "uniform " + UIUtils.FinalPrecisionWirePortToCgType( PrecisionType.Float, WirePortDataType.FLOAT ) + " " + TessMinUniformName + ";" );
//Max
dataCollector.AddToProperties( -1, string.Format( TessMaxProperty, m_tessMaxDistance ), orderIndex++ );
dataCollector.AddToUniforms( -1, "uniform " + UIUtils.FinalPrecisionWirePortToCgType( PrecisionType.Float, WirePortDataType.FLOAT ) + " " + TessMaxUniformName + ";" );
}
}
break;
case 1:
{
//Tess
if ( !m_hasCustomFunction )
{
dataCollector.AddToProperties( -1, string.Format( TessProperty, m_tessFactor ), orderIndex++ );
dataCollector.AddToUniforms( -1, "uniform " + UIUtils.FinalPrecisionWirePortToCgType( PrecisionType.Float, WirePortDataType.FLOAT ) + " " + TessUniformName + ";" );
}
}
break;
case 2:
{
dataCollector.AddToIncludes( -1, TessellationOpHelper.TessInclude );
//Tess
if ( !m_hasCustomFunction )
{
dataCollector.AddToProperties( -1, string.Format( EdgeLengthTessProperty, m_tessFactor ), orderIndex++ );
dataCollector.AddToUniforms( -1, "uniform " + UIUtils.FinalPrecisionWirePortToCgType( PrecisionType.Float, WirePortDataType.FLOAT ) + " " + EdgeLengthTessUniformName + ";" );
}
}
break;
case 3:
{
dataCollector.AddToIncludes( -1, TessellationOpHelper.TessInclude );
if ( !m_hasCustomFunction )
{
//Tess
dataCollector.AddToProperties( -1, string.Format( EdgeLengthTessProperty, m_tessFactor ), orderIndex++ );
dataCollector.AddToUniforms( -1, "uniform " + UIUtils.FinalPrecisionWirePortToCgType( PrecisionType.Float, WirePortDataType.FLOAT ) + " " + EdgeLengthTessUniformName + ";" );
//Max Displacement
dataCollector.AddToProperties( -1, string.Format( EdgeLengthTessMaxDispProperty, m_tessMaxDistance ), orderIndex++ );
dataCollector.AddToUniforms( -1, "uniform " + UIUtils.FinalPrecisionWirePortToCgType( PrecisionType.Float, WirePortDataType.FLOAT ) + " " + EdgeLengthTessMaxDispUniformName + ";" );
}
}
break;
}
if ( m_phongEnabled )
{
dataCollector.AddToProperties( -1, string.Format( PhongStrengthProperty, m_phongStrength ), orderIndex++ );
dataCollector.AddToUniforms( -1, "uniform " + UIUtils.FinalPrecisionWirePortToCgType( PrecisionType.Float, WirePortDataType.FLOAT ) + " " + PhongStrengthUniformName + ";" );
}
}
//ToDo: Optimize material property fetches to use Id instead of string
public void UpdateFromMaterial( Material mat )
{
if ( m_enabled )
{
if ( m_phongEnabled )
{
if ( mat.HasProperty( PhongStrengthUniformName ) )
m_phongStrength = mat.GetFloat( PhongStrengthUniformName );
}
switch ( m_tessType )
{
case 0:
{
if ( mat.HasProperty( TessUniformName ) )
m_tessFactor = mat.GetFloat( TessUniformName );
if ( mat.HasProperty( TessMinUniformName ) )
m_tessMinDistance = mat.GetFloat( TessMinUniformName );
if ( mat.HasProperty( TessMaxUniformName ) )
m_tessMaxDistance = mat.GetFloat( TessMaxUniformName );
}
break;
case 1:
{
if ( mat.HasProperty( TessUniformName ) )
m_tessFactor = mat.GetFloat( TessUniformName );
}
break;
case 2:
{
if ( mat.HasProperty( EdgeLengthTessUniformName ) )
m_tessFactor = mat.GetFloat( EdgeLengthTessUniformName );
}
break;
case 3:
{
if ( mat.HasProperty( EdgeLengthTessUniformName ) )
m_tessFactor = mat.GetFloat( EdgeLengthTessUniformName );
if ( mat.HasProperty( EdgeLengthTessMaxDispUniformName ) )
m_tessMaxDistance = mat.GetFloat( EdgeLengthTessMaxDispUniformName );
}
break;
}
}
}
public void WriteToOptionalParams( ref string optionalParams )
{
optionalParams += TessellationOpHelper.TessSurfParam + Constants.OptionalParametersSep;
if ( m_phongEnabled )
{
optionalParams += TessellationOpHelper.PhongStrengthParam + Constants.OptionalParametersSep;
}
}
public void Reset()
{
m_hasCustomFunction = false;
m_customFunction = string.Empty;
m_additionalData = string.Empty;
m_additionalDataDict.Clear();
switch ( m_tessType )
{
case 0:
{
m_customData[ 0 ] = TessUniformName;
m_customData[ 1 ] = TessMinUniformName;
m_customData[ 2 ] = TessMaxUniformName;
}
break;
case 1:
{
m_customData[ 0 ] = TessUniformName;
m_customData[ 1 ] = string.Empty;
m_customData[ 2 ] = string.Empty;
}
break;
case 2:
{
m_customData[ 0 ] = EdgeLengthTessUniformName;
m_customData[ 1 ] = string.Empty;
m_customData[ 2 ] = string.Empty;
}
break;
case 3:
{
m_customData[ 0 ] = EdgeLengthTessUniformName;
m_customData[ 1 ] = EdgeLengthTessMaxDispUniformName;
m_customData[ 2 ] = string.Empty;
}
break;
}
}
public string GetCurrentTessellationFunction
{
get
{
if ( m_hasCustomFunction )
{
return TessFunctionOpen +
m_customFunction +
TessFunctionClose;
}
string tessFunction = string.Empty;
switch ( m_tessType )
{
case 0:
{
tessFunction = TessFunctionOpen +
DistBasedTessFunctionBody +
TessFunctionClose;
}
break;
case 1:
{
tessFunction = FixedAmountTessFunctionOpen +
FixedAmountTessFunctionBody +
TessFunctionClose;
}
break;
case 2:
{
tessFunction = TessFunctionOpen +
EdgeLengthTessFunctionBody +
TessFunctionClose;
}
break;
case 3:
{
tessFunction = TessFunctionOpen +
EdgeLengthTessCullFunctionBody +
TessFunctionClose;
}
break;
}
return tessFunction;
}
}
public void AddAdditionalData( string data )
{
if ( !m_additionalDataDict.ContainsKey( data ) )
{
m_additionalDataDict.Add( data, true );
m_additionalData += data;
}
}
public void AddCustomFunction( string returnData )
{
m_hasCustomFunction = true;
m_customFunction = m_additionalData + string.Format( CustomFunctionBody, returnData );
}
public void Destroy()
{
m_additionalDataDict.Clear();
m_additionalDataDict = null;
}
public bool IsTessellationPort( int index )
{
return index == m_masterNodeIndexPort;
}
public bool EnableTesselation { get { return m_enabled; } }
public int TessType { get { return m_tessType; } }
public int MasterNodeIndexPort
{
get { return m_masterNodeIndexPort; }
set { m_masterNodeIndexPort = value; }
}
public int VertexOffsetIndexPort
{
get { return m_vertexOffsetIndexPort; }
set { m_vertexOffsetIndexPort = value; }
}
public StandardSurfaceOutputNode ParentSurface { get { return m_parentSurface; } set { m_parentSurface = value; } }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Resources
{
using System;
using System.IO;
using System.Globalization;
using System.Collections;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Diagnostics;
public sealed class ResourceReader : IDisposable
{
private const int ResSetVersion = 2;
private const int ResourceTypeCodeString = 1;
private const int ResourceManagerMagicNumber = unchecked((int)0xBEEFCACE);
private const int ResourceManagerHeaderVersionNumber = 1;
private BinaryReader _store; // backing store we're reading from.
private long _nameSectionOffset; // Offset to name section of file.
private long _dataSectionOffset; // Offset to Data section of file.
private int[] _namePositions; // relative locations of names
private Type[] _typeTable; // Lazy array of Types for resource values.
private int[] _typeNamePositions; // To delay initialize type table
private int _numResources; // Num of resources files, in case arrays aren't allocated.
private int _version;
public ResourceReader(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable);
_store = new BinaryReader(stream, Encoding.UTF8);
ReadResources();
}
public void Dispose()
{
Dispose(true);
}
[System.Security.SecuritySafeCritical] // auto-generated
private unsafe void Dispose(bool disposing)
{
if (_store != null)
{
if (disposing)
{
// Close the stream in a thread-safe way. This fix means
// that we may call Close n times, but that's safe.
BinaryReader copyOfStore = _store;
_store = null;
if (copyOfStore != null)
copyOfStore.Dispose();
}
_store = null;
_namePositions = null;
}
}
private void SkipString()
{
int stringLength = Read7BitEncodedInt();
if (stringLength < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
_store.BaseStream.Seek(stringLength, SeekOrigin.Current);
}
private unsafe int GetNamePosition(int index)
{
Debug.Assert(index >= 0 && index < _numResources, "Bad index into name position array. index: " + index);
int r;
r = _namePositions[index];
if (r < 0 || r > _dataSectionOffset - _nameSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesNameInvalidOffset + ":" + r);
}
return r;
}
public IDictionaryEnumerator GetEnumerator()
{
if (_store == null)
throw new InvalidOperationException(SR.ResourceReaderIsClosed);
return new ResourceEnumerator(this);
}
private unsafe String AllocateStringForNameIndex(int index, out int dataOffset)
{
Debug.Assert(_store != null, "ResourceReader is closed!");
byte[] bytes;
int byteLen;
long nameVA = GetNamePosition(index);
lock (this)
{
_store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
// Can't use _store.ReadString, since it's using UTF-8!
byteLen = Read7BitEncodedInt();
if (byteLen < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
bytes = new byte[byteLen];
// We must read byteLen bytes, or we have a corrupted file.
// Use a blocking read in case the stream doesn't give us back
// everything immediately.
int count = byteLen;
while (count > 0)
{
int n = _store.Read(bytes, byteLen - count, count);
if (n == 0)
throw new EndOfStreamException(SR.BadImageFormat_ResourceNameCorrupted_NameIndex + index);
count -= n;
}
dataOffset = _store.ReadInt32();
if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesDataInvalidOffset + " offset :" + dataOffset);
}
}
return Encoding.Unicode.GetString(bytes, 0, byteLen);
}
private string GetValueForNameIndex(int index)
{
Debug.Assert(_store != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
lock (this)
{
_store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
SkipString();
int dataPos = _store.ReadInt32();
if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesDataInvalidOffset + dataPos);
}
try
{
return LoadString(dataPos);
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, eof);
}
catch (ArgumentOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, e);
}
}
}
//returns null if the resource is not a string
private string LoadString(int pos)
{
_store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
int typeIndex = Read7BitEncodedInt();
if (_version == 1)
{
Type typeinStream = FindType(typeIndex);
if (typeIndex == -1 || !typeinStream.Equals(typeof(String)))
return null;
}
else
{
if (ResourceTypeCodeString != typeIndex)
{
return null;
}
}
return _store.ReadString();
}
private void ReadResources()
{
Debug.Assert(_store != null, "ResourceReader is closed!");
try
{
// mega try-catch performs exceptionally bad on x64; factored out body into
// _ReadResources and wrap here.
_ReadResources();
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, eof);
}
catch (IndexOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, e);
}
}
private void _ReadResources()
{
// Read out the ResourceManager header
// Read out magic number
int magicNum = _store.ReadInt32();
if (magicNum != ResourceManagerMagicNumber)
throw new ArgumentException(SR.Resources_StreamNotValid);
// Assuming this is ResourceManager header V1 or greater, hopefully
// after the version number there is a number of bytes to skip
// to bypass the rest of the ResMgr header. For V2 or greater, we
// use this to skip to the end of the header
int resMgrHeaderVersion = _store.ReadInt32();
//number of bytes to skip over to get past ResMgr header
int numBytesToSkip = _store.ReadInt32();
if (numBytesToSkip < 0 || resMgrHeaderVersion < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
if (resMgrHeaderVersion > 1)
{
_store.BaseStream.Seek(numBytesToSkip, SeekOrigin.Current);
}
else
{
// We don't care about numBytesToSkip; read the rest of the header
//Due to legacy : this field is always a variant of System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
//So we Skip the type name for resourcereader unlike Desktop
SkipString();
// Skip over type name for a suitable ResourceSet
SkipString();
}
// Read RuntimeResourceSet header
// Do file version check
int version = _store.ReadInt32();
if (version != ResSetVersion && version != 1)
throw new ArgumentException(SR.Arg_ResourceFileUnsupportedVersion + "Expected:" + ResSetVersion + "but got:" + version);
_version = version;
// number of resources
_numResources = _store.ReadInt32();
if (_numResources < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
// Read type positions into type positions array.
// But delay initialize the type table.
int numTypes = _store.ReadInt32();
if (numTypes < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_typeTable = new Type[numTypes];
_typeNamePositions = new int[numTypes];
for (int i = 0; i < numTypes; i++)
{
_typeNamePositions[i] = (int)_store.BaseStream.Position;
// Skip over the Strings in the file. Don't create types.
SkipString();
}
// Prepare to read in the array of name hashes
// Note that the name hashes array is aligned to 8 bytes so
// we can use pointers into it on 64 bit machines. (4 bytes
// may be sufficient, but let's plan for the future)
// Skip over alignment stuff. All public .resources files
// should be aligned No need to verify the byte values.
long pos = _store.BaseStream.Position;
int alignBytes = ((int)pos) & 7;
if (alignBytes != 0)
{
for (int i = 0; i < 8 - alignBytes; i++)
{
_store.ReadByte();
}
}
//Skip over the array of name hashes
for (int i = 0; i < _numResources; i++)
{
_store.ReadInt32();
}
// Read in the array of relative positions for all the names.
_namePositions = new int[_numResources];
for (int i = 0; i < _numResources; i++)
{
int namePosition = _store.ReadInt32();
if (namePosition < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_namePositions[i] = namePosition;
}
// Read location of data section.
_dataSectionOffset = _store.ReadInt32();
if (_dataSectionOffset < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
// Store current location as start of name section
_nameSectionOffset = _store.BaseStream.Position;
// _nameSectionOffset should be <= _dataSectionOffset; if not, it's corrupt
if (_dataSectionOffset < _nameSectionOffset)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
}
private Type FindType(int typeIndex)
{
if (typeIndex < 0 || typeIndex >= _typeTable.Length)
{
throw new BadImageFormatException(SR.BadImageFormat_InvalidType);
}
if (_typeTable[typeIndex] == null)
{
long oldPos = _store.BaseStream.Position;
try
{
_store.BaseStream.Position = _typeNamePositions[typeIndex];
String typeName = _store.ReadString();
_typeTable[typeIndex] = Type.GetType(typeName, true);
}
finally
{
_store.BaseStream.Position = oldPos;
}
}
Debug.Assert(_typeTable[typeIndex] != null, "Should have found a type!");
return _typeTable[typeIndex];
}
//blatantly copied over from BinaryReader
private int Read7BitEncodedInt()
{
// Read out an Int32 7 bits at a time. The high bit
// of the byte when on means to continue reading more bytes.
int count = 0;
int shift = 0;
byte b;
do
{
// Check for a corrupted stream. Read a max of 5 bytes.
// In a future version, add a DataFormatException.
if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7
throw new FormatException(SR.Format_Bad7BitInt32);
// ReadByte handles end of stream cases for us.
b = _store.ReadByte();
count |= (b & 0x7F) << shift;
shift += 7;
} while ((b & 0x80) != 0);
return count;
}
internal sealed class ResourceEnumerator : IDictionaryEnumerator
{
private const int ENUM_DONE = Int32.MinValue;
private const int ENUM_NOT_STARTED = -1;
private ResourceReader _reader;
private bool _currentIsValid;
private int _currentName;
internal ResourceEnumerator(ResourceReader reader)
{
_currentName = ENUM_NOT_STARTED;
_reader = reader;
}
public bool MoveNext()
{
if (_currentName == _reader._numResources - 1 || _currentName == ENUM_DONE)
{
_currentIsValid = false;
_currentName = ENUM_DONE;
return false;
}
_currentIsValid = true;
_currentName++;
return true;
}
public Object Key
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
int _dataPosition;
return _reader.AllocateStringForNameIndex(_currentName, out _dataPosition);
}
}
public Object Current
{
get
{
return Entry;
}
}
public DictionaryEntry Entry
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
String key;
Object value = null;
int _dataPosition;
key = _reader.AllocateStringForNameIndex(_currentName, out _dataPosition);
value = _reader.GetValueForNameIndex(_currentName);
return new DictionaryEntry(key, value);
}
}
public Object Value
{
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
return _reader.GetValueForNameIndex(_currentName);
}
}
public void Reset()
{
if (_reader._store == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
_currentIsValid = false;
_currentName = ENUM_NOT_STARTED;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.Tracing;
using Xunit;
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
using Microsoft.Diagnostics.Tracing.Session;
#endif
using System.Diagnostics;
namespace BasicEventSourceTests
{
internal enum Color { Red, Blue, Green };
internal enum ColorUInt32 : uint { Red, Blue, Green };
internal enum ColorByte : byte { Red, Blue, Green };
internal enum ColorSByte : sbyte { Red, Blue, Green };
internal enum ColorInt16 : short { Red, Blue, Green };
internal enum ColorUInt16 : ushort { Red, Blue, Green };
internal enum ColorInt64 : long { Red, Blue, Green };
internal enum ColorUInt64 : ulong { Red, Blue, Green };
public class TestsWrite
{
[EventData]
private struct PartB_UserInfo
{
public string UserName { get; set; }
}
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the EventListener code path
/// </summary>
[Fact]
[ActiveIssue("dotnet/corefx #19455", TargetFrameworkMonikers.NetFramework)]
public void Test_Write_T_EventListener()
{
using (var listener = new EventListenerListener())
{
Test_Write_T(listener);
}
}
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the EventListener code path using events instead of virtual callbacks.
/// </summary>
[Fact]
[ActiveIssue("dotnet/corefx #19455", TargetFrameworkMonikers.NetFramework)]
public void Test_Write_T_EventListener_UseEvents()
{
Test_Write_T(new EventListenerListener(true));
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the ETW code path
/// </summary>
[Fact]
public void Test_Write_T_ETW()
{
using (var listener = new EtwListener())
{
Test_Write_T(listener);
}
}
#endif //USE_ETW
/// <summary>
/// Te
/// </summary>
/// <param name="listener"></param>
private void Test_Write_T(Listener listener)
{
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var logger = new EventSource("EventSourceName"))
{
var tests = new List<SubTest>();
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/String",
delegate ()
{
logger.Write("Greeting", new { msg = "Hello, world!" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Greeting", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "msg"), "Hello, world!");
}));
/*************************************************************************/
decimal myMoney = 300;
tests.Add(new SubTest("Write/Basic/decimal",
delegate ()
{
logger.Write("Decimal", new { money = myMoney });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Decimal", evt.EventName);
var eventMoney = evt.PayloadValue(0, "money");
// TOD FIX ME - Fix TraceEvent to return decimal instead of double.
//Assert.Equal((decimal)eventMoney, (decimal)300);
}));
/*************************************************************************/
DateTime now = DateTime.Now;
tests.Add(new SubTest("Write/Basic/DateTime",
delegate ()
{
logger.Write("DateTime", new { nowTime = now });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("DateTime", evt.EventName);
var eventNow = evt.PayloadValue(0, "nowTime");
Assert.Equal(eventNow, now);
}));
/*************************************************************************/
byte[] byteArray = { 0, 1, 2, 3 };
tests.Add(new SubTest("Write/Basic/byte[]",
delegate ()
{
logger.Write("Bytes", new { bytes = byteArray });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Bytes", evt.EventName);
var eventArray = evt.PayloadValue(0, "bytes");
Array.Equals(eventArray, byteArray);
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/PartBOnly",
delegate ()
{
// log just a PartB
logger.Write("UserInfo", new EventSourceOptions { Keywords = EventKeywords.None },
new { _1 = new PartB_UserInfo { UserName = "Someone Else" } });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("UserInfo", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Someone Else");
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/PartBAndC",
delegate ()
{
// log a PartB and a PartC
logger.Write("Duration", new EventSourceOptions { Keywords = EventKeywords.None },
new { _1 = new PartB_UserInfo { UserName = "Myself" }, msec = 10 });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Duration", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Myself");
Assert.Equal(evt.PayloadValue(1, "msec"), 10);
}));
/*************************************************************************/
/*************************** ENUM TESTING *******************************/
/*************************************************************************/
/*************************************************************************/
GenerateEnumTest<Color>(ref tests, logger, Color.Green);
GenerateEnumTest<ColorUInt32>(ref tests, logger, ColorUInt32.Green);
GenerateEnumTest<ColorByte>(ref tests, logger, ColorByte.Green);
GenerateEnumTest<ColorSByte>(ref tests, logger, ColorSByte.Green);
GenerateEnumTest<ColorInt16>(ref tests, logger, ColorInt16.Green);
GenerateEnumTest<ColorUInt16>(ref tests, logger, ColorUInt16.Green);
GenerateEnumTest<ColorInt64>(ref tests, logger, ColorInt64.Green);
GenerateEnumTest<ColorUInt64>(ref tests, logger, ColorUInt64.Green);
/*************************************************************************/
/*************************** ARRAY TESTING *******************************/
/*************************************************************************/
/*************************************************************************/
GenerateArrayTest<Boolean>(ref tests, logger, new Boolean[] { false, true, false });
GenerateArrayTest<byte>(ref tests, logger, new byte[] { 1, 10, 100 });
GenerateArrayTest<sbyte>(ref tests, logger, new sbyte[] { 1, 10, 100 });
GenerateArrayTest<Int16>(ref tests, logger, new Int16[] { 1, 10, 100 });
GenerateArrayTest<UInt16>(ref tests, logger, new UInt16[] { 1, 10, 100 });
GenerateArrayTest<Int32>(ref tests, logger, new Int32[] { 1, 10, 100 });
GenerateArrayTest<UInt32>(ref tests, logger, new UInt32[] { 1, 10, 100 });
GenerateArrayTest<Int64>(ref tests, logger, new Int64[] { 1, 10, 100 });
GenerateArrayTest<UInt64>(ref tests, logger, new UInt64[] { 1, 10, 100 });
GenerateArrayTest<Char>(ref tests, logger, new Char[] { 'a', 'c', 'b' });
GenerateArrayTest<Double>(ref tests, logger, new Double[] { 1, 10, 100 });
GenerateArrayTest<Single>(ref tests, logger, new Single[] { 1, 10, 100 });
GenerateArrayTest<IntPtr>(ref tests, logger, new IntPtr[] { (IntPtr)1, (IntPtr)10, (IntPtr)100 });
GenerateArrayTest<UIntPtr>(ref tests, logger, new UIntPtr[] { (UIntPtr)1, (UIntPtr)10, (UIntPtr)100 });
GenerateArrayTest<Guid>(ref tests, logger, new Guid[] { Guid.Empty, new Guid("121a11ee-3bcb-49cc-b425-f4906fb14f72") });
/*************************************************************************/
/*********************** DICTIONARY TESTING ******************************/
/*************************************************************************/
var dict = new Dictionary<string, string>() { { "elem1", "10" }, { "elem2", "20" } };
var dictInt = new Dictionary<string, int>() { { "elem1", 10 }, { "elem2", 20 } };
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithStringDict_C",
delegate()
{
// log a dictionary
logger.Write("EventWithStringDict_C", new {
myDict = dict,
s = "end" });
},
delegate(Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithStringDict_C", evt.EventName);
var keyValues = evt.PayloadValue(0, "myDict");
IDictionary<string, object> vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.Equal(vDict["elem1"], "10");
Assert.Equal(vDict["elem2"], "20");
Assert.Equal(evt.PayloadValue(1, "s"), "end");
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithStringDict_BC",
delegate()
{
// log a PartB and a dictionary as a PartC
logger.Write("EventWithStringDict_BC", new {
PartB_UserInfo = new { UserName = "Me", LogTime = "Now" },
PartC_Dict = dict,
s = "end" });
},
delegate(Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithStringDict_BC", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Me");
Assert.Equal(structValueAsDictionary["LogTime"], "Now");
var keyValues = evt.PayloadValue(1, "PartC_Dict");
var vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.NotNull(dict);
Assert.Equal(vDict["elem1"], "10"); // string values.
Assert.Equal(vDict["elem2"], "20");
Assert.Equal(evt.PayloadValue(2, "s"), "end");
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithIntDict_BC",
delegate()
{
// log a Dict<string, int> as a PartC
logger.Write("EventWithIntDict_BC", new {
PartB_UserInfo = new { UserName = "Me", LogTime = "Now" },
PartC_Dict = dictInt,
s = "end" });
},
delegate(Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithIntDict_BC", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Me");
Assert.Equal(structValueAsDictionary["LogTime"], "Now");
var keyValues = evt.PayloadValue(1, "PartC_Dict");
var vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.NotNull(vDict);
Assert.Equal(vDict["elem1"], 10); // Notice they are integers, not strings.
Assert.Equal(vDict["elem2"], 20);
Assert.Equal(evt.PayloadValue(2, "s"), "end");
}));
/*************************************************************************/
/**************************** Empty Event TESTING ************************/
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/Message",
delegate ()
{
logger.Write("EmptyEvent");
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EmptyEvent", evt.EventName);
}));
/*************************************************************************/
/**************************** EventSourceOptions TESTING *****************/
/*************************************************************************/
EventSourceOptions options = new EventSourceOptions();
options.Level = EventLevel.LogAlways;
options.Keywords = EventKeywords.All;
options.Opcode = EventOpcode.Info;
options.Tags = EventTags.None;
tests.Add(new SubTest("Write/Basic/MessageOptions",
delegate ()
{
logger.Write("EmptyEvent", options);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EmptyEvent", evt.EventName);
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios",
delegate ()
{
logger.Write("OptionsEvent", options, new { OptionsEvent = "test options!" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("OptionsEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test options!");
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithRefOptios",
delegate ()
{
var v = new { OptionsEvent = "test ref options!" };
logger.Write("RefOptionsEvent", ref options, ref v);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("RefOptionsEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test ref options!");
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithNullString",
delegate ()
{
string nullString = null;
logger.Write("NullStringEvent", new { a = (string)null, b = nullString });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("NullStringEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "a"), "");
Assert.Equal(evt.PayloadValue(1, "b"), "");
}));
Guid activityId = new Guid("00000000-0000-0000-0000-000000000001");
Guid relActivityId = new Guid("00000000-0000-0000-0000-000000000002");
tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios",
delegate ()
{
var v = new { ActivityMsg = "test activity!" };
logger.Write("ActivityEvent", ref options, ref activityId, ref relActivityId, ref v);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("ActivityEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "ActivityMsg"), "test activity!");
}));
// If you only wish to run one or several of the tests you can filter them here by
// Uncommenting the following line.
// tests = tests.FindAll(test => Regex.IsMatch(test.Name, "Write/Basic/EventII"));
// Here is where we actually run tests. First test the ETW path
EventTestHarness.RunTests(tests, listener, logger);
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
/// <summary>
/// This is not a user error but it is something unusual.
/// You can use the Write API in a EventSource that was did not
/// Declare SelfDescribingSerialization. In that case THOSE
/// events MUST use SelfDescribing serialization.
/// </summary>
[Fact]
[ActiveIssue("dotnet/corefx #18806", TargetFrameworkMonikers.NetFramework)]
public void Test_Write_T_In_Manifest_Serialization()
{
using (var eventListener = new EventListenerListener())
{
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
using (var etwListener = new EtwListener())
#endif
{
var listenerGenerators = new Func<Listener>[]
{
() => eventListener,
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
() => etwListener
#endif // USE_ETW
};
foreach (Func<Listener> listenerGenerator in listenerGenerators)
{
var events = new List<Event>();
using (var listener = listenerGenerator())
{
Debug.WriteLine("Testing Listener " + listener);
// Create an eventSource with manifest based serialization
using (var logger = new SdtEventSources.EventSourceTest())
{
listener.OnEvent = delegate (Event data) { events.Add(data); };
listener.EventSourceSynchronousEnable(logger);
// Use the Write<T> API. This is OK
logger.Write("MyTestEvent", new { arg1 = 3, arg2 = "hi" });
}
}
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("MyTestEvent", _event.EventName);
Assert.Equal(3, (int)_event.PayloadValue(0, "arg1"));
Assert.Equal("hi", (string)_event.PayloadValue(1, "arg2"));
}
}
}
}
private void GenerateEnumTest<T>(ref List<SubTest> tests, EventSource logger, T enumValue)
{
string subTestName = enumValue.GetType().ToString();
tests.Add(new SubTest("Write/Enum/EnumEvent" + subTestName,
delegate ()
{
T c = enumValue;
// log an array
logger.Write("EnumEvent" + subTestName, new { b = "start", v = c, s = "end" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EnumEvent" + subTestName, evt.EventName);
Assert.Equal(evt.PayloadValue(0, "b"), "start");
if (evt.IsEtw)
{
var value = evt.PayloadValue(1, "v");
Assert.Equal(2, int.Parse(value.ToString())); // Green has the int value of 2.
}
else
{
Assert.Equal(evt.PayloadValue(1, "v"), enumValue);
}
Assert.Equal(evt.PayloadValue(2, "s"), "end");
}));
}
private void GenerateArrayTest<T>(ref List<SubTest> tests, EventSource logger, T[] array)
{
string typeName = array.GetType().GetElementType().ToString();
tests.Add(new SubTest("Write/Array/" + typeName,
delegate ()
{
// log an array
logger.Write("SomeEvent" + typeName, new { a = array, s = "end" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("SomeEvent" + typeName, evt.EventName);
var eventArray = evt.PayloadValue(0, "a");
Array.Equals(array, eventArray);
Assert.Equal("end", evt.PayloadValue(1, "s"));
}));
}
/// <summary>
/// Convert an array of key value pairs (as ETW structs) into a dictionary with those values.
/// </summary>
/// <param name="structValue"></param>
/// <returns></returns>
private IDictionary<string, object> GetDictionaryFromKeyValueArray(object structValue)
{
var ret = new Dictionary<string, object>();
var asArray = structValue as object[];
Assert.NotNull(asArray);
foreach (var item in asArray)
{
var keyValue = item as IDictionary<string, object>;
Assert.Equal(keyValue.Count, 2);
ret.Add((string)keyValue["Key"], keyValue["Value"]);
}
return ret;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Compression
{
internal sealed partial class DeflateManagedStream : Stream
{
internal const int DefaultBufferSize = 8192;
private Stream _stream;
private CompressionMode _mode;
private bool _leaveOpen;
private InflaterManaged _inflater;
private DeflaterManaged _deflater;
private byte[] _buffer;
private int _asyncOperations;
private IFileFormatWriter _formatWriter;
private bool _wroteHeader;
private bool _wroteBytes;
public DeflateManagedStream(Stream stream, CompressionMode mode) : this(stream, mode, leaveOpen: false)
{
}
// Since a reader is being taken, CompressionMode.Decompress is implied
internal DeflateManagedStream(Stream stream, bool leaveOpen, IFileFormatReader reader)
{
Debug.Assert(reader != null, "The IFileFormatReader passed to the internal DeflateStream constructor must be non-null");
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream));
InitializeInflater(stream, leaveOpen, reader);
}
// A specific constructor to allow decompression of Deflate64
internal DeflateManagedStream(Stream stream, ZipArchiveEntry.CompressionMethodValues method)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream));
InitializeInflater(stream, false, null, method);
}
public DeflateManagedStream(Stream stream, CompressionMode mode, bool leaveOpen)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
switch (mode)
{
case CompressionMode.Decompress:
InitializeInflater(stream, leaveOpen);
break;
case CompressionMode.Compress:
InitializeDeflater(stream, leaveOpen, CompressionLevel.Optimal);
break;
default:
throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(mode));
}
}
// Implies mode = Compress
public DeflateManagedStream(Stream stream, CompressionLevel compressionLevel) : this(stream, compressionLevel, leaveOpen: false)
{
}
// Implies mode = Compress
public DeflateManagedStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
InitializeDeflater(stream, leaveOpen, compressionLevel);
}
/// <summary>
/// Sets up this DeflateManagedStream to be used for Inflation/Decompression
/// </summary>
internal void InitializeInflater(Stream stream, bool leaveOpen, IFileFormatReader reader = null, ZipArchiveEntry.CompressionMethodValues method = ZipArchiveEntry.CompressionMethodValues.Deflate)
{
Debug.Assert(stream != null);
Debug.Assert(method == ZipArchiveEntry.CompressionMethodValues.Deflate || method == ZipArchiveEntry.CompressionMethodValues.Deflate64);
if (!stream.CanRead)
throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream));
_inflater = new InflaterManaged(reader, method == ZipArchiveEntry.CompressionMethodValues.Deflate64 ? true : false);
_stream = stream;
_mode = CompressionMode.Decompress;
_leaveOpen = leaveOpen;
_buffer = new byte[DefaultBufferSize];
}
/// <summary>
/// Sets up this DeflateManagedStream to be used for Deflation/Compression
/// </summary>
internal void InitializeDeflater(Stream stream, bool leaveOpen, CompressionLevel compressionLevel)
{
Debug.Assert(stream != null);
if (!stream.CanWrite)
throw new ArgumentException(SR.NotSupported_UnwritableStream, nameof(stream));
_deflater = new DeflaterManaged();
_stream = stream;
_mode = CompressionMode.Compress;
_leaveOpen = leaveOpen;
_buffer = new byte[DefaultBufferSize];
}
internal void SetFileFormatWriter(IFileFormatWriter writer)
{
if (writer != null)
{
_formatWriter = writer;
}
}
public Stream BaseStream => _stream;
public override bool CanRead
{
get
{
if (_stream == null)
{
return false;
}
return (_mode == CompressionMode.Decompress && _stream.CanRead);
}
}
public override bool CanWrite
{
get
{
if (_stream == null)
{
return false;
}
return (_mode == CompressionMode.Compress && _stream.CanWrite);
}
}
public override bool CanSeek => false;
public override long Length
{
get { throw new NotSupportedException(SR.NotSupported); }
}
public override long Position
{
get { throw new NotSupportedException(SR.NotSupported); }
set { throw new NotSupportedException(SR.NotSupported); }
}
public override void Flush()
{
EnsureNotDisposed();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
EnsureNotDisposed();
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.NotSupported);
}
public override void SetLength(long value)
{
throw new NotSupportedException(SR.NotSupported);
}
public override int Read(byte[] array, int offset, int count)
{
EnsureDecompressionMode();
ValidateParameters(array, offset, count);
EnsureNotDisposed();
int bytesRead;
int currentOffset = offset;
int remainingCount = count;
while (true)
{
bytesRead = _inflater.Inflate(array, currentOffset, remainingCount);
currentOffset += bytesRead;
remainingCount -= bytesRead;
if (remainingCount == 0)
{
break;
}
if (_inflater.Finished())
{
// if we finished decompressing, we can't have anything left in the outputwindow.
Debug.Assert(_inflater.AvailableOutput == 0, "We should have copied all stuff out!");
break;
}
int bytes = _stream.Read(_buffer, 0, _buffer.Length);
if (bytes <= 0)
{
break;
}
else if (bytes > _buffer.Length)
{
// The stream is either malicious or poorly implemented and returned a number of
// bytes larger than the buffer supplied to it.
throw new InvalidDataException(SR.GenericInvalidData);
}
_inflater.SetInput(_buffer, 0, bytes);
}
return count - remainingCount;
}
private void ValidateParameters(byte[] array, int offset, int count)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (array.Length - offset < count)
throw new ArgumentException(SR.InvalidArgumentOffsetCount);
}
private void EnsureNotDisposed()
{
if (_stream == null)
ThrowStreamClosedException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowStreamClosedException()
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
private void EnsureDecompressionMode()
{
if (_mode != CompressionMode.Decompress)
ThrowCannotReadFromDeflateManagedStreamException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowCannotReadFromDeflateManagedStreamException()
{
throw new InvalidOperationException(SR.CannotReadFromDeflateStream);
}
private void EnsureCompressionMode()
{
if (_mode != CompressionMode.Compress)
ThrowCannotWriteToDeflateManagedStreamException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowCannotWriteToDeflateManagedStreamException()
{
throw new InvalidOperationException(SR.CannotWriteToDeflateStream);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
public override Task<int> ReadAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
EnsureDecompressionMode();
// We use this checking order for compat to earlier versions:
if (_asyncOperations != 0)
throw new InvalidOperationException(SR.InvalidBeginCall);
ValidateParameters(array, offset, count);
EnsureNotDisposed();
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
Interlocked.Increment(ref _asyncOperations);
Task<int> readTask = null;
try
{
// Try to read decompressed data in output buffer
int bytesRead = _inflater.Inflate(array, offset, count);
if (bytesRead != 0)
{
// If decompression output buffer is not empty, return immediately.
return Task.FromResult(bytesRead);
}
if (_inflater.Finished())
{
// end of compression stream
return Task.FromResult(0);
}
// If there is no data on the output buffer and we are not at
// the end of the stream, we need to get more data from the base stream
readTask = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
if (readTask == null)
{
throw new InvalidOperationException(SR.NotSupported_UnreadableStream);
}
return ReadAsyncCore(readTask, array, offset, count, cancellationToken);
}
finally
{
// if we haven't started any async work, decrement the counter to end the transaction
if (readTask == null)
{
Interlocked.Decrement(ref _asyncOperations);
}
}
}
private async Task<int> ReadAsyncCore(Task<int> readTask, byte[] array, int offset, int count, CancellationToken cancellationToken)
{
try
{
while (true)
{
int bytesRead = await readTask.ConfigureAwait(false);
EnsureNotDisposed();
if (bytesRead <= 0)
{
// This indicates the base stream has received EOF
return 0;
}
else if (bytesRead > _buffer.Length)
{
// The stream is either malicious or poorly implemented and returned a number of
// bytes larger than the buffer supplied to it.
throw new InvalidDataException(SR.GenericInvalidData);
}
cancellationToken.ThrowIfCancellationRequested();
// Feed the data from base stream into decompression engine
_inflater.SetInput(_buffer, 0, bytesRead);
bytesRead = _inflater.Inflate(array, offset, count);
if (bytesRead == 0 && !_inflater.Finished())
{
// We could have read in head information and didn't get any data.
// Read from the base stream again.
readTask = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
if (readTask == null)
{
throw new InvalidOperationException(SR.NotSupported_UnreadableStream);
}
}
else
{
return bytesRead;
}
}
}
finally
{
Interlocked.Decrement(ref _asyncOperations);
}
}
public override void Write(byte[] array, int offset, int count)
{
// Validate the state and the parameters
EnsureCompressionMode();
ValidateParameters(array, offset, count);
EnsureNotDisposed();
DoMaintenance(array, offset, count);
// Write compressed the bytes we already passed to the deflater:
WriteDeflaterOutput();
// Pass new bytes through deflater and write them too:
_deflater.SetInput(array, offset, count);
WriteDeflaterOutput();
}
private void WriteDeflaterOutput()
{
while (!_deflater.NeedsInput())
{
int compressedBytes = _deflater.GetDeflateOutput(_buffer);
if (compressedBytes > 0)
{
_stream.Write(_buffer, 0, compressedBytes);
}
}
}
/// <summary>
/// Perform deflate-mode maintenance required due to custom header and footer writers
/// (e.g. set by GZipStream).
/// </summary>
private void DoMaintenance(byte[] array, int offset, int count)
{
// If no bytes written, do nothing:
if (count <= 0)
return;
// Note that stream contains more than zero data bytes:
_wroteBytes = true;
// If no header/footer formatter present, nothing else to do:
if (_formatWriter == null)
return;
// If formatter has not yet written a header, do it now:
if (!_wroteHeader)
{
byte[] b = _formatWriter.GetHeader();
_stream.Write(b, 0, b.Length);
_wroteHeader = true;
}
// Inform formatter of the data bytes written:
_formatWriter.UpdateWithBytesRead(array, offset, count);
}
// This is called by Dispose:
private void PurgeBuffers(bool disposing)
{
if (!disposing)
return;
if (_stream == null)
return;
Flush();
if (_mode != CompressionMode.Compress)
return;
// Some deflaters (e.g. ZLib) write more than zero bytes for zero byte inputs.
// This round-trips and we should be ok with this, but our legacy managed deflater
// always wrote zero output for zero input and upstack code (e.g. ZipArchiveEntry)
// took dependencies on it. Thus, make sure to only "flush" when we actually had
// some input:
if (_wroteBytes)
{
// Compress any bytes left
WriteDeflaterOutput();
// Pull out any bytes left inside deflater:
bool finished;
do
{
int compressedBytes;
finished = _deflater.Finish(_buffer, out compressedBytes);
if (compressedBytes > 0)
_stream.Write(_buffer, 0, compressedBytes);
} while (!finished);
}
else
{
// In case of zero length buffer, we still need to clean up the native created stream before
// the object get disposed because eventually ZLibNative.ReleaseHandle will get called during
// the dispose operation and although it frees the stream but it return error code because the
// stream state was still marked as in use. The symptoms of this problem will not be seen except
// if running any diagnostic tools which check for disposing safe handle objects
bool finished;
do
{
int compressedBytes;
finished = _deflater.Finish(_buffer, out compressedBytes);
} while (!finished);
}
// Write format footer:
if (_formatWriter != null && _wroteHeader)
{
byte[] b = _formatWriter.GetFooter();
_stream.Write(b, 0, b.Length);
}
}
protected override void Dispose(bool disposing)
{
try
{
PurgeBuffers(disposing);
}
finally
{
// Close the underlying stream even if PurgeBuffers threw.
// Stream.Close() may throw here (may or may not be due to the same error).
// In this case, we still need to clean up internal resources, hence the inner finally blocks.
try
{
if (disposing && !_leaveOpen && _stream != null)
_stream.Dispose();
}
finally
{
_stream = null;
try
{
_deflater?.Dispose();
_inflater?.Dispose();
}
finally
{
_deflater = null;
_inflater = null;
base.Dispose(disposing);
}
}
}
}
public override Task WriteAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
EnsureCompressionMode();
// We use this checking order for compat to earlier versions:
if (_asyncOperations != 0)
throw new InvalidOperationException(SR.InvalidBeginCall);
ValidateParameters(array, offset, count);
EnsureNotDisposed();
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
return WriteAsyncCore(array, offset, count, cancellationToken);
}
private async Task WriteAsyncCore(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _asyncOperations);
try
{
await base.WriteAsync(array, offset, count, cancellationToken).ConfigureAwait(false);
}
finally
{
Interlocked.Decrement(ref _asyncOperations);
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.LogReceiverService
{
using System;
using System.IO;
using Xunit;
#if WCF_SUPPORTED
using System.Runtime.Serialization;
#endif
using System.Xml;
using System.Xml.Serialization;
using NLog.Layouts;
using NLog.LogReceiverService;
public class LogReceiverServiceTests : NLogTestBase
{
[Fact]
public void ToLogEventInfoTest()
{
var events = new NLogEvents
{
BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks,
ClientName = "foo",
LayoutNames = new StringCollection { "foo", "bar", "baz" },
Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" },
Events =
new[]
{
new NLogEvent
{
Id = 1,
LevelOrdinal = 2,
LoggerOrdinal = 0,
TimeDelta = 30000000,
MessageOrdinal = 4,
Values = "0|1|2"
},
new NLogEvent
{
Id = 2,
LevelOrdinal = 3,
LoggerOrdinal = 2,
MessageOrdinal = 4,
TimeDelta = 30050000,
Values = "0|1|3",
}
}
};
var converted = events.ToEventInfo();
Assert.Equal(2, converted.Count);
Assert.Equal("message1", converted[0].FormattedMessage);
Assert.Equal("message1", converted[1].FormattedMessage);
Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime());
Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime());
Assert.Equal("logger1", converted[0].LoggerName);
Assert.Equal("logger3", converted[1].LoggerName);
Assert.Equal(LogLevel.Info, converted[0].Level);
Assert.Equal(LogLevel.Warn, converted[1].Level);
Layout fooLayout = "${event-context:foo}";
Layout barLayout = "${event-context:bar}";
Layout bazLayout = "${event-context:baz}";
Assert.Equal("logger1", fooLayout.Render(converted[0]));
Assert.Equal("logger1", fooLayout.Render(converted[1]));
Assert.Equal("logger2", barLayout.Render(converted[0]));
Assert.Equal("logger2", barLayout.Render(converted[1]));
Assert.Equal("logger3", bazLayout.Render(converted[0]));
Assert.Equal("zzz", bazLayout.Render(converted[1]));
}
[Fact]
public void NoLayoutsTest()
{
var events = new NLogEvents
{
BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks,
ClientName = "foo",
LayoutNames = new StringCollection(),
Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" },
Events =
new[]
{
new NLogEvent
{
Id = 1,
LevelOrdinal = 2,
LoggerOrdinal = 0,
TimeDelta = 30000000,
MessageOrdinal = 4,
Values = null,
},
new NLogEvent
{
Id = 2,
LevelOrdinal = 3,
LoggerOrdinal = 2,
MessageOrdinal = 4,
TimeDelta = 30050000,
Values = null,
}
}
};
var converted = events.ToEventInfo();
Assert.Equal(2, converted.Count);
Assert.Equal("message1", converted[0].FormattedMessage);
Assert.Equal("message1", converted[1].FormattedMessage);
Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime());
Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime());
Assert.Equal("logger1", converted[0].LoggerName);
Assert.Equal("logger3", converted[1].LoggerName);
Assert.Equal(LogLevel.Info, converted[0].Level);
Assert.Equal(LogLevel.Warn, converted[1].Level);
}
#if !SILVERLIGHT
/// <summary>
/// Ensures that serialization formats of DataContractSerializer and XmlSerializer are the same
/// on the same <see cref="NLogEvents"/> object.
/// </summary>
[Fact]
public void CompareSerializationFormats()
{
var events = new NLogEvents
{
BaseTimeUtc = DateTime.UtcNow.Ticks,
ClientName = "foo",
LayoutNames = new StringCollection { "foo", "bar", "baz" },
Strings = new StringCollection { "logger1", "logger2", "logger3" },
Events =
new[]
{
new NLogEvent
{
Id = 1,
LevelOrdinal = 2,
LoggerOrdinal = 0,
TimeDelta = 34,
Values = "1|2|3"
},
new NLogEvent
{
Id = 2,
LevelOrdinal = 3,
LoggerOrdinal = 2,
TimeDelta = 345,
Values = "1|2|3",
}
}
};
var serializer1 = new XmlSerializer(typeof(NLogEvents));
var sw1 = new StringWriter();
using (var writer1 = XmlWriter.Create(sw1, new XmlWriterSettings { Indent = true }))
{
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("i", "http://www.w3.org/2001/XMLSchema-instance");
serializer1.Serialize(writer1, events, namespaces);
}
var serializer2 = new DataContractSerializer(typeof(NLogEvents));
var sw2 = new StringWriter();
using (var writer2 = XmlWriter.Create(sw2, new XmlWriterSettings { Indent = true }))
{
serializer2.WriteObject(writer2, events);
}
var xml1 = sw1.ToString();
var xml2 = sw2.ToString();
Assert.Equal(xml1, xml2);
}
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
namespace System.Net.Security
{
//
// Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob.
//
#if DEBUG
internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle
{
#else
internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
public SafeSspiAuthDataHandle() : base(true)
{
}
protected override bool ReleaseHandle()
{
return Interop.Secur32.SspiFreeAuthIdentity(handle) == Interop.SecurityStatus.OK;
}
}
//
// A set of Safe Handles that depend on native FreeContextBuffer finalizer
//
#if DEBUG
internal abstract class SafeFreeContextBuffer : DebugSafeHandle
{
#else
internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
protected SafeFreeContextBuffer() : base(true) { }
// This must be ONLY called from this file.
internal void Set(IntPtr value)
{
this.handle = value;
}
internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray)
{
int res = -1;
SafeFreeContextBuffer_SECURITY pkgArray_SECURITY = null;
res = Interop.Secur32.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY);
pkgArray = pkgArray_SECURITY;
if (res != 0 && pkgArray != null)
{
pkgArray.SetHandleAsInvalid();
}
return res;
}
internal static SafeFreeContextBuffer CreateEmptyHandle()
{
return new SafeFreeContextBuffer_SECURITY();
}
//
// After PInvoke call the method will fix the refHandle.handle with the returned value.
// The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned.
//
// This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and
// reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.)
//
public unsafe static int QueryContextAttributes(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle)
{
return QueryContextAttributes_SECURITY(phContext, contextAttribute, buffer, refHandle);
}
private unsafe static int QueryContextAttributes_SECURITY(
SafeDeleteContext phContext,
Interop.Secur32.ContextAttribute contextAttribute,
byte* buffer,
SafeHandle refHandle)
{
int status = (int)Interop.SecurityStatus.InvalidHandle;
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
status = Interop.Secur32.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer);
}
finally
{
phContext.DangerousRelease();
}
if (status == 0 && refHandle != null)
{
if (refHandle is SafeFreeContextBuffer)
{
((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer);
}
else
{
((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer);
}
}
if (status != 0 && refHandle != null)
{
refHandle.SetHandleAsInvalid();
}
return status;
}
public static int SetContextAttributes(
SafeDeleteContext phContext,
Interop.Secur32.ContextAttribute contextAttribute, byte[] buffer)
{
return SetContextAttributes_SECURITY(phContext, contextAttribute, buffer);
}
private static int SetContextAttributes_SECURITY(
SafeDeleteContext phContext,
Interop.Secur32.ContextAttribute contextAttribute,
byte[] buffer)
{
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
return Interop.Secur32.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length);
}
finally
{
phContext.DangerousRelease();
}
}
}
internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer
{
internal SafeFreeContextBuffer_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
return Interop.Secur32.FreeContextBuffer(handle) == 0;
}
}
//
// Implementation of handles required CertFreeCertificateContext
//
#if DEBUG
internal sealed class SafeFreeCertContext : DebugSafeHandle
{
#else
internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
internal SafeFreeCertContext() : base(true) { }
// This must be ONLY called from this file.
internal void Set(IntPtr value)
{
this.handle = value;
}
private const uint CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040;
protected override bool ReleaseHandle()
{
Interop.Crypt32.CertFreeCertificateContext(handle);
return true;
}
}
//
// Implementation of handles dependable on FreeCredentialsHandle
//
#if DEBUG
internal abstract class SafeFreeCredentials : DebugSafeHandle
{
#else
internal abstract class SafeFreeCredentials : SafeHandle
{
#endif
internal Interop.Secur32.SSPIHandle _handle; //should be always used as by ref in PInvokes parameters
protected SafeFreeCredentials() : base(IntPtr.Zero, true)
{
_handle = new Interop.Secur32.SSPIHandle();
}
#if TRACE_VERBOSE
public override string ToString()
{
return "0x" + _handle.ToString();
}
#endif
public override bool IsInvalid
{
get { return IsClosed || _handle.IsZero; }
}
#if DEBUG
public new IntPtr DangerousGetHandle()
{
Debug.Fail("This method should never be called for this type");
throw NotImplemented.ByDesign;
}
#endif
public unsafe static int AcquireCredentialsHandle(
string package,
Interop.Secur32.CredentialUse intent,
ref Interop.Secur32.AuthIdentity authdata,
out SafeFreeCredentials outCredential)
{
GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#1("
+ package + ", "
+ intent + ", "
+ authdata + ")");
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.Secur32.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
ref authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
#if TRACE_VERBOSE
GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
+ String.Format("{0:x}", errorCode)
+ ", handle = " + outCredential.ToString());
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public unsafe static int AcquireDefaultCredential(
string package,
Interop.Secur32.CredentialUse intent,
out SafeFreeCredentials outCredential)
{
GlobalLog.Print("SafeFreeCredentials::AcquireDefaultCredential("
+ package + ", "
+ intent + ")");
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.Secur32.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
IntPtr.Zero,
null,
null,
ref outCredential._handle,
out timeStamp);
#if TRACE_VERBOSE
GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
+ errorCode.ToString("x")
+ ", handle = " + outCredential.ToString());
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public unsafe static int AcquireCredentialsHandle(
string package,
Interop.Secur32.CredentialUse intent,
ref SafeSspiAuthDataHandle authdata,
out SafeFreeCredentials outCredential)
{
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.Secur32.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public unsafe static int AcquireCredentialsHandle(
string package,
Interop.Secur32.CredentialUse intent,
ref Interop.Secur32.SecureCredential authdata,
out SafeFreeCredentials outCredential)
{
GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#2("
+ package + ", "
+ intent + ", "
+ authdata + ")");
int errorCode = -1;
long timeStamp;
// If there is a certificate, wrap it into an array.
// Not threadsafe.
IntPtr copiedPtr = authdata.certContextArray;
try
{
IntPtr certArrayPtr = new IntPtr(&copiedPtr);
if (copiedPtr != IntPtr.Zero)
{
authdata.certContextArray = certArrayPtr;
}
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.Secur32.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
ref authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
}
finally
{
authdata.certContextArray = copiedPtr;
}
#if TRACE_VERBOSE
GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
+ errorCode.ToString("x")
+ ", handle = " + outCredential.ToString());
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
}
//
// This is a class holding a Credential handle reference, used for static handles cache
//
#if DEBUG
internal sealed class SafeCredentialReference : DebugCriticalHandleMinusOneIsInvalid
{
#else
internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid
{
#endif
//
// Static cache will return the target handle if found the reference in the table.
//
internal SafeFreeCredentials Target;
internal static SafeCredentialReference CreateReference(SafeFreeCredentials target)
{
SafeCredentialReference result = new SafeCredentialReference(target);
if (result.IsInvalid)
{
return null;
}
return result;
}
private SafeCredentialReference(SafeFreeCredentials target) : base()
{
// Bumps up the refcount on Target to signify that target handle is statically cached so
// its dispose should be postponed
bool ignore = false;
target.DangerousAddRef(ref ignore);
Target = target;
SetHandle(new IntPtr(0)); // make this handle valid
}
protected override bool ReleaseHandle()
{
SafeFreeCredentials target = Target;
if (target != null)
{
target.DangerousRelease();
}
Target = null;
return true;
}
}
internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials
{
public SafeFreeCredential_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
return Interop.Secur32.FreeCredentialsHandle(ref _handle) == 0;
}
}
//
// Implementation of handles that are dependent on DeleteSecurityContext
//
#if DEBUG
internal abstract class SafeDeleteContext : DebugSafeHandle
{
#else
internal abstract class SafeDeleteContext : SafeHandle
{
#endif
private const string dummyStr = " ";
private static readonly byte[] s_dummyBytes = new byte[] { 0 };
//
// ATN: _handle is internal since it is used on PInvokes by other wrapper methods.
// However all such wrappers MUST manually and reliably adjust refCounter of SafeDeleteContext handle.
//
internal Interop.Secur32.SSPIHandle _handle;
protected SafeFreeCredentials _EffectiveCredential;
protected SafeDeleteContext() : base(IntPtr.Zero, true)
{
_handle = new Interop.Secur32.SSPIHandle();
}
public override bool IsInvalid
{
get
{
return IsClosed || _handle.IsZero;
}
}
public override string ToString()
{
return _handle.ToString();
}
#if DEBUG
//This method should never be called for this type
public new IntPtr DangerousGetHandle()
{
throw new InvalidOperationException();
}
#endif
//-------------------------------------------------------------------
internal unsafe static int InitializeSecurityContext(
ref SafeFreeCredentials inCredentials,
ref SafeDeleteContext refContext,
string targetName,
Interop.Secur32.ContextFlags inFlags,
Interop.Secur32.Endianness endianness,
SecurityBuffer inSecBuffer,
SecurityBuffer[] inSecBuffers,
SecurityBuffer outSecBuffer,
ref Interop.Secur32.ContextFlags outFlags)
{
#if TRACE_VERBOSE
GlobalLog.Enter("SafeDeleteContext::InitializeSecurityContext");
GlobalLog.Print(" credential = " + inCredentials.ToString());
GlobalLog.Print(" refContext = " + Logging.ObjectToString(refContext));
GlobalLog.Print(" targetName = " + targetName);
GlobalLog.Print(" inFlags = " + inFlags);
GlobalLog.Print(" reservedI = 0x0");
GlobalLog.Print(" endianness = " + endianness);
if (inSecBuffers == null)
{
GlobalLog.Print(" inSecBuffers = (null)");
}
else
{
GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
}
#endif
GlobalLog.Assert(outSecBuffer != null, "SafeDeleteContext::InitializeSecurityContext()|outSecBuffer != null");
GlobalLog.Assert(inSecBuffer == null || inSecBuffers == null, "SafeDeleteContext::InitializeSecurityContext()|inSecBuffer == null || inSecBuffers == null");
if (inCredentials == null)
{
throw new ArgumentNullException("inCredentials");
}
Interop.Secur32.SecurityBufferDescriptor inSecurityBufferDescriptor = null;
if (inSecBuffer != null)
{
inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(1);
}
else if (inSecBuffers != null)
{
inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(inSecBuffers.Length);
}
Interop.Secur32.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(1);
// Actually, this is returned in outFlags.
bool isSspiAllocated = (inFlags & Interop.Secur32.ContextFlags.AllocateMemory) != 0 ? true : false;
int errorCode = -1;
Interop.Secur32.SSPIHandle contextHandle = new Interop.Secur32.SSPIHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
GCHandle pinnedOutBytes = new GCHandle();
// Optional output buffer that may need to be freed.
SafeFreeContextBuffer outFreeContextBuffer = null;
try
{
pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
Interop.Secur32.SecurityBufferStruct[] inUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
if (inSecurityBufferDescriptor != null)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
{
securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index];
if (securityBuffer != null)
{
// Copy the SecurityBuffer content into unmanaged place holder.
inUnmanagedBuffer[index].count = securityBuffer.size;
inUnmanagedBuffer[index].type = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].token = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
#endif
}
}
}
Interop.Secur32.SecurityBufferStruct[] outUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[1];
fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr;
outUnmanagedBuffer[0].count = outSecBuffer.size;
outUnmanagedBuffer[0].type = outSecBuffer.type;
if (outSecBuffer.token == null || outSecBuffer.token.Length == 0)
{
outUnmanagedBuffer[0].token = IntPtr.Zero;
}
else
{
outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
}
if (isSspiAllocated)
{
outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle();
}
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
if (targetName == null || targetName.Length == 0)
{
targetName = dummyStr;
}
fixed (char* namePtr = targetName)
{
errorCode = MustRunInitializeSecurityContext_SECURITY(
ref inCredentials,
contextHandle.IsZero ? null : &contextHandle,
(byte*)(((object)targetName == (object)dummyStr) ? null : namePtr),
inFlags,
endianness,
inSecurityBufferDescriptor,
refContext,
outSecurityBufferDescriptor,
ref outFlags,
outFreeContextBuffer);
}
GlobalLog.Print("SafeDeleteContext:InitializeSecurityContext Marshalling OUT buffer");
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].count;
outSecBuffer.type = outUnmanagedBuffer[0].type;
if (outSecBuffer.size > 0)
{
outSecBuffer.token = new byte[outSecBuffer.size];
Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size);
}
else
{
outSecBuffer.token = null;
}
}
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
if (pinnedOutBytes.IsAllocated)
{
pinnedOutBytes.Free();
}
if (outFreeContextBuffer != null)
{
outFreeContextBuffer.Dispose();
}
}
GlobalLog.Leave("SafeDeleteContext::InitializeSecurityContext() unmanaged InitializeSecurityContext()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + Logging.ObjectToString(refContext));
return errorCode;
}
//
// After PInvoke call the method will fix the handleTemplate.handle with the returned value.
// The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavour or null can be passed if no handle is returned.
//
private static unsafe int MustRunInitializeSecurityContext_SECURITY(
ref SafeFreeCredentials inCredentials,
void* inContextPtr,
byte* targetName,
Interop.Secur32.ContextFlags inFlags,
Interop.Secur32.Endianness endianness,
Interop.Secur32.SecurityBufferDescriptor inputBuffer,
SafeDeleteContext outContext,
Interop.Secur32.SecurityBufferDescriptor outputBuffer,
ref Interop.Secur32.ContextFlags attributes,
SafeFreeContextBuffer handleTemplate)
{
int errorCode = (int)Interop.SecurityStatus.InvalidHandle;
try
{
bool ignore = false;
inCredentials.DangerousAddRef(ref ignore);
outContext.DangerousAddRef(ref ignore);
Interop.Secur32.SSPIHandle credentialHandle = inCredentials._handle;
long timeStamp;
errorCode = Interop.Secur32.InitializeSecurityContextW(
ref credentialHandle,
inContextPtr,
targetName,
inFlags,
0,
endianness,
inputBuffer,
0,
ref outContext._handle,
outputBuffer,
ref attributes,
out timeStamp);
}
finally
{
//
// When a credential handle is first associated with the context we keep credential
// ref count bumped up to ensure ordered finalization.
// If the credential handle has been changed we de-ref the old one and associate the
// context with the new cred handle but only if the call was successful.
if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0)
{
// Disassociate the previous credential handle
if (outContext._EffectiveCredential != null)
{
outContext._EffectiveCredential.DangerousRelease();
}
outContext._EffectiveCredential = inCredentials;
}
else
{
inCredentials.DangerousRelease();
}
outContext.DangerousRelease();
}
// The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer.
if (handleTemplate != null)
{
//ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes
handleTemplate.Set(((Interop.Secur32.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token);
if (handleTemplate.IsInvalid)
{
handleTemplate.SetHandleAsInvalid();
}
}
if (inContextPtr == null && (errorCode & 0x80000000) != 0)
{
// an error on the first call, need to set the out handle to invalid value
outContext._handle.SetToInvalid();
}
return errorCode;
}
//-------------------------------------------------------------------
internal unsafe static int AcceptSecurityContext(
ref SafeFreeCredentials inCredentials,
ref SafeDeleteContext refContext,
Interop.Secur32.ContextFlags inFlags,
Interop.Secur32.Endianness endianness,
SecurityBuffer inSecBuffer,
SecurityBuffer[] inSecBuffers,
SecurityBuffer outSecBuffer,
ref Interop.Secur32.ContextFlags outFlags)
{
#if TRACE_VERBOSE
GlobalLog.Enter("SafeDeleteContext::AcceptSecurityContex");
GlobalLog.Print(" credential = " + inCredentials.ToString());
GlobalLog.Print(" refContext = " + Logging.ObjectToString(refContext));
GlobalLog.Print(" inFlags = " + inFlags);
if (inSecBuffers == null)
{
GlobalLog.Print(" inSecBuffers = (null)");
}
else
{
GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
}
#endif
GlobalLog.Assert(outSecBuffer != null, "SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null");
GlobalLog.Assert(inSecBuffer == null || inSecBuffers == null, "SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null");
if (inCredentials == null)
{
throw new ArgumentNullException("inCredentials");
}
Interop.Secur32.SecurityBufferDescriptor inSecurityBufferDescriptor = null;
if (inSecBuffer != null)
{
inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(1);
}
else if (inSecBuffers != null)
{
inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(inSecBuffers.Length);
}
Interop.Secur32.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(1);
// Actually, this is returned in outFlags.
bool isSspiAllocated = (inFlags & Interop.Secur32.ContextFlags.AllocateMemory) != 0 ? true : false;
int errorCode = -1;
Interop.Secur32.SSPIHandle contextHandle = new Interop.Secur32.SSPIHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
GCHandle pinnedOutBytes = new GCHandle();
// Optional output buffer that may need to be freed.
SafeFreeContextBuffer outFreeContextBuffer = null;
try
{
pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
var inUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
if (inSecurityBufferDescriptor != null)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
{
securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index];
if (securityBuffer != null)
{
// Copy the SecurityBuffer content into unmanaged place holder.
inUnmanagedBuffer[index].count = securityBuffer.size;
inUnmanagedBuffer[index].type = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].token = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
#endif
}
}
}
var outUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[1];
fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr;
// Copy the SecurityBuffer content into unmanaged place holder.
outUnmanagedBuffer[0].count = outSecBuffer.size;
outUnmanagedBuffer[0].type = outSecBuffer.type;
if (outSecBuffer.token == null || outSecBuffer.token.Length == 0)
{
outUnmanagedBuffer[0].token = IntPtr.Zero;
}
else
{
outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
}
if (isSspiAllocated)
{
outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle();
}
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
errorCode = MustRunAcceptSecurityContext_SECURITY(
ref inCredentials,
contextHandle.IsZero ? null : &contextHandle,
inSecurityBufferDescriptor,
inFlags,
endianness,
refContext,
outSecurityBufferDescriptor,
ref outFlags,
outFreeContextBuffer);
GlobalLog.Print("SafeDeleteContext:AcceptSecurityContext Marshalling OUT buffer");
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].count;
outSecBuffer.type = outUnmanagedBuffer[0].type;
if (outSecBuffer.size > 0)
{
outSecBuffer.token = new byte[outSecBuffer.size];
Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size);
}
else
{
outSecBuffer.token = null;
}
}
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
if (pinnedOutBytes.IsAllocated)
{
pinnedOutBytes.Free();
}
if (outFreeContextBuffer != null)
{
outFreeContextBuffer.Dispose();
}
}
GlobalLog.Leave("SafeDeleteContext::AcceptSecurityContex() unmanaged AcceptSecurityContex()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + Logging.ObjectToString(refContext));
return errorCode;
}
//
// After PInvoke call the method will fix the handleTemplate.handle with the returned value.
// The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavour or null can be passed if no handle is returned.
//
private static unsafe int MustRunAcceptSecurityContext_SECURITY(
ref SafeFreeCredentials inCredentials,
void* inContextPtr,
Interop.Secur32.SecurityBufferDescriptor inputBuffer,
Interop.Secur32.ContextFlags inFlags,
Interop.Secur32.Endianness endianness,
SafeDeleteContext outContext,
Interop.Secur32.SecurityBufferDescriptor outputBuffer,
ref Interop.Secur32.ContextFlags outFlags,
SafeFreeContextBuffer handleTemplate)
{
int errorCode = (int)Interop.SecurityStatus.InvalidHandle;
// Run the body of this method as a non-interruptible block.
try
{
bool ignore = false;
inCredentials.DangerousAddRef(ref ignore);
outContext.DangerousAddRef(ref ignore);
Interop.Secur32.SSPIHandle credentialHandle = inCredentials._handle;
long timeStamp;
errorCode = Interop.Secur32.AcceptSecurityContext(
ref credentialHandle,
inContextPtr,
inputBuffer,
inFlags,
endianness,
ref outContext._handle,
outputBuffer,
ref outFlags,
out timeStamp);
}
finally
{
//
// When a credential handle is first associated with the context we keep credential
// ref count bumped up to ensure ordered finalization.
// If the credential handle has been changed we de-ref the old one and associate the
// context with the new cred handle but only if the call was successful.
if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0)
{
// Disassociate the previous credential handle.
if (outContext._EffectiveCredential != null)
{
outContext._EffectiveCredential.DangerousRelease();
}
outContext._EffectiveCredential = inCredentials;
}
else
{
inCredentials.DangerousRelease();
}
outContext.DangerousRelease();
}
// The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer.
if (handleTemplate != null)
{
//ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes.
handleTemplate.Set(((Interop.Secur32.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token);
if (handleTemplate.IsInvalid)
{
handleTemplate.SetHandleAsInvalid();
}
}
if (inContextPtr == null && (errorCode & 0x80000000) != 0)
{
// An error on the first call, need to set the out handle to invalid value.
outContext._handle.SetToInvalid();
}
return errorCode;
}
internal unsafe static int CompleteAuthToken(
ref SafeDeleteContext refContext,
SecurityBuffer[] inSecBuffers)
{
GlobalLog.Enter("SafeDeleteContext::CompleteAuthToken");
GlobalLog.Print(" refContext = " + Logging.ObjectToString(refContext));
#if TRACE_VERBOSE
GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
#endif
GlobalLog.Assert(inSecBuffers != null, "SafeDeleteContext::CompleteAuthToken()|inSecBuffers == null");
var inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(inSecBuffers.Length);
int errorCode = (int)Interop.SecurityStatus.InvalidHandle;
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
var inUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[inSecurityBufferDescriptor.Count];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
{
securityBuffer = inSecBuffers[index];
if (securityBuffer != null)
{
inUnmanagedBuffer[index].count = securityBuffer.size;
inUnmanagedBuffer[index].type = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].token = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
#endif
}
}
Interop.Secur32.SSPIHandle contextHandle = new Interop.Secur32.SSPIHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
try
{
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
try
{
bool ignore = false;
refContext.DangerousAddRef(ref ignore);
errorCode = Interop.Secur32.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, inSecurityBufferDescriptor);
}
finally
{
refContext.DangerousRelease();
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
}
}
GlobalLog.Leave("SafeDeleteContext::CompleteAuthToken() unmanaged CompleteAuthToken()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + Logging.ObjectToString(refContext));
return errorCode;
}
}
internal sealed class SafeDeleteContext_SECURITY : SafeDeleteContext
{
internal SafeDeleteContext_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
if (this._EffectiveCredential != null)
{
this._EffectiveCredential.DangerousRelease();
}
return Interop.Secur32.DeleteSecurityContext(ref _handle) == 0;
}
}
// Based on SafeFreeContextBuffer.
internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding
{
private int _size;
public override int Size
{
get { return _size; }
}
public override bool IsInvalid
{
get { return handle == new IntPtr(0) || handle == new IntPtr(-1); }
}
internal unsafe void Set(IntPtr value)
{
this.handle = value;
}
internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle()
{
return new SafeFreeContextBufferChannelBinding_SECURITY();
}
public unsafe static int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
{
return QueryContextChannelBinding_SECURITY(phContext, contextAttribute, buffer, refHandle);
}
private unsafe static int QueryContextChannelBinding_SECURITY(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
{
int status = (int)Interop.SecurityStatus.InvalidHandle;
// SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which
// map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique.
if (contextAttribute != Interop.Secur32.ContextAttribute.EndpointBindings &&
contextAttribute != Interop.Secur32.ContextAttribute.UniqueBindings)
{
return status;
}
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
status = Interop.Secur32.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer);
}
finally
{
phContext.DangerousRelease();
}
if (status == 0 && refHandle != null)
{
refHandle.Set((*buffer).pBindings);
refHandle._size = (*buffer).BindingsLength;
}
if (status != 0 && refHandle != null)
{
refHandle.SetHandleAsInvalid();
}
return status;
}
}
internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding
{
protected override bool ReleaseHandle()
{
return Interop.Secur32.FreeContextBuffer(handle) == 0;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Steamworks.Data;
namespace Steamworks
{
internal unsafe class ISteamHTMLSurface : SteamInterface
{
internal ISteamHTMLSurface( bool IsGameServer )
{
SetupInterface( IsGameServer );
}
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_SteamHTMLSurface_v005", CallingConvention = Platform.CC)]
internal static extern IntPtr SteamAPI_SteamHTMLSurface_v005();
public override IntPtr GetUserInterfacePointer() => SteamAPI_SteamHTMLSurface_v005();
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_Init", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _Init( IntPtr self );
#endregion
internal bool Init()
{
var returnValue = _Init( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_Shutdown", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _Shutdown( IntPtr self );
#endregion
internal bool Shutdown()
{
var returnValue = _Shutdown( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_CreateBrowser", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _CreateBrowser( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchUserAgent, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchUserCSS );
#endregion
internal CallResult<HTML_BrowserReady_t> CreateBrowser( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchUserAgent, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchUserCSS )
{
var returnValue = _CreateBrowser( Self, pchUserAgent, pchUserCSS );
return new CallResult<HTML_BrowserReady_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_RemoveBrowser", CallingConvention = Platform.CC)]
private static extern void _RemoveBrowser( IntPtr self, HHTMLBrowser unBrowserHandle );
#endregion
internal void RemoveBrowser( HHTMLBrowser unBrowserHandle )
{
_RemoveBrowser( Self, unBrowserHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_LoadURL", CallingConvention = Platform.CC)]
private static extern void _LoadURL( IntPtr self, HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchURL, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchPostData );
#endregion
internal void LoadURL( HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchURL, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchPostData )
{
_LoadURL( Self, unBrowserHandle, pchURL, pchPostData );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_SetSize", CallingConvention = Platform.CC)]
private static extern void _SetSize( IntPtr self, HHTMLBrowser unBrowserHandle, uint unWidth, uint unHeight );
#endregion
internal void SetSize( HHTMLBrowser unBrowserHandle, uint unWidth, uint unHeight )
{
_SetSize( Self, unBrowserHandle, unWidth, unHeight );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_StopLoad", CallingConvention = Platform.CC)]
private static extern void _StopLoad( IntPtr self, HHTMLBrowser unBrowserHandle );
#endregion
internal void StopLoad( HHTMLBrowser unBrowserHandle )
{
_StopLoad( Self, unBrowserHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_Reload", CallingConvention = Platform.CC)]
private static extern void _Reload( IntPtr self, HHTMLBrowser unBrowserHandle );
#endregion
internal void Reload( HHTMLBrowser unBrowserHandle )
{
_Reload( Self, unBrowserHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_GoBack", CallingConvention = Platform.CC)]
private static extern void _GoBack( IntPtr self, HHTMLBrowser unBrowserHandle );
#endregion
internal void GoBack( HHTMLBrowser unBrowserHandle )
{
_GoBack( Self, unBrowserHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_GoForward", CallingConvention = Platform.CC)]
private static extern void _GoForward( IntPtr self, HHTMLBrowser unBrowserHandle );
#endregion
internal void GoForward( HHTMLBrowser unBrowserHandle )
{
_GoForward( Self, unBrowserHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_AddHeader", CallingConvention = Platform.CC)]
private static extern void _AddHeader( IntPtr self, HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValue );
#endregion
internal void AddHeader( HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValue )
{
_AddHeader( Self, unBrowserHandle, pchKey, pchValue );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_ExecuteJavascript", CallingConvention = Platform.CC)]
private static extern void _ExecuteJavascript( IntPtr self, HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchScript );
#endregion
internal void ExecuteJavascript( HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchScript )
{
_ExecuteJavascript( Self, unBrowserHandle, pchScript );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_MouseUp", CallingConvention = Platform.CC)]
private static extern void _MouseUp( IntPtr self, HHTMLBrowser unBrowserHandle, IntPtr eMouseButton );
#endregion
internal void MouseUp( HHTMLBrowser unBrowserHandle, IntPtr eMouseButton )
{
_MouseUp( Self, unBrowserHandle, eMouseButton );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_MouseDown", CallingConvention = Platform.CC)]
private static extern void _MouseDown( IntPtr self, HHTMLBrowser unBrowserHandle, IntPtr eMouseButton );
#endregion
internal void MouseDown( HHTMLBrowser unBrowserHandle, IntPtr eMouseButton )
{
_MouseDown( Self, unBrowserHandle, eMouseButton );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_MouseDoubleClick", CallingConvention = Platform.CC)]
private static extern void _MouseDoubleClick( IntPtr self, HHTMLBrowser unBrowserHandle, IntPtr eMouseButton );
#endregion
internal void MouseDoubleClick( HHTMLBrowser unBrowserHandle, IntPtr eMouseButton )
{
_MouseDoubleClick( Self, unBrowserHandle, eMouseButton );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_MouseMove", CallingConvention = Platform.CC)]
private static extern void _MouseMove( IntPtr self, HHTMLBrowser unBrowserHandle, int x, int y );
#endregion
internal void MouseMove( HHTMLBrowser unBrowserHandle, int x, int y )
{
_MouseMove( Self, unBrowserHandle, x, y );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_MouseWheel", CallingConvention = Platform.CC)]
private static extern void _MouseWheel( IntPtr self, HHTMLBrowser unBrowserHandle, int nDelta );
#endregion
internal void MouseWheel( HHTMLBrowser unBrowserHandle, int nDelta )
{
_MouseWheel( Self, unBrowserHandle, nDelta );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_KeyDown", CallingConvention = Platform.CC)]
private static extern void _KeyDown( IntPtr self, HHTMLBrowser unBrowserHandle, uint nNativeKeyCode, IntPtr eHTMLKeyModifiers, [MarshalAs( UnmanagedType.U1 )] bool bIsSystemKey );
#endregion
internal void KeyDown( HHTMLBrowser unBrowserHandle, uint nNativeKeyCode, IntPtr eHTMLKeyModifiers, [MarshalAs( UnmanagedType.U1 )] bool bIsSystemKey )
{
_KeyDown( Self, unBrowserHandle, nNativeKeyCode, eHTMLKeyModifiers, bIsSystemKey );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_KeyUp", CallingConvention = Platform.CC)]
private static extern void _KeyUp( IntPtr self, HHTMLBrowser unBrowserHandle, uint nNativeKeyCode, IntPtr eHTMLKeyModifiers );
#endregion
internal void KeyUp( HHTMLBrowser unBrowserHandle, uint nNativeKeyCode, IntPtr eHTMLKeyModifiers )
{
_KeyUp( Self, unBrowserHandle, nNativeKeyCode, eHTMLKeyModifiers );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_KeyChar", CallingConvention = Platform.CC)]
private static extern void _KeyChar( IntPtr self, HHTMLBrowser unBrowserHandle, uint cUnicodeChar, IntPtr eHTMLKeyModifiers );
#endregion
internal void KeyChar( HHTMLBrowser unBrowserHandle, uint cUnicodeChar, IntPtr eHTMLKeyModifiers )
{
_KeyChar( Self, unBrowserHandle, cUnicodeChar, eHTMLKeyModifiers );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_SetHorizontalScroll", CallingConvention = Platform.CC)]
private static extern void _SetHorizontalScroll( IntPtr self, HHTMLBrowser unBrowserHandle, uint nAbsolutePixelScroll );
#endregion
internal void SetHorizontalScroll( HHTMLBrowser unBrowserHandle, uint nAbsolutePixelScroll )
{
_SetHorizontalScroll( Self, unBrowserHandle, nAbsolutePixelScroll );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_SetVerticalScroll", CallingConvention = Platform.CC)]
private static extern void _SetVerticalScroll( IntPtr self, HHTMLBrowser unBrowserHandle, uint nAbsolutePixelScroll );
#endregion
internal void SetVerticalScroll( HHTMLBrowser unBrowserHandle, uint nAbsolutePixelScroll )
{
_SetVerticalScroll( Self, unBrowserHandle, nAbsolutePixelScroll );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_SetKeyFocus", CallingConvention = Platform.CC)]
private static extern void _SetKeyFocus( IntPtr self, HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.U1 )] bool bHasKeyFocus );
#endregion
internal void SetKeyFocus( HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.U1 )] bool bHasKeyFocus )
{
_SetKeyFocus( Self, unBrowserHandle, bHasKeyFocus );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_ViewSource", CallingConvention = Platform.CC)]
private static extern void _ViewSource( IntPtr self, HHTMLBrowser unBrowserHandle );
#endregion
internal void ViewSource( HHTMLBrowser unBrowserHandle )
{
_ViewSource( Self, unBrowserHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_CopyToClipboard", CallingConvention = Platform.CC)]
private static extern void _CopyToClipboard( IntPtr self, HHTMLBrowser unBrowserHandle );
#endregion
internal void CopyToClipboard( HHTMLBrowser unBrowserHandle )
{
_CopyToClipboard( Self, unBrowserHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_PasteFromClipboard", CallingConvention = Platform.CC)]
private static extern void _PasteFromClipboard( IntPtr self, HHTMLBrowser unBrowserHandle );
#endregion
internal void PasteFromClipboard( HHTMLBrowser unBrowserHandle )
{
_PasteFromClipboard( Self, unBrowserHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_Find", CallingConvention = Platform.CC)]
private static extern void _Find( IntPtr self, HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchSearchStr, [MarshalAs( UnmanagedType.U1 )] bool bCurrentlyInFind, [MarshalAs( UnmanagedType.U1 )] bool bReverse );
#endregion
internal void Find( HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchSearchStr, [MarshalAs( UnmanagedType.U1 )] bool bCurrentlyInFind, [MarshalAs( UnmanagedType.U1 )] bool bReverse )
{
_Find( Self, unBrowserHandle, pchSearchStr, bCurrentlyInFind, bReverse );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_StopFind", CallingConvention = Platform.CC)]
private static extern void _StopFind( IntPtr self, HHTMLBrowser unBrowserHandle );
#endregion
internal void StopFind( HHTMLBrowser unBrowserHandle )
{
_StopFind( Self, unBrowserHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_GetLinkAtPosition", CallingConvention = Platform.CC)]
private static extern void _GetLinkAtPosition( IntPtr self, HHTMLBrowser unBrowserHandle, int x, int y );
#endregion
internal void GetLinkAtPosition( HHTMLBrowser unBrowserHandle, int x, int y )
{
_GetLinkAtPosition( Self, unBrowserHandle, x, y );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_SetCookie", CallingConvention = Platform.CC)]
private static extern void _SetCookie( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchHostname, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValue, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchPath, RTime32 nExpires, [MarshalAs( UnmanagedType.U1 )] bool bSecure, [MarshalAs( UnmanagedType.U1 )] bool bHTTPOnly );
#endregion
internal void SetCookie( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchHostname, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchKey, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchValue, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchPath, RTime32 nExpires, [MarshalAs( UnmanagedType.U1 )] bool bSecure, [MarshalAs( UnmanagedType.U1 )] bool bHTTPOnly )
{
_SetCookie( Self, pchHostname, pchKey, pchValue, pchPath, nExpires, bSecure, bHTTPOnly );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_SetPageScaleFactor", CallingConvention = Platform.CC)]
private static extern void _SetPageScaleFactor( IntPtr self, HHTMLBrowser unBrowserHandle, float flZoom, int nPointX, int nPointY );
#endregion
internal void SetPageScaleFactor( HHTMLBrowser unBrowserHandle, float flZoom, int nPointX, int nPointY )
{
_SetPageScaleFactor( Self, unBrowserHandle, flZoom, nPointX, nPointY );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_SetBackgroundMode", CallingConvention = Platform.CC)]
private static extern void _SetBackgroundMode( IntPtr self, HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.U1 )] bool bBackgroundMode );
#endregion
internal void SetBackgroundMode( HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.U1 )] bool bBackgroundMode )
{
_SetBackgroundMode( Self, unBrowserHandle, bBackgroundMode );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_SetDPIScalingFactor", CallingConvention = Platform.CC)]
private static extern void _SetDPIScalingFactor( IntPtr self, HHTMLBrowser unBrowserHandle, float flDPIScaling );
#endregion
internal void SetDPIScalingFactor( HHTMLBrowser unBrowserHandle, float flDPIScaling )
{
_SetDPIScalingFactor( Self, unBrowserHandle, flDPIScaling );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_OpenDeveloperTools", CallingConvention = Platform.CC)]
private static extern void _OpenDeveloperTools( IntPtr self, HHTMLBrowser unBrowserHandle );
#endregion
internal void OpenDeveloperTools( HHTMLBrowser unBrowserHandle )
{
_OpenDeveloperTools( Self, unBrowserHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_AllowStartRequest", CallingConvention = Platform.CC)]
private static extern void _AllowStartRequest( IntPtr self, HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.U1 )] bool bAllowed );
#endregion
internal void AllowStartRequest( HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.U1 )] bool bAllowed )
{
_AllowStartRequest( Self, unBrowserHandle, bAllowed );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_JSDialogResponse", CallingConvention = Platform.CC)]
private static extern void _JSDialogResponse( IntPtr self, HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.U1 )] bool bResult );
#endregion
internal void JSDialogResponse( HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.U1 )] bool bResult )
{
_JSDialogResponse( Self, unBrowserHandle, bResult );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamHTMLSurface_FileLoadDialogResponse", CallingConvention = Platform.CC)]
private static extern void _FileLoadDialogResponse( IntPtr self, HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchSelectedFiles );
#endregion
internal void FileLoadDialogResponse( HHTMLBrowser unBrowserHandle, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchSelectedFiles )
{
_FileLoadDialogResponse( Self, unBrowserHandle, pchSelectedFiles );
}
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using System;
using System.Collections.Generic;
using PlayFab.SharedModels;
namespace PlayFab.ProfilesModels
{
public enum EffectType
{
Allow,
Deny
}
/// <summary>
/// An entity object and its associated meta data.
/// </summary>
[Serializable]
public class EntityDataObject
{
/// <summary>
/// Un-escaped JSON object, if DataAsObject is true.
/// </summary>
public object DataObject;
/// <summary>
/// Escaped string JSON body of the object, if DataAsObject is default or false.
/// </summary>
public string EscapedDataObject;
/// <summary>
/// Name of this object.
/// </summary>
public string ObjectName;
}
/// <summary>
/// Combined entity type and ID structure which uniquely identifies a single entity.
/// </summary>
[Serializable]
public class EntityKey
{
/// <summary>
/// Unique ID of the entity.
/// </summary>
public string Id;
/// <summary>
/// Entity type. See https://api.playfab.com/docs/tutorials/entities/entitytypes
/// </summary>
public string Type;
}
[Serializable]
public class EntityLineage
{
/// <summary>
/// The Character Id of the associated entity.
/// </summary>
public string CharacterId;
/// <summary>
/// The Group Id of the associated entity.
/// </summary>
public string GroupId;
/// <summary>
/// The Master Player Account Id of the associated entity.
/// </summary>
public string MasterPlayerAccountId;
/// <summary>
/// The Namespace Id of the associated entity.
/// </summary>
public string NamespaceId;
/// <summary>
/// The Title Id of the associated entity.
/// </summary>
public string TitleId;
/// <summary>
/// The Title Player Account Id of the associated entity.
/// </summary>
public string TitlePlayerAccountId;
}
[Serializable]
public class EntityPermissionStatement
{
/// <summary>
/// The action this statement effects. May be 'Read', 'Write' or '*' for both read and write.
/// </summary>
public string Action;
/// <summary>
/// A comment about the statement. Intended solely for bookkeeping and debugging.
/// </summary>
public string Comment;
/// <summary>
/// Additional conditions to be applied for entity resources.
/// </summary>
public object Condition;
/// <summary>
/// The effect this statement will have. It may be either Allow or Deny
/// </summary>
public EffectType Effect;
/// <summary>
/// The principal this statement will effect.
/// </summary>
public object Principal;
/// <summary>
/// The resource this statements effects. Similar to 'pfrn:data--title![Title ID]/Profile/*'
/// </summary>
public string Resource;
}
[Serializable]
public class EntityProfileBody
{
/// <summary>
/// The entity id and type.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The chain of responsibility for this entity. Use Lineage.
/// </summary>
public string EntityChain;
/// <summary>
/// The files on this profile.
/// </summary>
public Dictionary<string,EntityProfileFileMetadata> Files;
/// <summary>
/// The friendly name of the entity. This field may serve different purposes for different entity types. i.e.: for a title
/// player account it could represent the display name of the player, whereas on a character it could be character's name.
/// </summary>
public string FriendlyName;
/// <summary>
/// The language on this profile.
/// </summary>
public string Language;
/// <summary>
/// The lineage of this profile.
/// </summary>
public EntityLineage Lineage;
/// <summary>
/// The objects on this profile.
/// </summary>
public Dictionary<string,EntityDataObject> Objects;
/// <summary>
/// The permissions that govern access to this entity profile and its properties. Only includes permissions set on this
/// profile, not global statements from titles and namespaces.
/// </summary>
public List<EntityPermissionStatement> Permissions;
/// <summary>
/// The version number of the profile in persistent storage at the time of the read. Used for optional optimistic
/// concurrency during update.
/// </summary>
public int VersionNumber;
}
/// <summary>
/// An entity file's meta data. To get a download URL call File/GetFiles API.
/// </summary>
[Serializable]
public class EntityProfileFileMetadata
{
/// <summary>
/// Checksum value for the file
/// </summary>
public string Checksum;
/// <summary>
/// Name of the file
/// </summary>
public string FileName;
/// <summary>
/// Last UTC time the file was modified
/// </summary>
public DateTime LastModified;
/// <summary>
/// Storage service's reported byte count
/// </summary>
public int Size;
}
/// <summary>
/// Given an entity type and entity identifier will retrieve the profile from the entity store. If the profile being
/// retrieved is the caller's, then the read operation is consistent, if not it is an inconsistent read. An inconsistent
/// read means that we do not guarantee all committed writes have occurred before reading the profile, allowing for a stale
/// read. If consistency is important the Version Number on the result can be used to compare which version of the profile
/// any reader has.
/// </summary>
[Serializable]
public class GetEntityProfileRequest : PlayFabRequestCommon
{
/// <summary>
/// Determines whether the objects will be returned as an escaped JSON string or as a un-escaped JSON object. Default is
/// JSON string.
/// </summary>
public bool? DataAsObject;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
}
[Serializable]
public class GetEntityProfileResponse : PlayFabResultCommon
{
/// <summary>
/// Entity profile
/// </summary>
public EntityProfileBody Profile;
}
/// <summary>
/// Given a set of entity types and entity identifiers will retrieve all readable profiles properties for the caller.
/// Profiles that the caller is not allowed to read will silently not be included in the results.
/// </summary>
[Serializable]
public class GetEntityProfilesRequest : PlayFabRequestCommon
{
/// <summary>
/// Determines whether the objects will be returned as an escaped JSON string or as a un-escaped JSON object. Default is
/// JSON string.
/// </summary>
public bool? DataAsObject;
/// <summary>
/// Entity keys of the profiles to load. Must be between 1 and 25
/// </summary>
public List<EntityKey> Entities;
}
[Serializable]
public class GetEntityProfilesResponse : PlayFabResultCommon
{
/// <summary>
/// Entity profiles
/// </summary>
public List<EntityProfileBody> Profiles;
}
/// <summary>
/// Retrieves the title access policy that is used before the profile's policy is inspected during a request. If never
/// customized this will return the default starter policy built by PlayFab.
/// </summary>
[Serializable]
public class GetGlobalPolicyRequest : PlayFabRequestCommon
{
}
[Serializable]
public class GetGlobalPolicyResponse : PlayFabResultCommon
{
/// <summary>
/// The permissions that govern access to all entities under this title or namespace.
/// </summary>
public List<EntityPermissionStatement> Permissions;
}
public enum OperationTypes
{
Created,
Updated,
Deleted,
None
}
/// <summary>
/// This will set the access policy statements on the given entity profile. This is not additive, any existing statements
/// will be replaced with the statements in this request.
/// </summary>
[Serializable]
public class SetEntityProfilePolicyRequest : PlayFabRequestCommon
{
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The statements to include in the access policy.
/// </summary>
public List<EntityPermissionStatement> Statements;
}
[Serializable]
public class SetEntityProfilePolicyResponse : PlayFabResultCommon
{
/// <summary>
/// The permissions that govern access to this entity profile and its properties. Only includes permissions set on this
/// profile, not global statements from titles and namespaces.
/// </summary>
public List<EntityPermissionStatement> Permissions;
}
/// <summary>
/// Updates the title access policy that is used before the profile's policy is inspected during a request. Policies are
/// compiled and cached for several minutes so an update here may not be reflected in behavior for a short time.
/// </summary>
[Serializable]
public class SetGlobalPolicyRequest : PlayFabRequestCommon
{
/// <summary>
/// The permissions that govern access to all entities under this title or namespace.
/// </summary>
public List<EntityPermissionStatement> Permissions;
}
[Serializable]
public class SetGlobalPolicyResponse : PlayFabResultCommon
{
}
/// <summary>
/// Given an entity profile, will update its language to the one passed in if the profile's version is at least the one
/// passed in.
/// </summary>
[Serializable]
public class SetProfileLanguageRequest : PlayFabRequestCommon
{
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The expected version of a profile to perform this update on
/// </summary>
public int ExpectedVersion;
/// <summary>
/// The language to set on the given entity. Deletes the profile's language if passed in a null string.
/// </summary>
public string Language;
}
[Serializable]
public class SetProfileLanguageResponse : PlayFabResultCommon
{
/// <summary>
/// The type of operation that occured on the profile's language
/// </summary>
public OperationTypes? OperationResult;
/// <summary>
/// The updated version of the profile after the language update
/// </summary>
public int? VersionNumber;
}
}
#endif
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using Internal.Cryptography;
using Internal.Cryptography.Pal;
namespace System.Security.Cryptography.X509Certificates
{
public class X509Certificate2 : X509Certificate
{
public X509Certificate2()
: base()
{
}
public X509Certificate2(byte[] rawData)
: base(rawData)
{
}
public X509Certificate2(byte[] rawData, String password)
: base(rawData, password)
{
}
public X509Certificate2(byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
: base(rawData, password, keyStorageFlags)
{
}
public X509Certificate2(IntPtr handle)
: base(handle)
{
}
internal X509Certificate2(ICertificatePal pal)
: base(pal)
{
}
public X509Certificate2(String fileName)
: base(fileName)
{
}
public X509Certificate2(String fileName, String password)
: base(fileName, password)
{
}
public X509Certificate2(String fileName, String password, X509KeyStorageFlags keyStorageFlags)
: base(fileName, password, keyStorageFlags)
{
}
public bool Archived
{
get
{
ThrowIfInvalid();
return Pal.Archived;
}
set
{
ThrowIfInvalid();
Pal.Archived = value;
}
}
public X509ExtensionCollection Extensions
{
get
{
ThrowIfInvalid();
X509ExtensionCollection extensions = _lazyExtensions;
if (extensions == null)
{
extensions = new X509ExtensionCollection();
foreach (X509Extension extension in Pal.Extensions)
{
X509Extension customExtension = CreateCustomExtensionIfAny(extension.Oid);
if (customExtension == null)
{
extensions.Add(extension);
}
else
{
customExtension.CopyFrom(extension);
extensions.Add(customExtension);
}
}
_lazyExtensions = extensions;
}
return extensions;
}
}
public String FriendlyName
{
get
{
ThrowIfInvalid();
return Pal.FriendlyName;
}
set
{
ThrowIfInvalid();
Pal.FriendlyName = value;
}
}
public bool HasPrivateKey
{
get
{
ThrowIfInvalid();
return Pal.HasPrivateKey;
}
}
public X500DistinguishedName IssuerName
{
get
{
ThrowIfInvalid();
X500DistinguishedName issuerName = _lazyIssuer;
if (issuerName == null)
issuerName = _lazyIssuer = Pal.IssuerName;
return issuerName;
}
}
public DateTime NotAfter
{
get { return GetNotAfter(); }
}
public DateTime NotBefore
{
get { return GetNotBefore(); }
}
public PublicKey PublicKey
{
get
{
ThrowIfInvalid();
PublicKey publicKey = _lazyPublicKey;
if (publicKey == null)
{
String keyAlgorithmOid = GetKeyAlgorithm();
byte[] parameters = GetKeyAlgorithmParameters();
byte[] keyValue = GetPublicKey();
Oid oid = new Oid(keyAlgorithmOid);
publicKey = _lazyPublicKey = new PublicKey(oid, new AsnEncodedData(oid, parameters), new AsnEncodedData(oid, keyValue));
}
return publicKey;
}
}
public byte[] RawData
{
get
{
ThrowIfInvalid();
byte[] rawData = _lazyRawData;
if (rawData == null)
{
rawData = _lazyRawData = Pal.RawData;
}
return rawData.CloneByteArray();
}
}
public String SerialNumber
{
get
{
byte[] serialNumber = GetSerialNumber();
Array.Reverse(serialNumber);
return serialNumber.ToHexStringUpper();
}
}
public Oid SignatureAlgorithm
{
get
{
ThrowIfInvalid();
Oid signatureAlgorithm = _lazySignatureAlgorithm;
if (signatureAlgorithm == null)
{
String oidValue = Pal.SignatureAlgorithm;
signatureAlgorithm = _lazySignatureAlgorithm = Oid.FromOidValue(oidValue, OidGroup.SignatureAlgorithm);
}
return signatureAlgorithm;
}
}
public X500DistinguishedName SubjectName
{
get
{
ThrowIfInvalid();
X500DistinguishedName subjectName = _lazySubjectName;
if (subjectName == null)
subjectName = _lazySubjectName = Pal.SubjectName;
return subjectName;
}
}
public String Thumbprint
{
get
{
byte[] thumbPrint = GetCertHash();
return thumbPrint.ToHexStringUpper();
}
}
public int Version
{
get
{
ThrowIfInvalid();
int version = _lazyVersion;
if (version == 0)
version = _lazyVersion = Pal.Version;
return version;
}
}
public static X509ContentType GetCertContentType(byte[] rawData)
{
if (rawData == null || rawData.Length == 0)
throw new ArgumentException(SR.Arg_EmptyOrNullArray, "rawData");
return X509Pal.Instance.GetCertContentType(rawData);
}
public static X509ContentType GetCertContentType(String fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
// Desktop compat: The desktop CLR expands the filename to a full path for the purpose of performing a CAS permission check. While CAS is not present here,
// we still need to call GetFullPath() so we get the same exception behavior if the fileName is bad.
String fullPath = Path.GetFullPath(fileName);
return X509Pal.Instance.GetCertContentType(fileName);
}
public String GetNameInfo(X509NameType nameType, bool forIssuer)
{
return Pal.GetNameInfo(nameType, forIssuer);
}
public override String ToString()
{
return base.ToString(fVerbose: true);
}
public override String ToString(bool verbose)
{
if (verbose == false || Pal == null)
return ToString();
StringBuilder sb = new StringBuilder();
// Version
sb.AppendLine("[Version]");
sb.Append(" V");
sb.Append(Version);
// Subject
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Subject]");
sb.Append(" ");
sb.Append(SubjectName.Name);
String simpleName = GetNameInfo(X509NameType.SimpleName, false);
if (simpleName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("Simple Name: ");
sb.Append(simpleName);
}
String emailName = GetNameInfo(X509NameType.EmailName, false);
if (emailName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("Email Name: ");
sb.Append(emailName);
}
String upnName = GetNameInfo(X509NameType.UpnName, false);
if (upnName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("UPN Name: ");
sb.Append(upnName);
}
String dnsName = GetNameInfo(X509NameType.DnsName, false);
if (dnsName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("DNS Name: ");
sb.Append(dnsName);
}
// Issuer
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Issuer]");
sb.Append(" ");
sb.Append(IssuerName.Name);
simpleName = GetNameInfo(X509NameType.SimpleName, true);
if (simpleName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("Simple Name: ");
sb.Append(simpleName);
}
emailName = GetNameInfo(X509NameType.EmailName, true);
if (emailName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("Email Name: ");
sb.Append(emailName);
}
upnName = GetNameInfo(X509NameType.UpnName, true);
if (upnName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("UPN Name: ");
sb.Append(upnName);
}
dnsName = GetNameInfo(X509NameType.DnsName, true);
if (dnsName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("DNS Name: ");
sb.Append(dnsName);
}
// Serial Number
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Serial Number]");
sb.Append(" ");
sb.AppendLine(SerialNumber);
// NotBefore
sb.AppendLine();
sb.AppendLine("[Not Before]");
sb.Append(" ");
sb.AppendLine(FormatDate(NotBefore));
// NotAfter
sb.AppendLine();
sb.AppendLine("[Not After]");
sb.Append(" ");
sb.AppendLine(FormatDate(NotAfter));
// Thumbprint
sb.AppendLine();
sb.AppendLine("[Thumbprint]");
sb.Append(" ");
sb.AppendLine(Thumbprint);
// Signature Algorithm
sb.AppendLine();
sb.AppendLine("[Signature Algorithm]");
sb.Append(" ");
sb.Append(SignatureAlgorithm.FriendlyName);
sb.Append('(');
sb.Append(SignatureAlgorithm.Value);
sb.AppendLine(")");
// Public Key
sb.AppendLine();
sb.Append("[Public Key]");
// It could throw if it's some user-defined CryptoServiceProvider
try
{
PublicKey pubKey = PublicKey;
sb.AppendLine();
sb.Append(" ");
sb.Append("Algorithm: ");
sb.Append(pubKey.Oid.FriendlyName);
// So far, we only support RSACryptoServiceProvider & DSACryptoServiceProvider Keys
try
{
sb.AppendLine();
sb.Append(" ");
sb.Append("Length: ");
using (RSA pubRsa = this.GetRSAPublicKey())
{
if (pubRsa != null)
{
sb.Append(pubRsa.KeySize);
}
}
}
catch (NotSupportedException)
{
}
sb.AppendLine();
sb.Append(" ");
sb.Append("Key Blob: ");
sb.AppendLine(pubKey.EncodedKeyValue.Format(true));
sb.Append(" ");
sb.Append("Parameters: ");
sb.Append(pubKey.EncodedParameters.Format(true));
}
catch (CryptographicException)
{
}
// Private key
Pal.AppendPrivateKeyInfo(sb);
// Extensions
X509ExtensionCollection extensions = Extensions;
if (extensions.Count > 0)
{
sb.AppendLine();
sb.AppendLine();
sb.Append("[Extensions]");
foreach (X509Extension extension in extensions)
{
try
{
sb.AppendLine();
sb.Append("* ");
sb.Append(extension.Oid.FriendlyName);
sb.Append('(');
sb.Append(extension.Oid.Value);
sb.Append("):");
sb.AppendLine();
sb.Append(" ");
sb.Append(extension.Format(true));
}
catch (CryptographicException)
{
}
}
}
sb.AppendLine();
return sb.ToString();
}
private static X509Extension CreateCustomExtensionIfAny(Oid oid)
{
string oidValue = oid.Value;
switch (oidValue)
{
case Oids.BasicConstraints:
return X509Pal.Instance.SupportsLegacyBasicConstraintsExtension ?
new X509BasicConstraintsExtension() :
null;
case Oids.BasicConstraints2:
return new X509BasicConstraintsExtension();
case Oids.KeyUsage:
return new X509KeyUsageExtension();
case Oids.EnhancedKeyUsage:
return new X509EnhancedKeyUsageExtension();
case Oids.SubjectKeyIdentifier:
return new X509SubjectKeyIdentifierExtension();
default:
return null;
}
}
private volatile byte[] _lazyRawData;
private volatile Oid _lazySignatureAlgorithm;
private volatile int _lazyVersion;
private volatile X500DistinguishedName _lazySubjectName;
private volatile X500DistinguishedName _lazyIssuer;
private volatile PublicKey _lazyPublicKey;
private volatile X509ExtensionCollection _lazyExtensions;
}
}
| |
//*****************************************************************************
//
// Project: libgeotiff
// Purpose: Code to abstract translation between pixel/line and PCS
// coordinates.
// Author: Frank Warmerdam, warmerda@home.com
//
//*****************************************************************************
// Copyright (c) 1999, Frank Warmerdam
// Copyright (c) 2008 by the Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//*****************************************************************************
using System;
using System.Collections.Generic;
using System.Text;
using Free.Ports.LibTiff;
namespace Free.Ports.LibGeoTiff
{
public static partial class libgeotiff
{
//***********************************************************************/
//* inv_geotransform() */
//* */
//* Invert a 6 term geotransform style matrix. */
//***********************************************************************/
static bool inv_geotransform(double[] gt_in, double[] gt_out)
{
// we assume a 3rd row that is [0 0 1]
// Compute determinate
double det=gt_in[0]*gt_in[4]-gt_in[1]*gt_in[3];
if(Math.Abs(det)<0.000000000000001) return false;
double inv_det=1.0/det;
// compute adjoint, and devide by determinate
gt_out[0]=gt_in[4]*inv_det;
gt_out[3]=-gt_in[3]*inv_det;
gt_out[1]=-gt_in[1]*inv_det;
gt_out[4]=gt_in[0]*inv_det;
gt_out[2]=(gt_in[1]*gt_in[5]-gt_in[2]*gt_in[4])*inv_det;
gt_out[5]=(-gt_in[0]*gt_in[5]+gt_in[2]*gt_in[3])*inv_det;
return true;
}
//***********************************************************************/
//* GTIFTiepointTranslate() */
//***********************************************************************/
static bool GTIFTiepointTranslate(int gcp_count, double[] gcps_in, int in_offset, double[] gcps_out, int out_offset, ref double x, ref double y)
{
// I would appreciate a _brief_ block of code for doing second order polynomial regression here!
return false;
}
//***********************************************************************/
//* GTIFImageToPCS() */
//***********************************************************************/
// Translate a pixel/line coordinate to projection coordinates.
//
// At this time this function does not support image to PCS translations for
// tiepoints-only definitions, only pixelscale and transformation matrix
// formulations.
//
// @param gtif The handle from GTIFNew() indicating the target file.
// @param x A reference to the double containing the pixel offset on input,
// and into which the easting/longitude will be put on completion.
// @param y A reference to the double containing the line offset on input,
// and into which the northing/latitude will be put on completion.
//
// @return true if the transformation succeeds, or false if it fails. It may
// fail if the file doesn't have properly setup transformation information,
// or it is in a form unsupported by this function.
public static bool GTIFImageToPCS(GTIF gtif, ref double x, ref double y)
{
bool res=false;
int tiepoint_count, count, transform_count;
TIFF tif=gtif.gt_tif;
double[] tiepoints=null;
double[] pixel_scale=null;
double[] transform=null;
// --------------------------------------------------------------------
// Fetch tiepoints and pixel scale.
// --------------------------------------------------------------------
object ap;
if(!gtif.gt_methods.get(tif, (ushort)GTIFF_TIEPOINTS, out tiepoint_count, out ap)) tiepoint_count=0;
else if(ap is double[]) tiepoints=(double[])ap;
if(!gtif.gt_methods.get(tif, (ushort)GTIFF_PIXELSCALE, out count, out ap)) count=0;
else if(ap is double[]) pixel_scale=(double[])ap;
if(!gtif.gt_methods.get(tif, (ushort)GTIFF_TRANSMATRIX, out transform_count, out ap)) transform_count=0;
else if(ap is double[]) transform=(double[])ap;
// --------------------------------------------------------------------
// If we have a transformation matrix, use it.
// --------------------------------------------------------------------
if(transform_count==16)
{
double x_in=x, y_in=y;
x=x_in*transform[0]+y_in*transform[1]+transform[3];
y=x_in*transform[4]+y_in*transform[5]+transform[7];
res=true;
}
// --------------------------------------------------------------------
// If the pixelscale count is zero, but we have tiepoints use
// the tiepoint based approach.
// --------------------------------------------------------------------
else if(tiepoint_count>6&&count==0)
{
res=GTIFTiepointTranslate(tiepoint_count/6, tiepoints, 0, tiepoints, 3, ref x, ref y);
}
// --------------------------------------------------------------------
// For now we require one tie point, and a valid pixel scale.
// --------------------------------------------------------------------
else if(count>=3&&tiepoint_count>=6)
{
x=(x-tiepoints[0])*pixel_scale[0]+tiepoints[3];
y=(y-tiepoints[1])*(-1*pixel_scale[1])+tiepoints[4];
res=true;
}
return res;
}
//***********************************************************************/
//* GTIFPCSToImage() */
//***********************************************************************/
// Translate a projection coordinate to pixel/line coordinates.
//
// At this time this function does not support PCS to image translations for
// tiepoints-only based definitions, only matrix and pixelscale/tiepoints
// formulations are supposed.
//
// @param gtif The handle from GTIFNew() indicating the target file.
// @param x A reference to the double containing the pixel offset on input,
// and into which the easting/longitude will be put on completion.
// @param y A reference to the double containing the line offset on input,
// and into which the northing/latitude will be put on completion.
//
// @return true if the transformation succeeds, or false if it fails. It may
// fail if the file doesn't have properly setup transformation information,
// or it is in a form unsupported by this function.
public static bool GTIFPCSToImage(GTIF gtif, ref double x, ref double y)
{
bool result=false;
int tiepoint_count, count, transform_count;
TIFF tif=gtif.gt_tif;
double[] tiepoints=null;
double[] pixel_scale=null;
double[] transform=null;
// --------------------------------------------------------------------
// Fetch tiepoints and pixel scale.
// --------------------------------------------------------------------
object ap;
if(!gtif.gt_methods.get(tif, (ushort)GTIFF_TIEPOINTS, out tiepoint_count, out ap)) tiepoint_count=0;
else if(ap is double[]) tiepoints=(double[])ap;
if(!gtif.gt_methods.get(tif, (ushort)GTIFF_PIXELSCALE, out count, out ap)) count=0;
else if(ap is double[]) pixel_scale=(double[])ap;
if(!gtif.gt_methods.get(tif, (ushort)GTIFF_TRANSMATRIX, out transform_count, out ap)) transform_count=0;
else if(ap is double[]) transform=(double[])ap;
// --------------------------------------------------------------------
// Handle matrix - convert to "geotransform" format, invert and
// apply.
// --------------------------------------------------------------------
if(transform_count==16)
{
double x_in=x, y_in=y;
double[] gt_in=new double[6];
double[] gt_out=new double[6];
gt_in[0]=transform[0];
gt_in[1]=transform[1];
gt_in[2]=transform[3];
gt_in[3]=transform[4];
gt_in[4]=transform[5];
gt_in[5]=transform[7];
if(!inv_geotransform(gt_in, gt_out)) result=false;
else
{
x=x_in*gt_out[0]+y_in*gt_out[1]+gt_out[2];
y=x_in*gt_out[3]+y_in*gt_out[4]+gt_out[5];
result=true;
}
}
// --------------------------------------------------------------------
// If the pixelscale count is zero, but we have tiepoints use
// the tiepoint based approach.
// --------------------------------------------------------------------
else if(tiepoint_count>6&&count==0)
{
result=GTIFTiepointTranslate(tiepoint_count/6, tiepoints, 3, tiepoints, 0, ref x, ref y);
}
// --------------------------------------------------------------------
// For now we require one tie point, and a valid pixel scale.
// --------------------------------------------------------------------
else if(count>=3&&tiepoint_count>=6)
{
x=(x-tiepoints[3])/pixel_scale[0]+tiepoints[0];
y=(y-tiepoints[4])/(-1*pixel_scale[1])+tiepoints[1];
result=true;
}
return result;
}
}
}
| |
//-----------------------------------------------------------------------------
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Cci.Immutable;
using Microsoft.Cci.MetadataReader.ObjectModelImplementation;
using Microsoft.Cci.MetadataReader.PEFileFlags;
using Microsoft.Cci.UtilityDataStructures;
namespace Microsoft.Cci.MetadataReader.ObjectModelImplementation {
internal abstract class ExpressionBase : IMetadataExpression {
internal abstract ITypeReference/*?*/ ModuleTypeReference { get; }
#region IExpression Members
public IEnumerable<ILocation> Locations {
get { return Enumerable<ILocation>.Empty; }
}
public ITypeReference Type {
get { return this.ModuleTypeReference; }
}
/// <summary>
/// Calls the visitor.Visit(T) method where T is the most derived object model node interface type implemented by the concrete type
/// of the object implementing IDoubleDispatcher. The dispatch method does not invoke Dispatch on any child objects. If child traversal
/// is desired, the implementations of the Visit methods should do the subsequent dispatching.
/// </summary>
public abstract void Dispatch(IMetadataVisitor visitor);
#endregion
}
internal sealed class ConstantExpression : ExpressionBase, IMetadataConstant {
readonly ITypeReference TypeReference;
internal object/*?*/ value;
internal ConstantExpression(
ITypeReference typeReference,
object/*?*/ value
) {
this.TypeReference = typeReference;
this.value = value;
}
internal override ITypeReference/*?*/ ModuleTypeReference {
get { return this.TypeReference; }
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
#region ICompileTimeConstant Members
public object/*?*/ Value {
get { return this.value; }
}
#endregion
}
internal sealed class ArrayExpression : ExpressionBase, IMetadataCreateArray {
internal readonly IArrayTypeReference VectorType;
internal readonly EnumerableArrayWrapper<ExpressionBase, IMetadataExpression> Elements;
internal ArrayExpression(
IArrayTypeReference vectorType,
EnumerableArrayWrapper<ExpressionBase, IMetadataExpression> elements
) {
this.VectorType = vectorType;
this.Elements = elements;
}
internal override ITypeReference/*?*/ ModuleTypeReference {
get { return this.VectorType; }
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
#region IArrayCreate Members
public ITypeReference ElementType {
get {
ITypeReference/*?*/ moduleTypeRef = this.VectorType.ElementType;
if (moduleTypeRef == null)
return Dummy.TypeReference;
return moduleTypeRef;
}
}
public IEnumerable<IMetadataExpression> Initializers {
get { return this.Elements; }
}
public IEnumerable<int> LowerBounds {
get { return IteratorHelper.GetSingletonEnumerable<int>(0); }
}
public uint Rank {
get { return 1; }
}
public IEnumerable<ulong> Sizes {
get { return IteratorHelper.GetSingletonEnumerable<ulong>((ulong)this.Elements.RawArray.Length); }
}
#endregion
}
internal sealed class TypeOfExpression : ExpressionBase, IMetadataTypeOf {
readonly PEFileToObjectModel PEFileToObjectModel;
readonly ITypeReference/*?*/ TypeExpression;
internal TypeOfExpression(
PEFileToObjectModel peFileToObjectModel,
ITypeReference/*?*/ typeExpression
) {
this.PEFileToObjectModel = peFileToObjectModel;
this.TypeExpression = typeExpression;
}
internal override ITypeReference/*?*/ ModuleTypeReference {
get { return this.PEFileToObjectModel.PlatformType.SystemType; }
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
#region ITypeOf Members
public ITypeReference TypeToGet {
get {
if (this.TypeExpression == null) return Dummy.TypeReference;
return this.TypeExpression;
}
}
#endregion
}
internal sealed class FieldOrPropertyNamedArgumentExpression : ExpressionBase, IMetadataNamedArgument {
const int IsFieldFlag = 0x01;
const int IsResolvedFlag = 0x02;
readonly IName Name;
readonly ITypeReference ContainingType;
int Flags;
readonly ITypeReference fieldOrPropTypeReference;
object/*?*/ resolvedFieldOrProperty;
internal readonly ExpressionBase ExpressionValue;
internal FieldOrPropertyNamedArgumentExpression(
IName name,
ITypeReference containingType,
bool isField,
ITypeReference fieldOrPropTypeReference,
ExpressionBase expressionValue
) {
this.Name = name;
this.ContainingType = containingType;
if (isField)
this.Flags |= FieldOrPropertyNamedArgumentExpression.IsFieldFlag;
this.fieldOrPropTypeReference = fieldOrPropTypeReference;
this.ExpressionValue = expressionValue;
}
public bool IsField {
get {
return (this.Flags & FieldOrPropertyNamedArgumentExpression.IsFieldFlag) == FieldOrPropertyNamedArgumentExpression.IsFieldFlag;
}
}
internal override ITypeReference/*?*/ ModuleTypeReference {
get { return this.fieldOrPropTypeReference; }
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
#region INamedArgument Members
public IName ArgumentName {
get { return this.Name; }
}
public IMetadataExpression ArgumentValue {
get { return this.ExpressionValue; }
}
public object/*?*/ ResolvedDefinition {
get {
if ((this.Flags & FieldOrPropertyNamedArgumentExpression.IsResolvedFlag) == 0) {
this.Flags |= FieldOrPropertyNamedArgumentExpression.IsResolvedFlag;
ITypeDefinition/*?*/ typeDef = this.ContainingType.ResolvedType;
if (this.IsField) {
foreach (ITypeDefinitionMember tdm in typeDef.GetMembersNamed(this.Name, false)) {
IFieldDefinition/*?*/ fd = tdm as IFieldDefinition;
if (fd == null)
continue;
ITypeReference/*?*/ fmtr = fd.Type as ITypeReference;
if (fmtr == null)
continue;
if (fmtr.InternedKey == this.fieldOrPropTypeReference.InternedKey) {
this.resolvedFieldOrProperty = fd;
break;
}
}
} else {
foreach (ITypeDefinitionMember tdm in typeDef.GetMembersNamed(this.Name, false)) {
IPropertyDefinition/*?*/ pd = tdm as IPropertyDefinition;
if (pd == null)
continue;
ITypeReference/*?*/ pmtr = pd.Type as ITypeReference;
if (pmtr == null)
continue;
if (pmtr.InternedKey == this.fieldOrPropTypeReference.InternedKey) {
this.resolvedFieldOrProperty = pd;
break;
}
}
}
}
return this.resolvedFieldOrProperty;
}
}
#endregion
}
internal sealed class CustomAttribute : MetadataObject, ICustomAttribute {
internal readonly IMethodReference Constructor;
internal readonly IMetadataExpression[]/*?*/ Arguments;
internal IMetadataNamedArgument[]/*?*/ NamedArguments;
internal readonly uint AttributeRowId;
internal CustomAttribute(PEFileToObjectModel peFileToObjectModel, uint attributeRowId, IMethodReference constructor,
IMetadataExpression[]/*?*/ arguments, IMetadataNamedArgument[]/*?*/ namedArguments)
: base(peFileToObjectModel) {
this.AttributeRowId = attributeRowId;
this.Constructor = constructor;
this.Arguments = arguments;
this.NamedArguments = namedArguments;
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
public override void DispatchAsReference(IMetadataVisitor visitor) {
throw new InvalidOperationException();
}
internal override uint TokenValue {
get { return TokenTypeIds.CustomAttribute | this.AttributeRowId; }
}
#region ICustomAttribute Members
IEnumerable<IMetadataExpression> ICustomAttribute.Arguments {
get { return IteratorHelper.GetReadonly(this.Arguments)??Enumerable<IMetadataExpression>.Empty; }
}
IMethodReference ICustomAttribute.Constructor {
get { return this.Constructor; }
}
IEnumerable<IMetadataNamedArgument> ICustomAttribute.NamedArguments {
get { return IteratorHelper.GetReadonly(this.NamedArguments)??Enumerable<IMetadataNamedArgument>.Empty; }
}
ushort ICustomAttribute.NumberOfNamedArguments {
get {
if (this.NamedArguments == null) return 0;
return (ushort)this.NamedArguments.Length;
}
}
public ITypeReference Type {
get {
ITypeReference/*?*/ moduleTypeRef = this.Constructor.ContainingType;
if (moduleTypeRef == null)
return Dummy.TypeReference;
return moduleTypeRef;
}
}
#endregion
}
internal sealed class SecurityCustomAttribute : ICustomAttribute {
internal readonly SecurityAttribute ContainingSecurityAttribute;
internal readonly IMethodReference ConstructorReference;
internal readonly IMetadataNamedArgument[]/*?*/ NamedArguments;
internal SecurityCustomAttribute(SecurityAttribute containingSecurityAttribute, IMethodReference constructorReference, IMetadataNamedArgument[]/*?*/ namedArguments) {
this.ContainingSecurityAttribute = containingSecurityAttribute;
this.ConstructorReference = constructorReference;
this.NamedArguments = namedArguments;
}
#region ICustomAttribute Members
IEnumerable<IMetadataExpression> ICustomAttribute.Arguments {
get { return Enumerable<IMetadataExpression>.Empty; }
}
public IMethodReference Constructor {
get { return this.ConstructorReference; }
}
IEnumerable<IMetadataNamedArgument> ICustomAttribute.NamedArguments {
get { return IteratorHelper.GetReadonly(this.NamedArguments)??Enumerable<IMetadataNamedArgument>.Empty; }
}
ushort ICustomAttribute.NumberOfNamedArguments {
get {
if (this.NamedArguments == null) return 0;
return (ushort)this.NamedArguments.Length;
}
}
public ITypeReference Type {
get { return this.ConstructorReference.ContainingType; }
}
#endregion
}
internal sealed class SecurityAttribute : MetadataObject, ISecurityAttribute {
internal readonly SecurityAction Action;
internal readonly uint DeclSecurityRowId;
internal SecurityAttribute(
PEFileToObjectModel peFileToObjectModel,
uint declSecurityRowId,
SecurityAction action
)
: base(peFileToObjectModel) {
this.DeclSecurityRowId = declSecurityRowId;
this.Action = action;
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
public override void DispatchAsReference(IMetadataVisitor visitor) {
throw new InvalidOperationException();
}
internal override uint TokenValue {
get { return TokenTypeIds.Permission | this.DeclSecurityRowId; }
}
protected override IEnumerable<ICustomAttribute> GetAttributes() {
return this.PEFileToObjectModel.GetSecurityAttributeData(this);
}
#region ISecurityAttribute Members
SecurityAction ISecurityAttribute.Action {
get { return this.Action; }
}
#endregion
}
internal sealed class NamespaceName {
internal readonly IName FullyQualifiedName;
internal readonly NamespaceName/*?*/ ParentNamespaceName;
internal readonly IName Name;
internal NamespaceName(
INameTable nameTable,
NamespaceName/*?*/ parentNamespaceName,
IName name
) {
this.ParentNamespaceName = parentNamespaceName;
this.Name = name;
if (parentNamespaceName == null)
this.FullyQualifiedName = name;
else
this.FullyQualifiedName = nameTable.GetNameFor(parentNamespaceName.FullyQualifiedName.Value + "." + name);
}
public override string ToString() {
return this.FullyQualifiedName.Value;
}
}
internal abstract class TypeName {
internal abstract ITypeReference/*?*/ GetAsTypeReference(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
);
}
internal abstract class NominalTypeName : TypeName {
internal abstract uint GenericParameterCount { get; }
internal abstract IMetadataReaderNamedTypeReference/*?*/ GetAsNomimalType(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
);
internal override ITypeReference GetAsTypeReference(
PEFileToObjectModel peFileToObjectModel, IMetadataReaderModuleReference module
) {
return this.GetAsNomimalType(peFileToObjectModel, module);
}
internal IMetadataReaderNamedTypeReference GetAsNamedTypeReference(
PEFileToObjectModel peFileToObjectModel, IMetadataReaderModuleReference module
) {
return this.GetAsNomimalType(peFileToObjectModel, module);
}
internal abstract INamedTypeDefinition/*?*/ ResolveNominalTypeName(
PEFileToObjectModel peFileToObjectModel
);
internal abstract IName UnmangledTypeName { get; }
}
internal sealed class NamespaceTypeName : NominalTypeName {
readonly ushort genericParameterCount;
internal readonly NamespaceName/*?*/ NamespaceName;
internal readonly IName Name;
internal readonly IName unmanagledTypeName;
internal NamespaceTypeName(INameTable nameTable, NamespaceName/*?*/ namespaceName, IName name) {
this.NamespaceName = namespaceName;
this.Name = name;
string nameStr = null;
TypeCache.SplitMangledTypeName(name.Value, out nameStr, out this.genericParameterCount);
if (this.genericParameterCount > 0)
this.unmanagledTypeName = nameTable.GetNameFor(nameStr);
else
this.unmanagledTypeName = name;
}
private NamespaceTypeName(INameTable nameTable, NamespaceName/*?*/ namespaceName, IName name, IName unmangledTypeName) {
this.NamespaceName = namespaceName;
this.Name = name;
this.unmanagledTypeName = unmangledTypeName;
}
internal override uint GenericParameterCount {
get { return this.genericParameterCount; }
}
internal override IMetadataReaderNamedTypeReference/*?*/ GetAsNomimalType(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
) {
var typeRef = new NamespaceTypeNameTypeReference(module, this, peFileToObjectModel);
var redirectedTypeRef = peFileToObjectModel.ModuleReader.metadataReaderHost.Redirect(peFileToObjectModel.Module, typeRef) as INamespaceTypeReference;
if (redirectedTypeRef != typeRef && redirectedTypeRef != null) {
var namespaceName = this.GetNamespaceName(peFileToObjectModel.NameTable, redirectedTypeRef.ContainingUnitNamespace as INestedUnitNamespaceReference);
var mangledName = redirectedTypeRef.Name;
if (redirectedTypeRef.GenericParameterCount > 0)
mangledName = peFileToObjectModel.NameTable.GetNameFor(redirectedTypeRef.Name.Value+"`"+redirectedTypeRef.GenericParameterCount);
var redirectedNamespaceTypeName = new NamespaceTypeName(peFileToObjectModel.NameTable, namespaceName, mangledName, redirectedTypeRef.Name);
return new NamespaceTypeNameTypeReference(module, redirectedNamespaceTypeName, peFileToObjectModel);
}
return typeRef;
}
private NamespaceName/*?*/ GetNamespaceName(INameTable nameTable, INestedUnitNamespaceReference/*?*/ nestedUnitNamespaceReference) {
if (nestedUnitNamespaceReference == null) return null;
var parentNamespaceName = this.GetNamespaceName(nameTable, nestedUnitNamespaceReference.ContainingUnitNamespace as INestedUnitNamespaceReference);
return new NamespaceName(nameTable, parentNamespaceName, nestedUnitNamespaceReference.Name);
}
internal override IName UnmangledTypeName {
get {
return this.unmanagledTypeName;
}
}
internal override INamedTypeDefinition/*?*/ ResolveNominalTypeName(
PEFileToObjectModel peFileToObjectModel
) {
if (this.NamespaceName == null)
return peFileToObjectModel.ResolveNamespaceTypeDefinition(
peFileToObjectModel.NameTable.EmptyName,
this.Name
);
else
return peFileToObjectModel.ResolveNamespaceTypeDefinition(
this.NamespaceName.FullyQualifiedName,
this.Name
);
}
internal bool MangleName {
get { return this.Name.UniqueKey != this.unmanagledTypeName.UniqueKey; }
}
}
internal sealed class NestedTypeName : NominalTypeName {
readonly ushort genericParameterCount;
internal readonly NominalTypeName ContainingTypeName;
internal readonly IName Name;
internal readonly IName unmangledTypeName;
internal NestedTypeName(INameTable nameTable, NominalTypeName containingTypeName, IName mangledName) {
this.ContainingTypeName = containingTypeName;
this.Name = mangledName;
string nameStr = null;
TypeCache.SplitMangledTypeName(mangledName.Value, out nameStr, out this.genericParameterCount);
this.unmangledTypeName = nameTable.GetNameFor(nameStr);
}
internal override uint GenericParameterCount {
get { return this.genericParameterCount; }
}
internal override IMetadataReaderNamedTypeReference/*?*/ GetAsNomimalType(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
) {
return new NestedTypeNameTypeReference(module, this, peFileToObjectModel);
}
internal override IName UnmangledTypeName {
get {
return this.unmangledTypeName;
}
}
internal override INamedTypeDefinition/*?*/ ResolveNominalTypeName(
PEFileToObjectModel peFileToObjectModel
) {
var containingType = this.ContainingTypeName.ResolveNominalTypeName(peFileToObjectModel);
if (containingType == null)
return null;
return peFileToObjectModel.ResolveNestedTypeDefinition(
containingType,
this.Name
);
}
internal bool MangleName {
get { return this.Name.UniqueKey != this.unmangledTypeName.UniqueKey; }
}
}
internal sealed class GenericTypeName : TypeName {
internal readonly NominalTypeName GenericTemplate;
internal readonly List<TypeName> GenericArguments;
internal GenericTypeName(NominalTypeName genericTemplate, List<TypeName> genericArguments) {
this.GenericTemplate = genericTemplate;
this.GenericArguments = genericArguments;
}
internal override ITypeReference/*?*/ GetAsTypeReference(PEFileToObjectModel peFileToObjectModel, IMetadataReaderModuleReference module) {
var nominalType = this.GenericTemplate.GetAsNomimalType(peFileToObjectModel, module);
if (nominalType == null) return null;
int argumentUsed;
return this.GetSpecializedTypeReference(peFileToObjectModel, nominalType, out argumentUsed, mostNested: true);
}
private ITypeReference GetSpecializedTypeReference(PEFileToObjectModel peFileToObjectModel, INamedTypeReference nominalType, out int argumentUsed, bool mostNested) {
argumentUsed = 0;
int len = this.GenericArguments.Count;
var nestedType = nominalType as INestedTypeReference;
if (nestedType != null) {
var parentTemplate = this.GetSpecializedTypeReference(peFileToObjectModel, (INamedTypeReference)nestedType.ContainingType, out argumentUsed, mostNested: false);
if (parentTemplate != nestedType.ContainingType)
nominalType = new SpecializedNestedTypeReference(nestedType, parentTemplate, peFileToObjectModel.InternFactory);
}
var argsToUse = mostNested ? len-argumentUsed : nominalType.GenericParameterCount;
if (argsToUse == 0) return nominalType;
var genericArgumentsReferences = new ITypeReference[argsToUse];
for (int i = 0; i < argsToUse; ++i)
genericArgumentsReferences[i] = this.GenericArguments[i+argumentUsed].GetAsTypeReference(peFileToObjectModel, peFileToObjectModel.Module)??Dummy.TypeReference;
argumentUsed += argsToUse;
return new GenericTypeInstanceReference(nominalType, IteratorHelper.GetReadonly(genericArgumentsReferences), peFileToObjectModel.InternFactory);
}
}
internal sealed class ArrayTypeName : TypeName {
readonly TypeName ElementType;
readonly uint Rank; // 0 is SZArray
internal ArrayTypeName(TypeName elementType, uint rank) {
this.ElementType = elementType;
this.Rank = rank;
}
internal override ITypeReference/*?*/ GetAsTypeReference(PEFileToObjectModel peFileToObjectModel, IMetadataReaderModuleReference module) {
ITypeReference/*?*/ elementType = this.ElementType.GetAsTypeReference(peFileToObjectModel, module);
if (elementType == null) return null;
if (this.Rank == 0)
return Vector.GetVector(elementType, peFileToObjectModel.InternFactory);
else
return Matrix.GetMatrix(elementType, this.Rank, peFileToObjectModel.InternFactory);
}
}
internal sealed class PointerTypeName : TypeName {
internal readonly TypeName TargetType;
internal PointerTypeName(
TypeName targetType
) {
this.TargetType = targetType;
}
internal override ITypeReference/*?*/ GetAsTypeReference(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
) {
var targetType = this.TargetType.GetAsTypeReference(peFileToObjectModel, module);
if (targetType == null) return null;
return PointerType.GetPointerType(targetType, peFileToObjectModel.InternFactory);
}
}
internal sealed class ManagedPointerTypeName : TypeName {
internal readonly TypeName TargetType;
internal ManagedPointerTypeName(
TypeName targetType
) {
this.TargetType = targetType;
}
internal override ITypeReference GetAsTypeReference(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
) {
ITypeReference/*?*/ targetType = this.TargetType.GetAsTypeReference(peFileToObjectModel, module);
if (targetType == null) return null;
return ManagedPointerType.GetManagedPointerType(targetType, peFileToObjectModel.InternFactory);
}
}
internal sealed class AssemblyQualifiedTypeName : TypeName {
private TypeName TypeName;
private readonly AssemblyIdentity AssemblyIdentity;
private readonly bool Retargetable;
internal AssemblyQualifiedTypeName(TypeName typeName, AssemblyIdentity assemblyIdentity, bool retargetable) {
this.TypeName = typeName;
this.AssemblyIdentity = assemblyIdentity;
this.Retargetable = retargetable;
}
internal override ITypeReference/*?*/ GetAsTypeReference(PEFileToObjectModel peFileToObjectModel, IMetadataReaderModuleReference module) {
foreach (var aref in peFileToObjectModel.GetAssemblyReferences()) {
var assemRef = aref as AssemblyReference;
if (assemRef == null) continue;
if (assemRef.AssemblyIdentity.Equals(this.AssemblyIdentity))
return this.TypeName.GetAsTypeReference(peFileToObjectModel, assemRef);
}
if (module.ContainingAssembly.AssemblyIdentity.Equals(this.AssemblyIdentity))
return this.TypeName.GetAsTypeReference(peFileToObjectModel, module);
AssemblyFlags flags = this.Retargetable ? AssemblyFlags.Retargetable : (AssemblyFlags)0;
return this.TypeName.GetAsTypeReference(peFileToObjectModel, new AssemblyReference(peFileToObjectModel, 0, this.AssemblyIdentity, flags));
}
}
internal enum TypeNameTokenKind {
EOS,
Identifier,
Dot,
Plus,
OpenBracket,
CloseBracket,
Astrix,
Comma,
Ampersand,
Equals,
PublicKeyToken,
}
internal struct ScannerState {
internal readonly int CurrentIndex;
internal readonly TypeNameTokenKind CurrentTypeNameTokenKind;
internal readonly IName CurrentIdentifierInfo;
internal ScannerState(
int currentIndex,
TypeNameTokenKind currentTypeNameTokenKind,
IName currentIdentifierInfo
) {
this.CurrentIndex = currentIndex;
this.CurrentTypeNameTokenKind = currentTypeNameTokenKind;
this.CurrentIdentifierInfo = currentIdentifierInfo;
}
}
internal sealed class TypeNameParser {
readonly INameTable NameTable;
readonly string TypeName;
readonly int Length;
readonly IName Version;
readonly IName Retargetable;
readonly IName PublicKeyToken;
readonly IName Culture;
readonly IName neutral;
int CurrentIndex;
TypeNameTokenKind CurrentTypeNameTokenKind;
IName CurrentIdentifierInfo;
ScannerState ScannerSnapshot() {
return new ScannerState(
this.CurrentIndex,
this.CurrentTypeNameTokenKind,
this.CurrentIdentifierInfo
);
}
void RestoreScanner(
ScannerState scannerState
) {
this.CurrentIndex = scannerState.CurrentIndex;
this.CurrentTypeNameTokenKind = scannerState.CurrentTypeNameTokenKind;
this.CurrentIdentifierInfo = scannerState.CurrentIdentifierInfo;
}
void SkipSpaces() {
int currPtr = this.CurrentIndex;
string name = this.TypeName;
while (currPtr < this.Length && char.IsWhiteSpace(name[currPtr])) {
currPtr++;
}
this.CurrentIndex = currPtr;
}
static bool IsEndofIdentifier(
char c,
bool assemblyName
) {
if (c == '[' || c == ']' || c == '*' || c == '+' || c == ',' || c == '&' || c == ' ' || char.IsWhiteSpace(c)) {
return true;
}
if (assemblyName) {
if (c == '=')
return true;
} else {
if (c == '.')
return true;
}
return false;
}
Version/*?*/ ScanVersion() {
this.SkipSpaces();
int currPtr = this.CurrentIndex;
string name = this.TypeName;
if (currPtr >= this.Length)
return null;
// TODO: build a Version number parser.
int endMark = name.IndexOf(',', currPtr);
if (endMark == -1) {
endMark = this.Length;
}
string versString = name.Substring(currPtr, endMark - currPtr);
Version/*?*/ vers = null;
try {
vers = new Version(versString);
} catch (FormatException) {
// Error
} catch (OverflowException) {
// Error
} catch (ArgumentOutOfRangeException) {
// Error
} catch (ArgumentException) {
// Error
}
this.CurrentIndex = endMark;
return vers;
}
bool ScanYesNo(out bool value) {
this.SkipSpaces();
int currPtr = this.CurrentIndex;
string name = this.TypeName;
if (currPtr + 3 <= this.Length && string.Compare(name, currPtr, "yes", 0, 3, StringComparison.OrdinalIgnoreCase) == 0) {
this.CurrentIndex += 3;
value = true;
return true;
}
if (currPtr + 2 <= this.Length && string.Compare(name, currPtr, "no", 0, 2, StringComparison.OrdinalIgnoreCase) == 0) {
this.CurrentIndex += 2;
value = false;
return true;
}
value = false;
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
byte[] ScanPublicKeyToken() {
this.SkipSpaces();
int currPtr = this.CurrentIndex;
string name = this.TypeName;
if (currPtr + 4 <= this.Length && string.Compare(name, currPtr, "null", 0, 4, StringComparison.OrdinalIgnoreCase) == 0) {
this.CurrentIndex += 4;
return TypeCache.EmptyByteArray;
}
if (currPtr + 16 > this.Length) {
return TypeCache.EmptyByteArray;
}
string val = name.Substring(currPtr, 16);
this.CurrentIndex += 16;
ulong result = 0;
try {
result = ulong.Parse(val, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture);
} catch {
return TypeCache.EmptyByteArray;
}
byte[] pkToken = new byte[8];
for (int i = 7; i >= 0; --i) {
pkToken[i] = (byte)result;
result >>= 8;
}
return pkToken;
}
void NextToken(bool assemblyName) {
this.SkipSpaces();
if (this.CurrentIndex >= this.TypeName.Length) {
this.CurrentTypeNameTokenKind = TypeNameTokenKind.EOS;
return;
}
switch (this.TypeName[this.CurrentIndex]) {
case '[':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.OpenBracket;
this.CurrentIndex++;
break;
case ']':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.CloseBracket;
this.CurrentIndex++;
break;
case '*':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Astrix;
this.CurrentIndex++;
break;
case '.':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Dot;
this.CurrentIndex++;
break;
case '+':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Plus;
this.CurrentIndex++;
break;
case ',':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Comma;
this.CurrentIndex++;
break;
case '&':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Ampersand;
this.CurrentIndex++;
break;
case '=':
if (assemblyName) {
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Equals;
this.CurrentIndex++;
break;
}
goto default;
default: {
int currIndex = this.CurrentIndex;
StringBuilder sb = new StringBuilder();
string name = this.TypeName;
while (currIndex < this.Length) {
char c = name[currIndex];
if (TypeNameParser.IsEndofIdentifier(c, assemblyName))
break;
if (c == '\\') {
currIndex++;
if (currIndex < this.Length) {
sb.Append(name[currIndex]);
currIndex++;
} else {
break;
}
} else {
sb.Append(c);
currIndex++;
}
}
this.CurrentIndex = currIndex;
this.CurrentIdentifierInfo = this.NameTable.GetNameFor(sb.ToString());
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Identifier;
break;
}
}
}
static bool IsTypeNameStart(
TypeNameTokenKind typeNameTokenKind
) {
return typeNameTokenKind == TypeNameTokenKind.Identifier
|| typeNameTokenKind == TypeNameTokenKind.OpenBracket;
}
internal TypeNameParser(
INameTable nameTable,
string typeName
) {
this.NameTable = nameTable;
this.TypeName = typeName;
this.Length = typeName.Length;
this.Version = nameTable.GetNameFor("Version");
this.Retargetable = nameTable.GetNameFor("Retargetable");
this.PublicKeyToken = nameTable.GetNameFor("PublicKeyToken");
this.Culture = nameTable.GetNameFor("Culture");
this.neutral = nameTable.GetNameFor("neutral");
this.CurrentIdentifierInfo = nameTable.EmptyName;
this.NextToken(false);
}
NamespaceTypeName/*?*/ ParseNamespaceTypeName() {
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier) {
return null;
}
IName lastName = this.CurrentIdentifierInfo;
NamespaceName/*?*/ currNsp = null;
this.NextToken(false);
while (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Dot) {
this.NextToken(false);
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier) {
return null;
}
currNsp = new NamespaceName(this.NameTable, currNsp, lastName);
lastName = this.CurrentIdentifierInfo;
this.NextToken(false);
}
return new NamespaceTypeName(this.NameTable, currNsp, lastName);
}
TypeName/*?*/ ParseGenericTypeArgument() {
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.OpenBracket) {
this.NextToken(false);
TypeName/*?*/ retTypeName = this.ParseTypeNameWithPossibleAssemblyName();
if (retTypeName == null) {
return null;
}
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.CloseBracket) {
return null;
}
this.NextToken(false);
return retTypeName;
} else {
return this.ParseFullName();
}
}
NominalTypeName/*?*/ ParseNominalTypeName() {
NominalTypeName/*?*/ nomTypeName = this.ParseNamespaceTypeName();
if (nomTypeName == null)
return null;
while (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Plus) {
this.NextToken(false);
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier) {
return null;
}
nomTypeName = new NestedTypeName(this.NameTable, nomTypeName, this.CurrentIdentifierInfo);
this.NextToken(false);
}
return nomTypeName;
}
TypeName/*?*/ ParsePossiblyGenericTypeName() {
NominalTypeName/*?*/ nomTypeName = this.ParseNominalTypeName();
if (nomTypeName == null)
return null;
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.OpenBracket) {
ScannerState scannerSnapshot = this.ScannerSnapshot();
this.NextToken(false);
if (TypeNameParser.IsTypeNameStart(this.CurrentTypeNameTokenKind)) {
List<TypeName> genArgList = new List<TypeName>();
TypeName/*?*/ genArg = this.ParseGenericTypeArgument();
if (genArg == null)
return null;
genArgList.Add(genArg);
while (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Comma) {
this.NextToken(false);
genArg = this.ParseGenericTypeArgument();
if (genArg == null)
return null;
genArgList.Add(genArg);
}
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.CloseBracket) {
return null;
}
this.NextToken(false);
return new GenericTypeName(nomTypeName, genArgList);
}
this.RestoreScanner(scannerSnapshot);
}
return nomTypeName;
}
TypeName/*?*/ ParseFullName() {
TypeName/*?*/ typeName = this.ParsePossiblyGenericTypeName();
if (typeName == null)
return null;
for (; ; ) {
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Astrix) {
this.NextToken(false);
typeName = new PointerTypeName(typeName);
} else if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.OpenBracket) {
this.NextToken(false);
uint rank;
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Astrix) {
rank = 1;
} else if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Comma) {
rank = 1;
while (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Comma) {
this.NextToken(false);
rank++;
}
} else if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.CloseBracket) {
rank = 0; // SZArray Case
} else {
return null;
}
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.CloseBracket) {
return null;
}
this.NextToken(false);
typeName = new ArrayTypeName(typeName, rank);
} else {
break;
}
}
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Ampersand) {
this.NextToken(false);
typeName = new ManagedPointerTypeName(typeName);
}
return typeName;
}
AssemblyIdentity/*?*/ ParseAssemblyName(out bool retargetable) {
retargetable = false;
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier) {
return null;
}
IName assemblyName = this.CurrentIdentifierInfo;
this.NextToken(true);
bool versionRead = false;
Version/*?*/ version = Dummy.Version;
bool pkTokenRead = false;
byte[] publicKeyToken = TypeCache.EmptyByteArray;
bool cultureRead = false;
bool retargetableRead = false;
IName culture = this.NameTable.EmptyName;
while (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Comma) {
this.NextToken(true);
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier)
return null;
IName infoIdent = this.CurrentIdentifierInfo;
this.NextToken(true);
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Equals)
return null;
if (infoIdent.UniqueKeyIgnoringCase == this.Culture.UniqueKeyIgnoringCase) {
this.NextToken(true);
if (cultureRead || this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier)
return null;
culture = this.CurrentIdentifierInfo;
if (culture.UniqueKeyIgnoringCase == this.neutral.UniqueKeyIgnoringCase)
culture = this.NameTable.EmptyName;
cultureRead = true;
} else if (infoIdent.UniqueKeyIgnoringCase == this.Version.UniqueKeyIgnoringCase) {
if (versionRead)
return null;
version = this.ScanVersion();
if (version == null)
return null;
versionRead = true;
} else if (infoIdent.UniqueKeyIgnoringCase == this.PublicKeyToken.UniqueKeyIgnoringCase) {
if (pkTokenRead)
return null;
publicKeyToken = this.ScanPublicKeyToken();
//if (IteratorHelper.EnumerableIsEmpty(publicKeyToken))
// return null;
pkTokenRead = true;
} else if (infoIdent.UniqueKeyIgnoringCase == this.Retargetable.UniqueKeyIgnoringCase) {
if (retargetableRead)
return null;
if (!this.ScanYesNo(out retargetable))
return null;
retargetableRead = true;
} else {
// TODO: Error: Identifier in assembly name.
while (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Comma && this.CurrentTypeNameTokenKind != TypeNameTokenKind.CloseBracket && this.CurrentTypeNameTokenKind != TypeNameTokenKind.EOS) {
this.NextToken(true);
}
}
this.NextToken(true);
}
// TODO: PublicKey also is possible...
return new AssemblyIdentity(assemblyName, culture.Value, version, publicKeyToken, string.Empty);
}
TypeName/*?*/ ParseTypeNameWithPossibleAssemblyName() {
TypeName/*?*/ tn = this.ParseFullName();
if (tn == null)
return null;
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Comma) {
this.NextToken(true);
bool retargetable = false;
AssemblyIdentity/*?*/ assemIdentity = this.ParseAssemblyName(out retargetable);
if (assemIdentity == null)
return null;
tn = new AssemblyQualifiedTypeName(tn, assemIdentity, retargetable);
}
return tn;
}
internal TypeName/*?*/ ParseTypeName() {
TypeName/*?*/ tn = this.ParseTypeNameWithPossibleAssemblyName();
if (tn == null || this.CurrentTypeNameTokenKind != TypeNameTokenKind.EOS)
return null;
return tn;
}
}
}
namespace Microsoft.Cci.MetadataReader {
internal abstract class AttributeDecoder {
internal bool decodeFailed;
internal bool morePermutationsArePossible;
readonly protected PEFileToObjectModel PEFileToObjectModel;
protected MemoryReader SignatureMemoryReader;
protected object/*?*/ GetPrimitiveValue(ITypeReference type) {
switch (type.TypeCode) {
case PrimitiveTypeCode.Int8:
if (this.SignatureMemoryReader.Offset+1 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (sbyte)0;
}
return this.SignatureMemoryReader.ReadSByte();
case PrimitiveTypeCode.Int16:
if (this.SignatureMemoryReader.Offset+2 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (short)0;
}
return this.SignatureMemoryReader.ReadInt16();
case PrimitiveTypeCode.Int32:
if (this.SignatureMemoryReader.Offset+4 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (int)0;
}
return this.SignatureMemoryReader.ReadInt32();
case PrimitiveTypeCode.Int64:
if (this.SignatureMemoryReader.Offset+8 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (long)0;
}
return this.SignatureMemoryReader.ReadInt64();
case PrimitiveTypeCode.UInt8:
if (this.SignatureMemoryReader.Offset+1 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (byte)0;
}
return this.SignatureMemoryReader.ReadByte();
case PrimitiveTypeCode.UInt16:
if (this.SignatureMemoryReader.Offset+2 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (ushort)0;
}
return this.SignatureMemoryReader.ReadUInt16();
case PrimitiveTypeCode.UInt32:
if (this.SignatureMemoryReader.Offset+4 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (uint)0;
}
return this.SignatureMemoryReader.ReadUInt32();
case PrimitiveTypeCode.UInt64:
if (this.SignatureMemoryReader.Offset+8 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (ulong)0;
}
return this.SignatureMemoryReader.ReadUInt64();
case PrimitiveTypeCode.Float32:
if (this.SignatureMemoryReader.Offset+4 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (float)0;
}
return this.SignatureMemoryReader.ReadSingle();
case PrimitiveTypeCode.Float64:
if (this.SignatureMemoryReader.Offset+8 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (double)0;
}
return this.SignatureMemoryReader.ReadDouble();
case PrimitiveTypeCode.Boolean: {
if (this.SignatureMemoryReader.Offset+1 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return false;
}
byte val = this.SignatureMemoryReader.ReadByte();
return val == 1;
}
case PrimitiveTypeCode.Char:
if (this.SignatureMemoryReader.Offset+2 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (char)0;
}
return this.SignatureMemoryReader.ReadChar();
}
this.decodeFailed = true;
return null;
}
protected string/*?*/ GetSerializedString() {
int byteLen = this.SignatureMemoryReader.ReadCompressedUInt32();
if (byteLen == -1)
return null;
if (byteLen == 0)
return string.Empty;
if (this.SignatureMemoryReader.Offset+byteLen > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return null;
}
return this.SignatureMemoryReader.ReadUTF8WithSize(byteLen);
}
protected ITypeReference/*?*/ GetFieldOrPropType() {
if (this.SignatureMemoryReader.Offset+1 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return null;
}
byte elementByte = this.SignatureMemoryReader.ReadByte();
switch (elementByte) {
case SerializationType.Boolean:
return this.PEFileToObjectModel.PlatformType.SystemBoolean;
case SerializationType.Char:
return this.PEFileToObjectModel.PlatformType.SystemChar;
case SerializationType.Int8:
return this.PEFileToObjectModel.PlatformType.SystemInt8;
case SerializationType.UInt8:
return this.PEFileToObjectModel.PlatformType.SystemUInt8;
case SerializationType.Int16:
return this.PEFileToObjectModel.PlatformType.SystemInt16;
case SerializationType.UInt16:
return this.PEFileToObjectModel.PlatformType.SystemUInt16;
case SerializationType.Int32:
return this.PEFileToObjectModel.PlatformType.SystemInt32;
case SerializationType.UInt32:
return this.PEFileToObjectModel.PlatformType.SystemUInt32;
case SerializationType.Int64:
return this.PEFileToObjectModel.PlatformType.SystemInt64;
case SerializationType.UInt64:
return this.PEFileToObjectModel.PlatformType.SystemUInt64;
case SerializationType.Single:
return this.PEFileToObjectModel.PlatformType.SystemFloat32;
case SerializationType.Double:
return this.PEFileToObjectModel.PlatformType.SystemFloat64;
case SerializationType.String:
return this.PEFileToObjectModel.PlatformType.SystemString;
case SerializationType.SZArray: {
ITypeReference/*?*/ elementType = this.GetFieldOrPropType();
if (elementType == null) return null;
return Vector.GetVector(elementType, this.PEFileToObjectModel.InternFactory);
}
case SerializationType.Type:
return this.PEFileToObjectModel.PlatformType.SystemType;
case SerializationType.TaggedObject:
return this.PEFileToObjectModel.PlatformType.SystemObject;
case SerializationType.Enum: {
string/*?*/ typeName = this.GetSerializedString();
if (typeName == null)
return null;
var result = this.PEFileToObjectModel.GetSerializedTypeNameAsTypeReference(typeName);
var tnr = result as TypeNameTypeReference;
if (tnr == null) {
var specializedNestedType = result as ISpecializedNestedTypeReference;
if (specializedNestedType != null)
tnr = specializedNestedType.UnspecializedVersion as TypeNameTypeReference;
}
if (tnr != null) tnr.IsEnum = true;
return result;
}
}
this.decodeFailed = true;
return null;
}
protected TypeName/*?*/ ConvertToTypeName(
string serializedTypeName
) {
TypeNameParser typeNameParser = new TypeNameParser(this.PEFileToObjectModel.NameTable, serializedTypeName);
TypeName/*?*/ typeName = typeNameParser.ParseTypeName();
return typeName;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected ExpressionBase/*?*/ ReadSerializedValue(ITypeReference type) {
switch (type.TypeCode) {
case PrimitiveTypeCode.Int8:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt8:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.UInt32:
case PrimitiveTypeCode.UInt64:
case PrimitiveTypeCode.Float32:
case PrimitiveTypeCode.Float64:
case PrimitiveTypeCode.Boolean:
case PrimitiveTypeCode.Char:
return new ConstantExpression(type, this.GetPrimitiveValue(type));
case PrimitiveTypeCode.String:
return new ConstantExpression(type, this.GetSerializedString());
default:
var typeDef = type.ResolvedType;
if (!(typeDef is Dummy)) {
if (typeDef.IsEnum)
return new ConstantExpression(type, this.GetPrimitiveValue(typeDef.UnderlyingType));
type = typeDef;
}
if (TypeHelper.TypesAreEquivalent(type, this.PEFileToObjectModel.PlatformType.SystemObject)) {
ITypeReference/*?*/ underlyingType = this.GetFieldOrPropType();
if (underlyingType == null) return null;
return this.ReadSerializedValue(underlyingType);
}
if (TypeHelper.TypesAreEquivalent(type, this.PEFileToObjectModel.PlatformType.SystemType)) {
string/*?*/ typeNameStr = this.GetSerializedString();
if (typeNameStr == null) {
return new ConstantExpression(this.PEFileToObjectModel.PlatformType.SystemType, null);
}
return new TypeOfExpression(this.PEFileToObjectModel, this.PEFileToObjectModel.GetSerializedTypeNameAsTypeReference(typeNameStr));
}
var vectorType = type as IArrayTypeReference;
if (vectorType != null) {
ITypeReference/*?*/ elementType = vectorType.ElementType;
if (elementType == null) {
this.decodeFailed = true;
return null;
}
int size = this.SignatureMemoryReader.ReadInt32();
if (size == -1) {
return new ConstantExpression(vectorType, null);
}
ExpressionBase[] arrayElements = new ExpressionBase[size];
for (int i = 0; i < size; ++i) {
ExpressionBase/*?*/ expr = this.ReadSerializedValue(elementType);
if (expr == null) {
this.decodeFailed = true;
return null;
}
arrayElements[i] = expr;
}
return new ArrayExpression(vectorType, new EnumerableArrayWrapper<ExpressionBase, IMetadataExpression>(arrayElements, Dummy.Expression));
} else {
// If the metadata is correct, type must be a reference to an enum type.
// Problem is, that without resolving this reference, it is not possible to know how many bytes to consume for the enum value
// We'll let the host deal with this by guessing
ITypeReference underlyingType;
switch (this.PEFileToObjectModel.ModuleReader.metadataReaderHost.GuessUnderlyingTypeSizeOfUnresolvableReferenceToEnum(type)) {
case 1: underlyingType = this.PEFileToObjectModel.PlatformType.SystemInt8; break;
case 2: underlyingType = this.PEFileToObjectModel.PlatformType.SystemInt16; break;
case 4: underlyingType = this.PEFileToObjectModel.PlatformType.SystemInt32; break;
case 8: underlyingType = this.PEFileToObjectModel.PlatformType.SystemInt64; break;
default:
this.decodeFailed = true; this.morePermutationsArePossible = false;
return new ConstantExpression(type, 0);
}
return new ConstantExpression(type, this.GetPrimitiveValue(underlyingType));
}
}
}
protected AttributeDecoder(
PEFileToObjectModel peFileToObjectModel,
MemoryReader signatureMemoryReader
) {
this.PEFileToObjectModel = peFileToObjectModel;
this.SignatureMemoryReader = signatureMemoryReader;
this.morePermutationsArePossible = true;
}
}
internal sealed class CustomAttributeDecoder : AttributeDecoder {
internal readonly ICustomAttribute CustomAttribute;
internal CustomAttributeDecoder(PEFileToObjectModel peFileToObjectModel, MemoryReader signatureMemoryReader, uint customAttributeRowId,
IMethodReference attributeConstructor)
: base(peFileToObjectModel, signatureMemoryReader) {
this.CustomAttribute = Dummy.CustomAttribute;
ushort prolog = this.SignatureMemoryReader.ReadUInt16();
if (prolog != SerializationType.CustomAttributeStart) return;
int len = attributeConstructor.ParameterCount;
IMetadataExpression[]/*?*/ exprList = len == 0 ? null : new IMetadataExpression[len];
int i = 0;
foreach (var parameter in attributeConstructor.Parameters) {
var parameterType = parameter.Type;
if (parameterType is Dummy) {
// Error...
return;
}
ExpressionBase/*?*/ argument = this.ReadSerializedValue(parameterType);
if (argument == null) {
// Error...
this.decodeFailed = true;
return;
}
exprList[i++] = argument;
}
IMetadataNamedArgument[]/*?*/ namedArgumentArray = null;
if (2 <= (int)this.SignatureMemoryReader.RemainingBytes) {
ushort numOfNamedArgs = this.SignatureMemoryReader.ReadUInt16();
if (numOfNamedArgs > 0) {
namedArgumentArray = new IMetadataNamedArgument[numOfNamedArgs];
for (i = 0; i < numOfNamedArgs; ++i) {
if (0 >= (int)this.SignatureMemoryReader.RemainingBytes) break;
bool isField = this.SignatureMemoryReader.ReadByte() == SerializationType.Field;
ITypeReference/*?*/ memberType = this.GetFieldOrPropType();
if (memberType == null) {
// Error...
return;
}
string/*?*/ memberStr = this.GetSerializedString();
if (memberStr == null)
return;
IName memberName = this.PEFileToObjectModel.NameTable.GetNameFor(memberStr);
ExpressionBase/*?*/ value = this.ReadSerializedValue(memberType);
if (value == null) {
// Error...
return;
}
ITypeReference/*?*/ moduleTypeRef = attributeConstructor.ContainingType;
if (moduleTypeRef == null) {
// Error...
return;
}
FieldOrPropertyNamedArgumentExpression namedArg = new FieldOrPropertyNamedArgumentExpression(memberName, moduleTypeRef, isField, memberType, value);
namedArgumentArray[i] = namedArg;
}
}
}
this.CustomAttribute = peFileToObjectModel.ModuleReader.metadataReaderHost.Rewrite(peFileToObjectModel.Module,
new CustomAttribute(peFileToObjectModel, customAttributeRowId, attributeConstructor, exprList, namedArgumentArray));
}
}
internal sealed class SecurityAttributeDecoder20 : AttributeDecoder {
internal readonly IEnumerable<ICustomAttribute> SecurityAttributes;
SecurityCustomAttribute/*?*/ ReadSecurityAttribute(SecurityAttribute securityAttribute) {
string/*?*/ typeNameStr = this.GetSerializedString();
if (typeNameStr == null)
return null;
ITypeReference/*?*/ moduleTypeReference = this.PEFileToObjectModel.GetSerializedTypeNameAsTypeReference(typeNameStr);
if (moduleTypeReference == null)
return null;
IMethodReference ctorReference = Dummy.MethodReference;
ITypeDefinition attributeType = moduleTypeReference.ResolvedType;
if (!(attributeType is Dummy)) {
foreach (ITypeDefinitionMember member in attributeType.GetMembersNamed(this.PEFileToObjectModel.NameTable.Ctor, false)) {
IMethodDefinition/*?*/ method = member as IMethodDefinition;
if (method == null) continue;
if (!IteratorHelper.EnumerableHasLength(method.Parameters, 1)) continue;
//TODO: check that parameter has the right type
ctorReference = method;
break;
}
} else {
int ctorKey = this.PEFileToObjectModel.NameTable.Ctor.UniqueKey;
foreach (ITypeMemberReference mref in this.PEFileToObjectModel.GetMemberReferences()) {
IMethodReference/*?*/ methRef = mref as IMethodReference;
if (methRef == null) continue;
if (methRef.ContainingType.InternedKey != moduleTypeReference.InternedKey) continue;
if (methRef.Name.UniqueKey != ctorKey) continue;
if (!IteratorHelper.EnumerableHasLength(methRef.Parameters, 1)) continue;
//TODO: check that parameter has the right type
ctorReference = methRef;
break;
}
}
if (ctorReference is Dummy) {
ctorReference = new MethodReference(this.PEFileToObjectModel.ModuleReader.metadataReaderHost, moduleTypeReference,
CallingConvention.Default|CallingConvention.HasThis, this.PEFileToObjectModel.PlatformType.SystemVoid,
this.PEFileToObjectModel.NameTable.Ctor, 0, this.PEFileToObjectModel.PlatformType.SystemSecurityPermissionsSecurityAction);
}
this.SignatureMemoryReader.ReadCompressedUInt32(); // BlobSize...
int numOfNamedArgs = this.SignatureMemoryReader.ReadCompressedUInt32();
FieldOrPropertyNamedArgumentExpression[]/*?*/ namedArgumentArray = null;
if (numOfNamedArgs > 0) {
namedArgumentArray = new FieldOrPropertyNamedArgumentExpression[numOfNamedArgs];
for (int i = 0; i < numOfNamedArgs; ++i) {
bool isField = this.SignatureMemoryReader.ReadByte() == SerializationType.Field;
ITypeReference/*?*/ memberType = this.GetFieldOrPropType();
if (memberType == null)
return null;
string/*?*/ memberStr = this.GetSerializedString();
if (memberStr == null)
return null;
IName memberName = this.PEFileToObjectModel.NameTable.GetNameFor(memberStr);
ExpressionBase/*?*/ value = this.ReadSerializedValue(memberType);
if (value == null)
return null;
namedArgumentArray[i] = new FieldOrPropertyNamedArgumentExpression(memberName, moduleTypeReference, isField, memberType, value);
}
}
return new SecurityCustomAttribute(securityAttribute, ctorReference, namedArgumentArray);
}
internal SecurityAttributeDecoder20(PEFileToObjectModel peFileToObjectModel, MemoryReader signatureMemoryReader, SecurityAttribute securityAttribute)
: base(peFileToObjectModel, signatureMemoryReader) {
this.SecurityAttributes = Enumerable<ICustomAttribute>.Empty;
byte prolog = this.SignatureMemoryReader.ReadByte();
if (prolog != SerializationType.SecurityAttribute20Start) return;
int numberOfAttributes = this.SignatureMemoryReader.ReadCompressedUInt32();
var securityCustomAttributes = new ICustomAttribute[numberOfAttributes];
for (int i = 0; i < numberOfAttributes; ++i) {
var secAttr = this.ReadSecurityAttribute(securityAttribute);
if (secAttr == null) {
// MDError...
return;
}
securityCustomAttributes[i] = secAttr;
}
this.SecurityAttributes = IteratorHelper.GetReadonly(securityCustomAttributes);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Engine.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Entities.DynamicQuery;
using Signum.React.Facades;
using Signum.Utilities;
using Signum.Entities;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Signum.Entities.Basics;
using Signum.React.Filters;
using System.Collections.ObjectModel;
using Signum.Engine.Maps;
using System.Threading;
using System.Threading.Tasks;
using Signum.Utilities.ExpressionTrees;
using Microsoft.AspNetCore.Mvc;
using Signum.React.Json;
using System.Linq.Expressions;
using System.ComponentModel.DataAnnotations;
namespace Signum.React.ApiControllers
{
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
[ValidateModelFilter]
public class QueryController : ControllerBase
{
[HttpGet("api/query/findLiteLike"), ProfilerActionSplitter("types")]
public async Task<List<Lite<Entity>>> FindLiteLike(string types, string subString, int count, CancellationToken token)
{
Implementations implementations = ParseImplementations(types);
return await AutocompleteUtils.FindLiteLikeAsync(implementations, subString, count, token);
}
[HttpPost("api/query/findRowsLike"), ProfilerActionSplitter("types")]
public async Task<ResultTable> FindRowsLike([Required, FromBody]AutocompleteQueryRequestTS request, CancellationToken token)
{
var qn = QueryLogic.ToQueryName(request.queryKey);
var qd = QueryLogic.Queries.QueryDescription(qn);
var dqRequest = new DQueryableRequest
{
QueryName = qn,
Columns = request.columns.EmptyIfNull().Select(a => a.ToColumn(qd, false)).ToList(),
Filters = request.filters.EmptyIfNull().Select(a => a.ToFilter(qd, false)).ToList(),
Orders = request.orders.EmptyIfNull().Select(a => a.ToOrder(qd, false)).ToList()
};
var dqueryable = QueryLogic.Queries.GetDQueryable(dqRequest);
var entityType = qd.Columns.Single(a => a.IsEntity).Implementations!.Value.Types.SingleEx();
var result = await dqueryable.Query.AutocompleteUntypedAsync(dqueryable.Context.GetEntitySelector(), request.subString, request.count, entityType, token);
var columnAccessors = dqRequest.Columns.Select(c => (
column: c,
lambda: Expression.Lambda(c.Token.BuildExpression(dqueryable.Context), dqueryable.Context.Parameter)
)).ToList();
return DQueryable.ToResultTable(result.ToArray(), columnAccessors, null, new Pagination.Firsts(request.count));
}
[HttpGet("api/query/allLites"), ProfilerActionSplitter("types")]
public async Task<List<Lite<Entity>>> FetchAllLites(string types, CancellationToken token)
{
Implementations implementations = ParseImplementations(types);
return await AutocompleteUtils.FindAllLiteAsync(implementations, token);
}
private static Implementations ParseImplementations(string types)
{
return Implementations.By(types.Split(',').Select(a => TypeLogic.GetType(a.Trim())).ToArray());
}
[HttpGet("api/query/description/{queryName}"), ProfilerActionSplitter("queryName")]
public QueryDescriptionTS GetQueryDescription(string queryName)
{
var qn = QueryLogic.ToQueryName(queryName);
return new QueryDescriptionTS(QueryLogic.Queries.QueryDescription(qn));
}
[HttpGet("api/query/queryEntity/{queryName}"), ProfilerActionSplitter("queryName")]
public QueryEntity GetQueryEntity(string queryName)
{
var qn = QueryLogic.ToQueryName(queryName);
return QueryLogic.GetQueryEntity(qn);
}
[HttpPost("api/query/parseTokens")]
public List<QueryTokenTS> ParseTokens([Required, FromBody]ParseTokensRequest request)
{
var qn = QueryLogic.ToQueryName(request.queryKey);
var qd = QueryLogic.Queries.QueryDescription(qn);
var tokens = request.tokens.Select(tr => QueryUtils.Parse(tr.token, qd, tr.options)).ToList();
return tokens.Select(qt => new QueryTokenTS(qt, recursive: true)).ToList();
}
public class TokenRequest
{
public string token;
public SubTokensOptions options;
public override string ToString() => $"{token} ({options})";
}
public class ParseTokensRequest
{
public string queryKey;
public List<TokenRequest> tokens;
}
[HttpPost("api/query/subTokens")]
public List<QueryTokenTS> SubTokens([Required, FromBody]SubTokensRequest request)
{
var qn = QueryLogic.ToQueryName(request.queryKey);
var qd = QueryLogic.Queries.QueryDescription(qn);
var token = request.token == null ? null: QueryUtils.Parse(request.token, qd, request.options);
var tokens = QueryUtils.SubTokens(token, qd, request.options);
return tokens.Select(qt => new QueryTokenTS(qt, recursive: false)).ToList();
}
public class SubTokensRequest
{
public string queryKey;
public string? token;
public SubTokensOptions options;
}
[HttpPost("api/query/executeQuery"), ProfilerActionSplitter]
public async Task<ResultTable> ExecuteQuery([Required, FromBody]QueryRequestTS request, CancellationToken token)
{
var result = await QueryLogic.Queries.ExecuteQueryAsync(request.ToQueryRequest(), token);
return result;
}
[HttpPost("api/query/entitiesWithFilter"), ProfilerActionSplitter]
public async Task<List<Lite<Entity>>> GetEntitiesWithFilter([Required, FromBody]QueryEntitiesRequestTS request, CancellationToken token)
{
return await QueryLogic.Queries.GetEntities(request.ToQueryEntitiesRequest()).ToListAsync();
}
[HttpPost("api/query/queryValue"), ProfilerActionSplitter]
public async Task<object?> QueryValue([Required, FromBody]QueryValueRequestTS request, CancellationToken token)
{
return await QueryLogic.Queries.ExecuteQueryValueAsync(request.ToQueryValueRequest(), token);
}
}
public class QueryValueRequestTS
{
public string querykey;
public List<FilterTS> filters;
public string valueToken;
public SystemTimeTS/*?*/ systemTime;
public QueryValueRequest ToQueryValueRequest()
{
var qn = QueryLogic.ToQueryName(this.querykey);
var qd = QueryLogic.Queries.QueryDescription(qn);
var value = valueToken.HasText() ? QueryUtils.Parse(valueToken, qd, SubTokensOptions.CanAggregate | SubTokensOptions.CanElement) : null;
return new QueryValueRequest
{
QueryName = qn,
Filters = this.filters.EmptyIfNull().Select(f => f.ToFilter(qd, canAggregate: false)).ToList(),
ValueToken = value,
SystemTime = this.systemTime?.ToSystemTime(),
};
}
public override string ToString() => querykey;
}
public class AutocompleteQueryRequestTS
{
public string queryKey;
public List<FilterTS> filters;
public List<ColumnTS> columns;
public List<OrderTS> orders;
public string subString;
public int count;
}
public class QueryRequestTS
{
public string queryKey;
public bool groupResults;
public List<FilterTS> filters;
public List<OrderTS> orders;
public List<ColumnTS> columns;
public PaginationTS pagination;
public SystemTimeTS/*?*/ systemTime;
public QueryRequest ToQueryRequest()
{
var qn = QueryLogic.ToQueryName(this.queryKey);
var qd = QueryLogic.Queries.QueryDescription(qn);
return new QueryRequest
{
QueryName = qn,
GroupResults = groupResults,
Filters = this.filters.EmptyIfNull().Select(f => f.ToFilter(qd, canAggregate: groupResults)).ToList(),
Orders = this.orders.EmptyIfNull().Select(f => f.ToOrder(qd, canAggregate: groupResults)).ToList(),
Columns = this.columns.EmptyIfNull().Select(f => f.ToColumn(qd, canAggregate: groupResults)).ToList(),
Pagination = this.pagination.ToPagination(),
SystemTime = this.systemTime?.ToSystemTime(),
};
}
public override string ToString() => queryKey;
}
public class QueryEntitiesRequestTS
{
public string queryKey;
public List<FilterTS> filters;
public List<OrderTS> orders;
public int? count;
public override string ToString() => queryKey;
public QueryEntitiesRequest ToQueryEntitiesRequest()
{
var qn = QueryLogic.ToQueryName(queryKey);
var qd = QueryLogic.Queries.QueryDescription(qn);
return new QueryEntitiesRequest
{
QueryName = qn,
Count = count,
Filters = filters.EmptyIfNull().Select(f => f.ToFilter(qd, canAggregate: false)).ToList(),
Orders = orders.EmptyIfNull().Select(f => f.ToOrder(qd, canAggregate: false)).ToList(),
};
}
}
public class OrderTS
{
public string token;
public OrderType orderType;
public Order ToOrder(QueryDescription qd, bool canAggregate)
{
return new Order(QueryUtils.Parse(this.token, qd, SubTokensOptions.CanElement | (canAggregate ? SubTokensOptions.CanAggregate : 0)), orderType);
}
public override string ToString() => $"{token} {orderType}";
}
[JsonConverter(typeof(FilterJsonConverter))]
public abstract class FilterTS
{
public abstract Filter ToFilter(QueryDescription qd, bool canAggregate);
public static FilterTS FromFilter(Filter filter)
{
if (filter is FilterCondition fc)
return new FilterConditionTS
{
token = fc.Token.FullKey(),
operation = fc.Operation,
value = fc.Value
};
if (filter is FilterGroup fg)
return new FilterGroupTS
{
token = fg.Token?.FullKey(),
groupOperation = fg.GroupOperation,
filters = fg.Filters.Select(f => FromFilter(f)).ToList(),
};
throw new UnexpectedValueException(filter);
}
}
public class FilterConditionTS : FilterTS
{
public string token;
public FilterOperation operation;
public object? value;
public override Filter ToFilter(QueryDescription qd, bool canAggregate)
{
var options = SubTokensOptions.CanElement | SubTokensOptions.CanAnyAll | (canAggregate ? SubTokensOptions.CanAggregate : 0);
var parsedToken = QueryUtils.Parse(token, qd, options);
var expectedValueType = operation.IsList() ? typeof(ObservableCollection<>).MakeGenericType(parsedToken.Type.Nullify()) : parsedToken.Type;
var val = value is JToken jtok ?
jtok.ToObject(expectedValueType, JsonSerializer.Create(SignumServer.JsonSerializerSettings)) :
value;
return new FilterCondition(parsedToken, operation, val);
}
public override string ToString() => $"{token} {operation} {value}";
}
public class FilterGroupTS : FilterTS
{
public FilterGroupOperation groupOperation;
public string? token;
public List<FilterTS> filters;
public override Filter ToFilter(QueryDescription qd, bool canAggregate)
{
var options = SubTokensOptions.CanElement | SubTokensOptions.CanAnyAll | (canAggregate ? SubTokensOptions.CanAggregate : 0);
var parsedToken = token == null ? null : QueryUtils.Parse(token, qd, options);
var parsedFilters = filters.Select(f => f.ToFilter(qd, canAggregate)).ToList();
return new FilterGroup(groupOperation, parsedToken, parsedFilters);
}
}
public class ColumnTS
{
public string token;
public string displayName;
public Column ToColumn(QueryDescription qd, bool canAggregate)
{
var queryToken = QueryUtils.Parse(token, qd, SubTokensOptions.CanElement | (canAggregate ? SubTokensOptions.CanAggregate : 0));
return new Column(queryToken, displayName ?? queryToken.NiceName());
}
public override string ToString() => $"{token} '{displayName}'";
}
public class PaginationTS
{
public PaginationMode mode;
public int? elementsPerPage;
public int? currentPage;
public PaginationTS() { }
public PaginationTS(Pagination pagination)
{
this.mode = pagination.GetMode();
this.elementsPerPage = pagination.GetElementsPerPage();
this.currentPage = (pagination as Pagination.Paginate)?.CurrentPage;
}
public override string ToString() => $"{mode} {elementsPerPage} {currentPage}";
public Pagination ToPagination()
{
switch (mode)
{
case PaginationMode.All: return new Pagination.All();
case PaginationMode.Firsts: return new Pagination.Firsts(this.elementsPerPage!.Value);
case PaginationMode.Paginate: return new Pagination.Paginate(this.elementsPerPage!.Value, this.currentPage!.Value);
default:throw new InvalidOperationException($"Unexpected {mode}");
}
}
}
public class SystemTimeTS
{
public SystemTimeMode mode;
public DateTime? startDate;
public DateTime? endDate;
public SystemTimeTS() { }
public SystemTimeTS(SystemTime systemTime)
{
if (systemTime is SystemTime.AsOf asOf)
{
mode = SystemTimeMode.AsOf;
startDate = asOf.DateTime;
}
else if (systemTime is SystemTime.Between between)
{
mode = SystemTimeMode.Between;
startDate = between.StartDateTime;
endDate = between.EndtDateTime;
}
else if (systemTime is SystemTime.ContainedIn containedIn)
{
mode = SystemTimeMode.ContainedIn;
startDate = containedIn.StartDateTime;
endDate = containedIn.EndtDateTime;
}
else if (systemTime is SystemTime.All all)
{
mode = SystemTimeMode.All;
startDate = null;
endDate = null;
}
else
throw new InvalidOperationException("Unexpected System Time");
}
public override string ToString() => $"{mode} {startDate} {endDate}";
public SystemTime ToSystemTime()
{
switch (mode)
{
case SystemTimeMode.All: return new SystemTime.All();
case SystemTimeMode.AsOf: return new SystemTime.AsOf(startDate!.Value);
case SystemTimeMode.Between: return new SystemTime.Between(startDate!.Value, endDate!.Value);
case SystemTimeMode.ContainedIn: return new SystemTime.ContainedIn(startDate!.Value, endDate!.Value);
default: throw new InvalidOperationException($"Unexpected {mode}");
}
}
}
public class QueryDescriptionTS
{
public string queryKey;
public Dictionary<string, ColumnDescriptionTS> columns;
public QueryDescriptionTS(QueryDescription queryDescription)
{
this.queryKey = QueryUtils.GetKey(queryDescription.QueryName);
this.columns = queryDescription.Columns.ToDictionary(a => a.Name, a => new ColumnDescriptionTS(a, queryDescription.QueryName));
foreach (var action in AddExtension.GetInvocationListTyped())
{
action(this);
}
}
[JsonExtensionData]
public Dictionary<string, object> Extension { get; set; } = new Dictionary<string, object>();
public static Action<QueryDescriptionTS> AddExtension;
}
public class ColumnDescriptionTS
{
public string name;
public TypeReferenceTS type;
public string typeColor;
public string niceTypeName;
public FilterType? filterType;
public string? unit;
public string? format;
public string displayName;
public bool isGroupable;
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool hasOrderAdapter;
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool preferEquals;
public string? propertyRoute;
public ColumnDescriptionTS(ColumnDescription a, object queryName)
{
var token = new ColumnToken(a, queryName);
this.name = a.Name;
this.type = new TypeReferenceTS(a.Type, a.Implementations);
this.filterType = QueryUtils.TryGetFilterType(a.Type);
this.typeColor = token.TypeColor;
this.niceTypeName = token.NiceTypeName;
this.isGroupable = token.IsGroupable;
this.hasOrderAdapter = QueryUtils.OrderAdapters.ContainsKey(token.Type);
this.preferEquals = token.Type == typeof(string) &&
token.GetPropertyRoute() is PropertyRoute pr &&
typeof(Entity).IsAssignableFrom(pr.RootType) &&
Schema.Current.HasSomeIndex(pr);
this.unit = UnitAttribute.GetTranslation(a.Unit);
this.format = a.Format;
this.displayName = a.DisplayName;
this.propertyRoute = token.GetPropertyRoute()?.ToString();
}
}
public class QueryTokenTS
{
public QueryTokenTS() { }
public QueryTokenTS(QueryToken qt, bool recursive)
{
this.toStr = qt.ToString();
this.niceName = qt.NiceName();
this.key = qt.Key;
this.fullKey = qt.FullKey();
this.type = new TypeReferenceTS(qt.Type, qt.GetImplementations());
this.filterType = QueryUtils.TryGetFilterType(qt.Type);
this.format = qt.Format;
this.unit = UnitAttribute.GetTranslation(qt.Unit);
this.typeColor = qt.TypeColor;
this.niceTypeName = qt.NiceTypeName;
this.queryTokenType = GetQueryTokenType(qt);
this.isGroupable = qt.IsGroupable;
this.hasOrderAdapter = QueryUtils.OrderAdapters.ContainsKey(qt.Type);
this.preferEquals = qt.Type == typeof(string) &&
qt.GetPropertyRoute() is PropertyRoute pr &&
typeof(Entity).IsAssignableFrom(pr.RootType) &&
Schema.Current.HasSomeIndex(pr);
this.propertyRoute = qt.GetPropertyRoute()?.ToString();
if (recursive && qt.Parent != null)
this.parent = new QueryTokenTS(qt.Parent, recursive);
}
private QueryTokenType? GetQueryTokenType(QueryToken qt)
{
if (qt is AggregateToken)
return QueryTokenType.Aggregate;
if (qt is CollectionElementToken ce)
return QueryTokenType.Element;
if (qt is CollectionAnyAllToken caat)
return QueryTokenType.AnyOrAll;
return null;
}
public string toStr;
public string niceName;
public string key;
public string fullKey;
public string typeColor;
public string niceTypeName;
public QueryTokenType? queryTokenType;
public TypeReferenceTS type;
public FilterType? filterType;
public string? format;
public string? unit;
public bool isGroupable;
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool hasOrderAdapter;
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool preferEquals;
public QueryTokenTS? parent;
public string? propertyRoute;
}
public enum QueryTokenType
{
Aggregate,
Element,
AnyOrAll,
}
}
| |
/// <summary>
///
/// /// 11/1/2013
/// Steve Peters
/// GameDevelopersGuild.com
/// Miami Fl
///
/// Primary class for all the breakable chunks used in the scene
///
/// </summary>
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class PhysicsController_Child : GDG_Physics
{
public bool positionFrozen = false;
public bool preventBreaking = false; //used with fixed position chunks to keep them from breaking into lower levels
public bool _FlipMaterials = false; //flip material slots 1 and 2, a hack fix for wierd Blender imports
public bool playerCanBreak = false;
protected float _passDownMass;
protected bool _breaker = false; //special use variable that prevents multiple sub-objects from being intantiated when breaking object(multiple collisions issue)
protected int breakStrength;
protected bool scaleCol;
protected PhysicsController_Master _DLMaster;
protected AudioClip _AudioClipToPlay;
protected bool _CanExplode = true;
protected colliderType colType = colliderType.nullCollider; //keeps a reference to our collidertype
private BoxCollider boxCol; //caches our box collider so the we don't need to use GetComponent in the scale collider method
private SphereCollider sphereCol;
override protected void Start ()
{
base.Start ();
base.SetInitialChunkProperties ();
//set our collider type
if (_myTransform.GetComponent<Collider>() != null)
{
if (_myTransform.GetComponent<Collider>().GetType() == (typeof(BoxCollider)))
{
colType = colliderType.box;
boxCol = (BoxCollider)_myTransform.GetComponent(typeof(BoxCollider));
}
else if (_myTransform.GetComponent<Collider>().GetType() == typeof(SphereCollider))
{
colType = colliderType.sphere;
sphereCol = (SphereCollider)_myTransform.GetComponent(typeof(SphereCollider));
}
else if (_myTransform.GetComponent<Collider>().GetType() == typeof(MeshCollider))
{
colType = colliderType.mesh;
}
else
{
Debug.Log("Collider Type not supported. Please submit bug report.");
colType = colliderType.notSupported;
}
}
//we need to add a slight delay to our lower levels break objects method so that they aren't denied the ability to break from
//the FPS controller singleton while FPS is low. Only called if we're breaking from an external script through the
//explode or break methods
if (passDownBreakage) {
Invoke ("BreakObjectHelper", 0.1f);
}
}
virtual protected void Update ()
{
if (scaleCol) {
ScaleCollider ();
}
if (_deleteable) {
CheckForRemoval ();
}
}
#region breaking methods
/*
* These methods are used if you want to break an object using an outside script ie. explosion controller
* or fracture by raycast
* */
#region CallableFractureMethods
/// <summary>
/// Breaks the object. Useful for circumstances where the object needs to break but the collider will not interact
/// with anything, such as magic or explosions. DLEnabled is passed from lower levels
/// </summary>
virtual public void breakObject (bool b)
{
if (b && canBreak) {
passDownBreakage = true;
_myRigidbody.isKinematic = false;
_breaker = true;
SpawnChild ();
}
}
//breaks the object and adds a world force to it
virtual public void breakObject (bool b, Vector3 force)
{
if (b && canBreak) {
_myRigidbody.isKinematic = false;
_myRigidbody.velocity += force;
breakObject (b);
}
}
//breaks the object and adds a world force and torque to it
virtual public void breakObject (bool b, Vector3 force, Vector3 rotation)
{
if (b && canBreak) {
_myRigidbody.isKinematic = false;
_myRigidbody.angularVelocity += rotation;
breakObject (b, force);
}
}
void BreakObjectHelper ()
{
breakObject (true);
}
#endregion
#region CallableExplosionMethods
public void explodeObject ()
{
if (_CanExplode) {
_physicsController.PopExplosionSphere (_myTransform.position);
_myTransform.GetComponent<PhysicsController_Child> ().breakObject (true);
if (_physicsController.explosionSound != null) {
AudioSource.PlayClipAtPoint (_physicsController.explosionSound, _myTransform.position, _physicsController.audioVolume);
}
_CanExplode = false;
}
}
#endregion
//having the breaker prevents multiple instances of DL1 from being created
virtual protected void OnCollisionEnter (Collision col)
{
if (!_breaker && canBreak && !preventBreaking) {
if (_PhysicsController.CanGameObjectDestroyBreakableObject (col.gameObject)) {
float collisionForce = GetImpactForce (col);
//If the force is strong enough, break the block and average fps is above minimum framerate
if ((collisionForce > breakStrength) || (_PassDownContactForce > breakStrength)) {
_PassDownContactForce = collisionForce;
_breaker = true;
SpawnChild ();
}
}
}
}
//special case for colliding with character controllers which require a trigger and cannot be used to calculate physics
public void animationBreak(Collider col)
{
if (!_breaker && playerCanBreak && !preventBreaking) {
_breaker = true;
SpawnChild();
}
}
//special case for colliding with character controllers which require a trigger and cannot be used to calculate physics
virtual public void OnTriggerEnter (Collider col)
{
if (!_breaker && canBreak && playerCanBreak && !preventBreaking) {
if (col.gameObject.tag.Equals ("Player")) {
_breaker = true;
SpawnChild ();
}
}
}
#endregion
/// <summary>
/// Spawns the child of the master object, passes the nessesary values to the rigidbody and kills itself
/// scale is passed from DL0 to DL1 Master, and from DL2 Master to DL2 objects
/// everywhere else scale is passed due to parent child relationship
/// </summary>
virtual protected void SpawnChild ()
{
_DLMaster.gameObject.SetActive (true);
_DLMaster.GetTransform().localScale = _myTransform.localScale;
_DLMaster.GetTransform().rotation = _myTransform.rotation;
_DLMaster.GetTransform().position = _myTransform.position;
_DLMaster.playerCanBreak = playerCanBreak;
_DLMaster.GetRigidbody().velocity = _myRigidbody.velocity;
_DLMaster.GetRigidbody().angularVelocity = _myRigidbody.angularVelocity;
_DLMaster._PhysicsController = _physicsController;
_DLMaster.GetRigidbody().mass = _myRigidbody.mass;
_DLMaster.passDownBreakage = passDownBreakage;
_DLMaster.PassDownContactForce = _PassDownContactForce;
_DLMaster.EnableChildren ();
BreakAndDestroy ();
}
public void ScaleCollider ()
{
if (colType == colliderType.box) {
if (boxCol.size.x < _finalScale.x)
{
boxCol.size = Vector3.Lerp(boxCol.size, _finalScale, Time.deltaTime * scaleTime);
} else {
scaleCol = false;
}
}
else if (colType == colliderType.sphere)
{
if (sphereCol.radius < _finalScale.x) {
sphereCol.radius = Mathf.Lerp(sphereCol.radius, _finalScale.x, Time.deltaTime * scaleTime);
} else {
scaleCol = false;
}
}
else if (colType == colliderType.mesh)
{
//MeshColliders don't scale";
scaleCol = false;
} else {
Debug.Log ("Scale collider was called on a collider type that is not supported. Please submit bug report.");
}
}
public void PlayParticleSystem ()
{
if (Time.time > _physicsController.ParticleSystemDelayTime) {
_physicsController.ParticleSystemDelayTime = Time.time + 0.5f;
Transform go = Instantiate (_physicsController.breakParticleSystem, _myTransform.position,
_myTransform.rotation) as Transform;
Destroy (go.gameObject, _physicsController.particleSystemLifetime);
}
}
public void PlayBreakingSound ()
{
if (FPSController_Singleton.Instance.CanPlayBreakingSound ()) {
//Gets a random clip from the physics controller
int audioClipNumber = (int)Mathf.Round (Random.Range (0, _physicsController.breakSounds.Length));
_AudioClipToPlay = _physicsController.breakSounds [audioClipNumber];
AudioSource.PlayClipAtPoint(_AudioClipToPlay, _myTransform.position, 100);//_physicsController.audioVolume);
}
}
void SetMass (int cargoMass)
{
GetComponent<Rigidbody>().mass += cargoMass;
}
protected override void SetMaterials ()
{
base.SetMaterials ();
if (_physicsController.overrideMaterials) {
if (GetComponent<Renderer>() != null) {
Material[] tempMats = new Material[1];
;
if (GetComponent<Renderer>().materials.Length == 1) {
tempMats [0] = _physicsController.outsideMaterial;
} else if (GetComponent<Renderer>().materials.Length == 2) {
tempMats = new Material[2];
if (_FlipMaterials) {
tempMats [1] = _physicsController.outsideMaterial;
tempMats [0] = _physicsController.insideMaterial;
} else {
tempMats [0] = _physicsController.outsideMaterial;
tempMats [1] = _physicsController.insideMaterial;
}
} else if (GetComponent<Renderer>().materials.Length == 3) {
tempMats = new Material[3];
tempMats [0] = _physicsController.outsideMaterial;
tempMats [1] = _physicsController.insideMaterial;
tempMats [2] = _physicsController.outsideMaterial;
}
GetComponent<Renderer>().materials = tempMats;
}
}
}
protected enum colliderType
{
box,
sphere,
mesh,
notSupported,
nullCollider
};
}
| |
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Rhino.Licensing
{
/// <summary>
///
/// </summary>
public class SntpClient
{
private const byte SntpDataLength = 48;
private readonly string[] hosts;
private int index = -1;
/// <summary>
///
/// </summary>
/// <param name="hosts"></param>
public SntpClient(string[] hosts)
{
this.hosts = hosts;
}
private static bool GetIsServerMode(byte[] sntpData)
{
return (sntpData[0] & 0x7) == 4 /* server mode */;
}
private static DateTime GetTransmitTimestamp(byte[] sntpData)
{
var milliSeconds = GetMilliSeconds(sntpData, 40);
return ComputeDate(milliSeconds);
}
private static DateTime ComputeDate(ulong milliseconds)
{
return new DateTime(1900, 1, 1).Add(TimeSpan.FromMilliseconds(milliseconds));
}
private static ulong GetMilliSeconds(byte[] sntpData, byte offset)
{
ulong intpart = 0, fractpart = 0;
for (var i = 0; i <= 3; i++)
{
intpart = 256*intpart + sntpData[offset + i];
}
for (var i = 4; i <= 7; i++)
{
fractpart = 256*fractpart + sntpData[offset + i];
}
var milliseconds = intpart*1000 + (fractpart*1000)/0x100000000L;
return milliseconds;
}
/// <summary>
///
/// </summary>
/// <param name="getTime"></param>
/// <param name="failure"></param>
public void BeginGetDate(Action<DateTime> getTime, Action failure)
{
index += 1;
if (hosts.Length <= index)
{
if (hosts.Length == index)
{
failure();
}
return;
}
try
{
var host = hosts[index];
var state = new State(null, null, getTime, failure);
var result = Dns.BeginGetHostAddresses(host, EndGetHostAddress, state );
RegisterWaitForTimeout(state, result);
}
catch (Exception)
{
// retry, recursion stops at the end of the hosts
BeginGetDate(getTime, failure);
}
}
private void EndGetHostAddress(IAsyncResult asyncResult)
{
var state = (State) asyncResult.AsyncState;
try
{
var addresses = Dns.EndGetHostAddresses(asyncResult);
var endPoint = new IPEndPoint(addresses[0], 123);
var socket = new UdpClient();
socket.Connect(endPoint);
socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500);
var sntpData = new byte[SntpDataLength];
sntpData[0] = 0x1B; // version = 4 & mode = 3 (client)
var newState = new State(socket, endPoint, state.GetTime, state.Failure);
var result = socket.BeginSend(sntpData, sntpData.Length, EndSend, newState);
RegisterWaitForTimeout(newState, result);
}
catch (Exception)
{
// retry, recursion stops at the end of the hosts
BeginGetDate(state.GetTime, state.Failure);
}
}
private void RegisterWaitForTimeout(State newState, IAsyncResult result)
{
if(result != null)
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, MaybeOperationTimeout, newState, 500, true);
}
private void MaybeOperationTimeout(object state, bool timedOut)
{
if (timedOut == false)
return;
var theState = (State)state;
try
{
if (theState.Socket != null)
{
theState.Socket.Close();
}
}
catch (Exception)
{
// retry, recursion stops at the end of the hosts
BeginGetDate(theState.GetTime, theState.Failure);
}
}
private void EndSend(IAsyncResult ar)
{
var state = (State) ar.AsyncState;
try
{
state.Socket.EndSend(ar);
var result = state.Socket.BeginReceive(EndReceive, state);
RegisterWaitForTimeout(state, result);
}
catch
{
state.Socket.Close();
BeginGetDate(state.GetTime, state.Failure);
}
}
private void EndReceive(IAsyncResult ar)
{
var state = (State) ar.AsyncState;
try
{
var endPoint = state.EndPoint;
var sntpData = state.Socket.EndReceive(ar, ref endPoint);
if(IsResponseValid(sntpData)==false)
{
state.Failure();
return;
}
var transmitTimestamp = GetTransmitTimestamp(sntpData);
state.GetTime(transmitTimestamp);
}
catch
{
BeginGetDate(state.GetTime, state.Failure);
}
finally
{
state.Socket.Close();
}
}
private bool IsResponseValid(byte[] sntpData)
{
return sntpData.Length >= SntpDataLength && GetIsServerMode(sntpData);
}
#region Nested type: State
private class State
{
public State(UdpClient socket, IPEndPoint endPoint, Action<DateTime> getTime, Action failure)
{
Socket = socket;
EndPoint = endPoint;
GetTime = getTime;
Failure = failure;
}
public UdpClient Socket { get; private set; }
public Action<DateTime> GetTime { get; private set; }
public Action Failure { get; private set; }
public IPEndPoint EndPoint { get; private set; }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Enyim.Caching;
using Enyim.Caching.Configuration;
using Enyim.Caching.Memcached;
namespace DemoApp
{
class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
var mbcc = new MembaseClientConfiguration();
mbcc.SocketPool.ReceiveTimeout = new TimeSpan(0, 0, 2);
mbcc.SocketPool.DeadTimeout = new TimeSpan(0, 0, 10);
mbcc.Urls.Add(new Uri("http://localhost:8091/pools/default"));
var client = new MembaseClient(mbcc);
var item1 = client.Cas(StoreMode.Set, "item1", 1);
var item2 = client.Cas(StoreMode.Set, "item2", 2);
var add1 = client.Cas(StoreMode.Add, "item1", 4);
Console.WriteLine(add1.Result);
Console.WriteLine(add1.Cas);
Console.WriteLine(add1.StatusCode);
Console.WriteLine("item1 = " + item1.Cas);
Console.WriteLine("item2 = " + item2.Cas);
Console.WriteLine("Go?");
Console.ReadLine();
var mre = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(o =>
{
mre.WaitOne();
Console.WriteLine("Waiting before change 1");
Thread.Sleep(4000);
Console.WriteLine("item1 overwrite = " + client.Cas(StoreMode.Set, "item1", 4, item1.Cas).Result);
Console.WriteLine("Waiting before change 2");
Thread.Sleep(4000);
Console.WriteLine("item2 overwrite = " + client.Cas(StoreMode.Set, "item2", 4, item2.Cas).Result);
});
//mre.Set();
//client.Sync("item1", item1.Cas, SyncMode.Mutation);
client.Sync(SyncMode.Mutation, new[] { new KeyValuePair<string, ulong>("item1", item1.Cas), new KeyValuePair<string, ulong>("item2", item2.Cas) });
Console.WriteLine("Changed");
Console.ReadLine();
////nscc.PerformanceMonitorFactory = new Membase.Configuration.DefaultPerformanceMonitorFactory();
////nscc.BucketPassword = "pass";
////ThreadPool.QueueUserWorkItem(o => StressTest(new MembaseClient(nscc), "TesT_A_"));
////ThreadPool.QueueUserWorkItem(o => StressTest(new MembaseClient("content", "content"), "TesT_B_"));
////ThreadPool.QueueUserWorkItem(o => StressTest(new MembaseClient(nscc, "default"), "TesT_B_"));
////ThreadPool.QueueUserWorkItem(o => StressTest(new MembaseClient(nscc, "default"), "TesT_C_"));
////ThreadPool.QueueUserWorkItem(o => StressTest(new MembaseClient(nscc, "default"), "TesT_D_"));
//Console.ReadLine();
//return;
//var mcc = new MemcachedClientConfiguration();
//mcc.AddServer("192.168.2.200:11211");
//mcc.AddServer("192.168.2.202:11211");
//mcc.SocketPool.ReceiveTimeout = new TimeSpan(0, 0, 4);
//mcc.SocketPool.ConnectionTimeout = new TimeSpan(0, 0, 4);
//mcc.SocketPool.DeadTimeout = new TimeSpan(0, 0, 10);
//StressTest(new MemcachedClient(mcc), "TesT_");
//return;
//var nc = new MembaseClient(nscc, "content", "content");
//var stats1 = nc.Stats("slabs");
//foreach (var kvp in stats1.GetRaw("curr_connections"))
// Console.WriteLine("{0} -> {1}", kvp.Key, kvp.Value);
//var nc2 = new MembaseClient(nscc, "content", "content");
//var stats2 = nc2.Stats();
//foreach (var kvp in stats2.GetRaw("curr_connections"))
// Console.WriteLine("{0} -> {1}", kvp.Key, kvp.Value);
}
private static void MultigetSpeedTest()
{
//Enyim.Caching.LogManager.AssignFactory(new ConsoleLogFactory());
var tmc = new MemcachedClientConfiguration();
tmc.AddServer("172.16.203.2:11211");
tmc.AddServer("172.16.203.2:11212");
//tmc.AddServer("172.16.203.2:11213");
//tmc.AddServer("172.16.203.2:11214");
tmc.Protocol = MemcachedProtocol.Binary;
//tmc.SocketPool.MinPoolSize = 1;
//tmc.SocketPool.MaxPoolSize = 1;
tmc.SocketPool.ReceiveTimeout = new TimeSpan(0, 0, 4);
tmc.SocketPool.ConnectionTimeout = new TimeSpan(0, 0, 4);
tmc.KeyTransformer = new DefaultKeyTransformer();
var tc = new MemcachedClient(tmc);
const string KeyPrefix = "asdfghjkl";
var val = new byte[10 * 1024];
val[val.Length - 1] = 1;
for (var i = 0; i < 100; i++)
if (!tc.Store(StoreMode.Set, KeyPrefix + i, val))
Console.WriteLine("Fail " + KeyPrefix + i);
var keys = Enumerable.Range(0, 500).Select(k => KeyPrefix + k).ToArray();
Console.WriteLine("+");
var sw = Stopwatch.StartNew();
//tc.Get(KeyPrefix + "4");
//sw.Stop();
//Console.WriteLine(sw.ElapsedMilliseconds);
//sw = Stopwatch.StartNew();
//var p = tc.Get2(keys);
//sw.Stop();
//Console.WriteLine(sw.ElapsedMilliseconds);
//sw = Stopwatch.StartNew();
//var t = tc.Get(keys);
//Console.WriteLine(" --" + t.Count);
//sw.Stop();
//Console.WriteLine(sw.ElapsedMilliseconds);
//Console.WriteLine("Waiting");
//Console.ReadLine();
//return;
for (var i = 0; i < 100; i++)
{
const int MAX = 300;
sw = Stopwatch.StartNew();
for (var j = 0; j < MAX; j++) tc.Get(keys);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
//sw = Stopwatch.StartNew();
//for (var j = 0; j < MAX; j++) tc.GetOld(keys);
//sw.Stop();
//Console.WriteLine(sw.ElapsedMilliseconds);
//sw = Stopwatch.StartNew();
//for (var j = 0; j < MAX; j++)
// foreach (var k in keys) tc.Get(k);
//sw.Stop();
//Console.WriteLine(sw.ElapsedMilliseconds);
Console.WriteLine("----");
}
Console.ReadLine();
return;
}
private static void StressTest(MemcachedClient client, string keyPrefix)
{
var i = 0;
var last = true;
var progress = @"-\|/".ToCharArray();
Console.CursorVisible = false;
Dictionary<bool, int> counters = new Dictionary<bool, int>() { { true, 0 }, { false, 0 } };
while (true)
{
var key = keyPrefix + i;
var state = client.Store(StoreMode.Set, key, i) & client.Get<int>(key) == i;
Action updateTitle = () => Console.Title = "Success: " + counters[true] + " Fail: " + counters[false];
if (state != last)
{
Console.ForegroundColor = state ? ConsoleColor.White : ConsoleColor.Red;
Console.Write(".");
counters[state] = 0;
last = state;
updateTitle();
}
else if (i % 200 == 0)
{
//Console.ForegroundColor = state ? ConsoleColor.White : ConsoleColor.Red;
//Console.Write(progress[(i / 200) % 4]);
//if (Console.CursorLeft == 0)
//{
// Console.CursorLeft = Console.WindowWidth - 1;
// Console.CursorTop -= 1;
//}
//else
//{
// Console.CursorLeft -= 1;
//}
updateTitle();
}
i++;
counters[state] = counters[state] + 1;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type float with 2 columns and 4 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct mat2x4 : IEnumerable<float>, IEquatable<mat2x4>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public float m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public float m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
public float m02;
/// <summary>
/// Column 0, Rows 3
/// </summary>
public float m03;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public float m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public float m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
public float m12;
/// <summary>
/// Column 1, Rows 3
/// </summary>
public float m13;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public mat2x4(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m03 = m03;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
this.m13 = m13;
}
/// <summary>
/// Constructs this matrix from a mat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a mat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a mat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(vec2 c0, vec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = 0f;
this.m03 = 0f;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = 0f;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(vec3 c0, vec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = 0f;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(vec4 c0, vec4 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = c0.w;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = c1.w;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public float[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public float[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public vec4 Column0
{
get
{
return new vec4(m00, m01, m02, m03);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
m03 = value.w;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public vec4 Column1
{
get
{
return new vec4(m10, m11, m12, m13);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
m13 = value.w;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public vec2 Row0
{
get
{
return new vec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public vec2 Row1
{
get
{
return new vec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public vec2 Row2
{
get
{
return new vec2(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 3
/// </summary>
public vec2 Row3
{
get
{
return new vec2(m03, m13);
}
set
{
m03 = value.x;
m13 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static mat2x4 Zero { get; } = new mat2x4(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static mat2x4 Ones { get; } = new mat2x4(1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static mat2x4 Identity { get; } = new mat2x4(1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static mat2x4 AllMaxValue { get; } = new mat2x4(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static mat2x4 DiagonalMaxValue { get; } = new mat2x4(float.MaxValue, 0f, 0f, 0f, 0f, float.MaxValue, 0f, 0f);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static mat2x4 AllMinValue { get; } = new mat2x4(float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static mat2x4 DiagonalMinValue { get; } = new mat2x4(float.MinValue, 0f, 0f, 0f, 0f, float.MinValue, 0f, 0f);
/// <summary>
/// Predefined all-Epsilon matrix
/// </summary>
public static mat2x4 AllEpsilon { get; } = new mat2x4(float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon);
/// <summary>
/// Predefined diagonal-Epsilon matrix
/// </summary>
public static mat2x4 DiagonalEpsilon { get; } = new mat2x4(float.Epsilon, 0f, 0f, 0f, 0f, float.Epsilon, 0f, 0f);
/// <summary>
/// Predefined all-NaN matrix
/// </summary>
public static mat2x4 AllNaN { get; } = new mat2x4(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN);
/// <summary>
/// Predefined diagonal-NaN matrix
/// </summary>
public static mat2x4 DiagonalNaN { get; } = new mat2x4(float.NaN, 0f, 0f, 0f, 0f, float.NaN, 0f, 0f);
/// <summary>
/// Predefined all-NegativeInfinity matrix
/// </summary>
public static mat2x4 AllNegativeInfinity { get; } = new mat2x4(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
/// <summary>
/// Predefined diagonal-NegativeInfinity matrix
/// </summary>
public static mat2x4 DiagonalNegativeInfinity { get; } = new mat2x4(float.NegativeInfinity, 0f, 0f, 0f, 0f, float.NegativeInfinity, 0f, 0f);
/// <summary>
/// Predefined all-PositiveInfinity matrix
/// </summary>
public static mat2x4 AllPositiveInfinity { get; } = new mat2x4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
/// <summary>
/// Predefined diagonal-PositiveInfinity matrix
/// </summary>
public static mat2x4 DiagonalPositiveInfinity { get; } = new mat2x4(float.PositiveInfinity, 0f, 0f, 0f, 0f, float.PositiveInfinity, 0f, 0f);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<float> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m03;
yield return m10;
yield return m11;
yield return m12;
yield return m13;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 4 = 8).
/// </summary>
public int Count => 8;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public float this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m03;
case 4: return m10;
case 5: return m11;
case 6: return m12;
case 7: return m13;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m03 = value; break;
case 4: this.m10 = value; break;
case 5: this.m11 = value; break;
case 6: this.m12 = value; break;
case 7: this.m13 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public float this[int col, int row]
{
get
{
return this[col * 4 + row];
}
set
{
this[col * 4 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(mat2x4 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is mat2x4 && Equals((mat2x4) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(mat2x4 lhs, mat2x4 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(mat2x4 lhs, mat2x4 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m03.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m13.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public mat4x2 Transposed => new mat4x2(m00, m10, m01, m11, m02, m12, m03, m13);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public float MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m03), m10), m11), m12), m13);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public float MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m03), m10), m11), m12), m13);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public float LengthSqr => (((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public float Sum => (((m00 + m01) + (m02 + m03)) + ((m10 + m11) + (m12 + m13)));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public float Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m02) + Math.Abs(m03))) + ((Math.Abs(m10) + Math.Abs(m11)) + (Math.Abs(m12) + Math.Abs(m13))));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public float NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m03)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m13));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m02), p) + Math.Pow((double)Math.Abs(m03), p))) + ((Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p)) + (Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m13), p)))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication mat2x4 * mat2 -> mat2x4.
/// </summary>
public static mat2x4 operator*(mat2x4 lhs, mat2 rhs) => new mat2x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication mat2x4 * mat3x2 -> mat3x4.
/// </summary>
public static mat3x4 operator*(mat2x4 lhs, mat3x2 rhs) => new mat3x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication mat2x4 * mat4x2 -> mat4.
/// </summary>
public static mat4 operator*(mat2x4 lhs, mat4x2 rhs) => new mat4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31), (lhs.m03 * rhs.m30 + lhs.m13 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static vec4 operator*(mat2x4 m, vec2 v) => new vec4((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y), (m.m03 * v.x + m.m13 * v.y));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static mat2x4 CompMul(mat2x4 A, mat2x4 B) => new mat2x4(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m03 * B.m03, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m13 * B.m13);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static mat2x4 CompDiv(mat2x4 A, mat2x4 B) => new mat2x4(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m03 / B.m03, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m13 / B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat2x4 CompAdd(mat2x4 A, mat2x4 B) => new mat2x4(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m03 + B.m03, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m13 + B.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat2x4 CompSub(mat2x4 A, mat2x4 B) => new mat2x4(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m03 - B.m03, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m13 - B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat2x4 operator+(mat2x4 lhs, mat2x4 rhs) => new mat2x4(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m03 + rhs.m03, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m13 + rhs.m13);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat2x4 operator+(mat2x4 lhs, float rhs) => new mat2x4(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m03 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m13 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat2x4 operator+(float lhs, mat2x4 rhs) => new mat2x4(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m03, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat2x4 operator-(mat2x4 lhs, mat2x4 rhs) => new mat2x4(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m03 - rhs.m03, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m13 - rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat2x4 operator-(mat2x4 lhs, float rhs) => new mat2x4(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m03 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m13 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat2x4 operator-(float lhs, mat2x4 rhs) => new mat2x4(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m03, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m13);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat2x4 operator/(mat2x4 lhs, float rhs) => new mat2x4(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m03 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m13 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat2x4 operator/(float lhs, mat2x4 rhs) => new mat2x4(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m03, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m13);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat2x4 operator*(mat2x4 lhs, float rhs) => new mat2x4(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m03 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat2x4 operator*(float lhs, mat2x4 rhs) => new mat2x4(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m03, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m13);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat2x4 operator<(mat2x4 lhs, mat2x4 rhs) => new bmat2x4(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m03 < rhs.m03, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m13 < rhs.m13);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator<(mat2x4 lhs, float rhs) => new bmat2x4(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m03 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m13 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator<(float lhs, mat2x4 rhs) => new bmat2x4(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m03, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m13);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat2x4 operator<=(mat2x4 lhs, mat2x4 rhs) => new bmat2x4(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m03 <= rhs.m03, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m13 <= rhs.m13);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator<=(mat2x4 lhs, float rhs) => new bmat2x4(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m03 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m13 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator<=(float lhs, mat2x4 rhs) => new bmat2x4(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m03, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m13);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat2x4 operator>(mat2x4 lhs, mat2x4 rhs) => new bmat2x4(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m03 > rhs.m03, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m13 > rhs.m13);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator>(mat2x4 lhs, float rhs) => new bmat2x4(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m03 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m13 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator>(float lhs, mat2x4 rhs) => new bmat2x4(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m03, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m13);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat2x4 operator>=(mat2x4 lhs, mat2x4 rhs) => new bmat2x4(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m03 >= rhs.m03, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m13 >= rhs.m13);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator>=(mat2x4 lhs, float rhs) => new bmat2x4(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m03 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m13 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator>=(float lhs, mat2x4 rhs) => new bmat2x4(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m03, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m13);
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
// Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com)
// David Stephensen (mailto:David.Stephensen@pdfsharp.com)
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using MigraDoc.DocumentObjectModel.Internals;
namespace MigraDoc.DocumentObjectModel.Shapes
{
/// <summary>
/// Represents an image in the document or paragraph.
/// </summary>
public class Image : Shape
{
/// <summary>
/// Initializes a new instance of the Image class.
/// </summary>
public Image()
{
}
public Image(MemoryStream imageStream) : this(string.Empty)
{
ImageStream = imageStream; // Added new property to hold the stream
}
/// <summary>
/// Initializes a new instance of the Image class with the specified parent.
/// </summary>
internal Image(DocumentObject parent) : base(parent) { }
/// <summary>
/// Initializes a new instance of the Image class from the specified (file) name.
/// </summary>
public Image(string name)
: this()
{
Name = name;
}
public MemoryStream ImageStream { get; set; }
public bool IsStreamBased
{
get { return ImageStream != null; }
}
//#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new Image Clone()
{
return (Image)DeepCopy();
}
/// <summary>
/// Implements the deep copy of the object.
/// </summary>
protected override object DeepCopy()
{
Image image = (Image)base.DeepCopy();
if (image.pictureFormat != null)
{
image.pictureFormat = image.pictureFormat.Clone();
image.pictureFormat.parent = image;
}
return image;
}
//#endregion
//#region Properties
/// <summary>
/// Gets or sets the name of the image.
/// </summary>
public string Name
{
get { return this.name.Value; }
set { this.name.Value = value; }
}
[DV]
internal NString name = NString.NullValue;
/// <summary>
/// Gets or sets the ScaleWidth of the image.
/// If the Width is set to, the resulting image width is ScaleWidth * Width.
/// </summary>
public double ScaleWidth
{
get { return this.scaleWidth.Value; }
set { this.scaleWidth.Value = value; }
}
[DV]
internal NDouble scaleWidth = NDouble.NullValue;
/// <summary>
/// Gets or sets the ScaleHeight of the image.
/// If the Height is set too, the resulting image height is ScaleHeight * Height.
/// </summary>
public double ScaleHeight
{
get { return this.scaleHeight.Value; }
set { this.scaleHeight.Value = value; }
}
[DV]
internal NDouble scaleHeight = NDouble.NullValue;
/// <summary>
/// Gets or sets whether the AspectRatio of the image is kept unchanged.
/// If both Width and Height are set, this property is ignored.
/// </summary>
public bool LockAspectRatio
{
get { return this.lockAspectRatio.Value; }
set { this.lockAspectRatio.Value = value; }
}
[DV]
internal NBool lockAspectRatio = NBool.NullValue;
/// <summary>
/// Gets or sets the PictureFormat for the image
/// </summary>
public PictureFormat PictureFormat
{
get
{
if (this.pictureFormat == null)
this.pictureFormat = new PictureFormat(this);
return this.pictureFormat;
}
set
{
SetParent(value);
this.pictureFormat = value;
}
}
[DV]
internal PictureFormat pictureFormat;
/// <summary>
/// Gets or sets a user defined resolution for the image in dots per inch.
/// </summary>
public double Resolution
{
get { return this.resolution.Value; }
set { this.resolution.Value = value; }
}
[DV]
internal NDouble resolution = NDouble.NullValue;
//#endregion
#region Internal
/// <summary>
/// Converts Image into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
serializer.WriteLine("\\image(\"" + this.name.Value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\")");
int pos = serializer.BeginAttributes();
base.Serialize(serializer);
if (!this.scaleWidth.IsNull)
serializer.WriteSimpleAttribute("ScaleWidth", this.ScaleWidth);
if (!this.scaleHeight.IsNull)
serializer.WriteSimpleAttribute("ScaleHeight", this.ScaleHeight);
if (!this.lockAspectRatio.IsNull)
serializer.WriteSimpleAttribute("LockAspectRatio", this.LockAspectRatio);
if (!this.resolution.IsNull)
serializer.WriteSimpleAttribute("Resolution", this.Resolution);
if (!this.IsNull("PictureFormat"))
this.pictureFormat.Serialize(serializer);
serializer.EndAttributes(pos);
}
/// <summary>
/// Gets the concrete image path, taking into account the DOM document's DdlFile and
/// ImagePath properties as well as the given working directory (which can be null).
/// </summary>
public string GetFilePath(string workingDir)
{
string filePath = "";
try
{
if (!String.IsNullOrEmpty(workingDir))
filePath = workingDir;
else
filePath = Directory.GetCurrentDirectory() + "\\";
if (!Document.IsNull("ImagePath"))
{
string foundfile = ImageHelper.GetImageName(filePath, this.Name, Document.ImagePath);
if (foundfile != null)
filePath = foundfile;
else
filePath = Path.Combine(filePath, Name);
}
else
filePath = Path.Combine(filePath, Name);
}
catch (Exception ex)
{
Debug.Assert(false, "Should never occur with properly formatted Wiki texts. " + ex);
return null;
//throw;
}
return filePath;
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get
{
if (meta == null)
meta = new Meta(typeof(Image));
return meta;
}
}
static Meta meta;
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Net;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb;
using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi;
using Microsoft.Protocols.TestTools.StackSdk.Transport;
namespace Microsoft.Protocols.TestTools.StackSdk.Networking.Rpce
{
internal delegate void SmbSendFunc();
/// <summary>
/// Describes the session of RPCE connection.
/// </summary>
public class RpceServerSessionContext : RpceContext
{
#region Field members
// RPC network address and endPort of client
private object remoteEndpoint;
//RPCE server context.
private RpceServerContext serverContext;
//Call id list for the connection.
private List<uint> outstandingCalls;
private IntPtr handle;
//Associate Group ID list
private List<uint> associateGroupIdList;
//SMB/SMB2 connection and open
internal IFileServiceServerConnection fsConnection;
internal IFileServiceServerOpen fsOpen;
//Buffer for multiple SMB READ/WRITE requests/responses.
internal byte[] smbBufferReceiving = new byte[0];
internal byte[] smbBufferSending = new byte[0];
internal object smbSendingLocker = new object();
internal int smbMaxSendingLength;
internal SmbSendFunc smbSendingFunc;
#endregion
#region ctor
/// <summary>
/// Initialize Rpce server context
/// </summary>
/// <param name="serverContext">The rpce server context.</param>
/// <param name="remoteEndpoint">Remote endpoint.</param>
internal RpceServerSessionContext(
RpceServerContext serverContext,
object remoteEndpoint)
: base()
{
this.serverContext = serverContext;
this.ProtocolSequence = serverContext.ProtocolSequence;
this.RpcVersionMajor = serverContext.RpcVersionMajor;
this.RpcVersionMinor = serverContext.RpcVersionMinor;
// Make handle always different.
handle = new IntPtr(Environment.TickCount);
this.remoteEndpoint = remoteEndpoint;
this.outstandingCalls = new List<uint>();
this.associateGroupIdList = new List<uint>();
}
#endregion
#region properties
/// <summary>
/// Call ID collection for the connection.
/// </summary>
public ReadOnlyCollection<uint> OutstandingCalls
{
get
{
return new ReadOnlyCollection<uint>(this.outstandingCalls);
}
}
/// <summary>
/// Remote Endpoint.
/// </summary>
public object RemoteEndpoint
{
get
{
return this.remoteEndpoint;
}
}
/// <summary>
/// The RPCE server context.
/// </summary>
public RpceServerContext ServerContext
{
get
{
return this.serverContext;
}
}
/// <summary>
/// The RPCE server context
/// </summary>
public IntPtr Handle
{
get
{
return handle;
}
}
/// <summary>
/// Security provider (SSPI).
/// </summary>
public new SecurityContext SecurityContext
{
get
{
return base.SecurityContext;
}
set
{
base.SecurityContext = value;
}
}
/// <summary>
/// Context of underlayer named pipe transport (SMB/SMB2).
/// User should cast return value to SmbServerOpen or Smb2ServerOpen.
/// If RPCE is using TCP as its transport, this property returns null.
/// If underlayer named pipe transport is closed, this property returns null.
/// </summary>
public IFileServiceServerOpen FileServiceTransportOpen
{
get
{
return fsOpen;
}
}
#endregion
#region Update SessionContext
/// <summary>
/// update context on sending PDU.
/// </summary>
/// <param name="pdu">PDU to send.</param>
internal void UpdateContextOnSendingPdu(RpcePdu pdu)
{
RpceCoPdu coPdu = pdu as RpceCoPdu;
if (coPdu == null)
{
return;
}
this.RpcVersionMajor = coPdu.rpc_vers;
this.RpcVersionMinor = coPdu.rpc_vers_minor;
if (coPdu.PTYPE == RpcePacketType.Bind ||
coPdu.PTYPE == RpcePacketType.BindAck ||
coPdu.PTYPE == RpcePacketType.AlterContext ||
coPdu.PTYPE == RpcePacketType.AlterContextResp)
{
this.SupportsHeaderSign
= (coPdu.pfc_flags & RpceCoPfcFlags.PFC_SUPPORT_HEADER_SIGN)
== RpceCoPfcFlags.PFC_SUPPORT_HEADER_SIGN;
}
this.SupportsConcurrentMultiplexing
= (coPdu.pfc_flags & RpceCoPfcFlags.PFC_CONC_MPX)
== RpceCoPfcFlags.PFC_CONC_MPX;
this.PackedDataRepresentationFormat = coPdu.packed_drep.dataRepFormat;
if (coPdu.PTYPE != RpcePacketType.Request)
{
this.outstandingCalls.Remove(coPdu.call_id);
}
switch (coPdu.PTYPE)
{
case RpcePacketType.BindAck:
RpceCoBindAckPdu bindAckPdu = coPdu as RpceCoBindAckPdu;
if (bindAckPdu != null)
{
UpdateContextOnSendingBindAckPdu(bindAckPdu);
}
break;
case RpcePacketType.Request:
RpceCoRequestPdu requestPdu = coPdu as RpceCoRequestPdu;
if (requestPdu != null)
{
this.ContextIdentifier = requestPdu.p_cont_id;
}
break;
case RpcePacketType.Response:
RpceCoResponsePdu responsePdu = coPdu as RpceCoResponsePdu;
if (responsePdu != null)
{
this.ContextIdentifier = responsePdu.p_cont_id;
}
break;
case RpcePacketType.BindNak:
case RpcePacketType.AlterContextResp:
case RpcePacketType.Fault:
case RpcePacketType.Shutdown:
default:
//default situation should do nothing.
//This is just update the context, if we cannot recognize the PDU, ignore it.
break;
}
}
/// <summary>
/// update context on sending RPCE CO BindAck PDU.
/// </summary>
/// <param name="bindAckPdu">BindAck PDU to send.</param>
internal void UpdateContextOnSendingBindAckPdu(RpceCoBindAckPdu bindAckPdu)
{
this.MaxTransmitFragmentSize = bindAckPdu.max_xmit_frag;
this.MaxReceiveFragmentSize = bindAckPdu.max_recv_frag;
this.AssociateGroupId = bindAckPdu.assoc_group_id;
if (bindAckPdu.sec_addr.port_spec != null)
{
this.SecondaryAddress
= Encoding.ASCII.GetString(bindAckPdu.sec_addr.port_spec);
}
if (bindAckPdu.p_result_list.p_results != null)
{
this.NdrVersion = RpceNdrVersion.None;
for (int i = 0; i < bindAckPdu.p_result_list.p_results.Length; i++)
{
p_result_t p_result = bindAckPdu.p_result_list.p_results[i];
if (p_result.result == p_cont_def_result_t.acceptance)
{
if (p_result.transfer_syntax.if_uuid == RpceUtility.NDR_INTERFACE_UUID
&&
p_result.transfer_syntax.if_vers_major == RpceUtility.NDR_INTERFACE_MAJOR_VERSION
&&
p_result.transfer_syntax.if_vers_minor == RpceUtility.NDR_INTERFACE_MINOR_VERSION)
{
this.NdrVersion |= RpceNdrVersion.NDR;
}
else if (p_result.transfer_syntax.if_uuid == RpceUtility.NDR64_INTERFACE_UUID
&&
p_result.transfer_syntax.if_vers_major == RpceUtility.NDR64_INTERFACE_MAJOR_VERSION
&&
p_result.transfer_syntax.if_vers_minor == RpceUtility.NDR64_INTERFACE_MINOR_VERSION)
{
this.NdrVersion |= RpceNdrVersion.NDR64;
}
}
else if (p_result.result == p_cont_def_result_t.negotiate_ack)
{
byte[] bitmask = BitConverter.GetBytes((ushort)p_result.reason);
this.BindTimeFeatureNegotiationBitmask = (RpceBindTimeFeatureNegotiationBitmask)bitmask[0];
if ((this.BindTimeFeatureNegotiationBitmask
& RpceBindTimeFeatureNegotiationBitmask.KeepConnectionOnOrphanSupported_Resp)
!= 0)
{
this.BindTimeFeatureNegotiationBitmask
|= RpceBindTimeFeatureNegotiationBitmask.KeepConnectionOnOrphanSupported;
}
}
}
foreach (KeyValuePair<ushort, RpceNdrVersion> item in this.PresentationContextsTable)
{
if ((this.NdrVersion & item.Value) == item.Value)
{
this.ContextIdentifier = item.Key;
break;
}
}
}
}
/// <summary>
/// update context on receiving PDU.
/// </summary>
/// <param name="pdu">PDU to receive.</param>
/// <exception cref="ArgumentNullException">Thrown when pdu is null.</exception>
internal void UpdateContextOnReceivingPdu(RpcePdu pdu)
{
RpceCoPdu coPdu = pdu as RpceCoPdu;
if (coPdu == null)
{
return;
}
this.RpcVersionMajor = coPdu.rpc_vers;
this.RpcVersionMinor = coPdu.rpc_vers_minor;
if (coPdu.PTYPE == RpcePacketType.Bind ||
coPdu.PTYPE == RpcePacketType.BindAck)
{
//TDI:
//TD said PFC_SUPPORT_HEADER_SIGN is meanful in Bind and AltContext.
//But when using Kerberos, AltContext doesn't have this flag,
//if server or client read this flag according to AltContext, Sign/Encrypt will fail.
this.SupportsHeaderSign
= (coPdu.pfc_flags & RpceCoPfcFlags.PFC_SUPPORT_HEADER_SIGN)
== RpceCoPfcFlags.PFC_SUPPORT_HEADER_SIGN;
this.SupportsConcurrentMultiplexing
= (coPdu.pfc_flags & RpceCoPfcFlags.PFC_CONC_MPX)
== RpceCoPfcFlags.PFC_CONC_MPX;
}
this.PackedDataRepresentationFormat = coPdu.packed_drep.dataRepFormat;
this.CurrentCallId = coPdu.call_id;
if (coPdu.PTYPE != RpcePacketType.Response && coPdu.PTYPE != RpcePacketType.Auth3)
{
this.outstandingCalls.Add(coPdu.call_id);
}
switch (coPdu.PTYPE)
{
case RpcePacketType.Bind:
RpceCoBindPdu bindPdu = coPdu as RpceCoBindPdu;
if (bindPdu != null)
{
UpdateContextOnReceivingBindPdu(bindPdu);
}
break;
case RpcePacketType.Request:
RpceCoRequestPdu requestPdu = coPdu as RpceCoRequestPdu;
if (requestPdu != null)
{
this.ContextIdentifier = requestPdu.p_cont_id;
}
break;
case RpcePacketType.Response:
RpceCoResponsePdu responsePdu = coPdu as RpceCoResponsePdu;
if (responsePdu != null)
{
this.ContextIdentifier = responsePdu.p_cont_id;
}
break;
case RpcePacketType.Auth3:
case RpcePacketType.AlterContext:
case RpcePacketType.CoCancel:
case RpcePacketType.Orphaned:
default:
//default situation should do nothing.
//This is just update the context, if we cannot recognize the PDU, ignore it.
break;
}
this.SecurityContextNeedContinueProcessing = coPdu.securityContextNeedContinueProcessing;
}
/// <summary>
/// update context on receiving RPCE CO Bind PDU.
/// </summary>
/// <param name="bindPdu">Bind PDU to receive.</param>
internal void UpdateContextOnReceivingBindPdu(RpceCoBindPdu bindPdu)
{
this.MaxTransmitFragmentSize = bindPdu.max_xmit_frag;
this.MaxReceiveFragmentSize = bindPdu.max_recv_frag;
if (bindPdu.assoc_group_id != 0)
{
this.AssociateGroupId = bindPdu.assoc_group_id;
}
else
{
if (this.associateGroupIdList.Count == 0)
{
this.AssociateGroupId = bindPdu.assoc_group_id + 1;
}
else
{
this.associateGroupIdList.Sort();
this.AssociateGroupId = this.associateGroupIdList[this.associateGroupIdList.Count - 1] + 1;
}
}
associateGroupIdList.Add(this.AssociateGroupId);
if (bindPdu.p_context_elem.p_cont_elem != null &&
bindPdu.p_context_elem.p_cont_elem.Length > 0)
{
this.InterfaceId
= bindPdu.p_context_elem.p_cont_elem[0].abstract_syntax.if_uuid;
this.InterfaceMajorVersion
= bindPdu.p_context_elem.p_cont_elem[0].abstract_syntax.if_vers_major;
this.InterfaceMinorVersion
= bindPdu.p_context_elem.p_cont_elem[0].abstract_syntax.if_vers_minor;
this.NdrVersion = RpceNdrVersion.None;
this.PresentationContextsTable.Clear();
for (int i = 0; i < bindPdu.p_context_elem.p_cont_elem.Length; i++)
{
p_cont_elem_t p_cont_elem = bindPdu.p_context_elem.p_cont_elem[i];
if (p_cont_elem.transfer_syntaxes == null)
{
continue;
}
for (int j = 0; j < p_cont_elem.transfer_syntaxes.Length; j++)
{
p_syntax_id_t transfer_syntax = p_cont_elem.transfer_syntaxes[j];
if (transfer_syntax.if_uuid == RpceUtility.NDR_INTERFACE_UUID
&&
transfer_syntax.if_vers_major == RpceUtility.NDR_INTERFACE_MAJOR_VERSION
&&
transfer_syntax.if_vers_minor == RpceUtility.NDR_INTERFACE_MINOR_VERSION)
{
this.NdrVersion |= RpceNdrVersion.NDR;
this.PresentationContextsTable.Add(p_cont_elem.p_cont_id, RpceNdrVersion.NDR);
}
else if (transfer_syntax.if_uuid == RpceUtility.NDR64_INTERFACE_UUID
&&
transfer_syntax.if_vers_major == RpceUtility.NDR64_INTERFACE_MAJOR_VERSION
&&
transfer_syntax.if_vers_minor == RpceUtility.NDR64_INTERFACE_MINOR_VERSION)
{
this.NdrVersion |= RpceNdrVersion.NDR64;
this.PresentationContextsTable.Add(p_cont_elem.p_cont_id, RpceNdrVersion.NDR64);
}
else
{
byte[] uuid = transfer_syntax.if_uuid.ToByteArray();
if (ArrayUtility.CompareArrays(
ArrayUtility.SubArray(
uuid,
0,
RpceUtility.BIND_TIME_FEATURE_NEGOTIATION_BITMASK_PREFIX_LENGTH),
ArrayUtility.SubArray(
RpceUtility.BIND_TIME_FEATURE_NEGOTIATION_BITMASK_GUID_BYTES,
0,
RpceUtility.BIND_TIME_FEATURE_NEGOTIATION_BITMASK_PREFIX_LENGTH))
&&
transfer_syntax.if_vers_major == 1
&&
transfer_syntax.if_vers_minor == 0)
{
this.BindTimeFeatureNegotiationBitmask = (RpceBindTimeFeatureNegotiationBitmask)
uuid[RpceUtility.BIND_TIME_FEATURE_NEGOTIATION_BITMASK_PREFIX_LENGTH];
}
}
}
}
}
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventWaitHandleSecurity
**
**
** Purpose: Managed ACL wrapper for Win32 events.
**
**
===========================================================*/
using System;
using System.Collections;
using System.Security.Permissions;
using System.Security.Principal;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
namespace System.Security.AccessControl
{
// Derive this list of values from winnt.h and MSDN docs:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/synchronization_object_security_and_access_rights.asp
// Win32's interesting values are EVENT_MODIFY_STATE (0x0002) and
// EVENT_ALL_ACCESS (0x1F0003). I don't know what 0x1 is, but Windows
// includes it in EVENT_ALL_ACCESS.
[Flags]
public enum EventWaitHandleRights
{
Modify = 0x000002,
Delete = 0x010000,
ReadPermissions = 0x020000,
ChangePermissions = 0x040000,
TakeOwnership = 0x080000,
Synchronize = 0x100000, // SYNCHRONIZE
FullControl = 0x1F0003
}
public sealed class EventWaitHandleAccessRule : AccessRule
{
// Constructor for creating access rules for registry objects
public EventWaitHandleAccessRule(IdentityReference identity, EventWaitHandleRights eventRights, AccessControlType type)
: this(identity, (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
public EventWaitHandleAccessRule(String identity, EventWaitHandleRights eventRights, AccessControlType type)
: this(new NTAccount(identity), (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
//
// Internal constructor to be called by public constructors
// and the access rule factory methods of {File|Folder}Security
//
internal EventWaitHandleAccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type )
: base(
identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type )
{
}
public EventWaitHandleRights EventWaitHandleRights {
get { return (EventWaitHandleRights) base.AccessMask; }
}
}
public sealed class EventWaitHandleAuditRule : AuditRule
{
public EventWaitHandleAuditRule(IdentityReference identity, EventWaitHandleRights eventRights, AuditFlags flags)
: this(identity, (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags)
{
}
/* // Not in the spec
public EventWaitHandleAuditRule(string identity, EventWaitHandleRights eventRights, AuditFlags flags)
: this(new NTAccount(identity), (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags)
{
}
*/
internal EventWaitHandleAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags)
{
}
public EventWaitHandleRights EventWaitHandleRights {
get { return (EventWaitHandleRights) base.AccessMask; }
}
}
public sealed class EventWaitHandleSecurity : NativeObjectSecurity
{
public EventWaitHandleSecurity()
: base(true, ResourceType.KernelObject)
{
}
[System.Security.SecurityCritical] // auto-generated
internal EventWaitHandleSecurity(String name, AccessControlSections includeSections)
: base(true, ResourceType.KernelObject, name, includeSections, _HandleErrorCode, null)
{
// Let the underlying ACL API's demand unmanaged code permission.
}
[System.Security.SecurityCritical] // auto-generated
internal EventWaitHandleSecurity(SafeWaitHandle handle, AccessControlSections includeSections)
: base(true, ResourceType.KernelObject, handle, includeSections, _HandleErrorCode, null)
{
// Let the underlying ACL API's demand unmanaged code permission.
}
[System.Security.SecurityCritical] // auto-generated
private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context)
{
System.Exception exception = null;
switch (errorCode) {
case Win32Native.ERROR_INVALID_NAME:
case Win32Native.ERROR_INVALID_HANDLE:
case Win32Native.ERROR_FILE_NOT_FOUND:
if ((name != null) && (name.Length != 0))
exception = new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
else
exception = new WaitHandleCannotBeOpenedException();
break;
default:
break;
}
return exception;
}
public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
{
return new EventWaitHandleAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type);
}
public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
{
return new EventWaitHandleAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags);
}
internal AccessControlSections GetAccessControlSectionsFromChanges()
{
AccessControlSections persistRules = AccessControlSections.None;
if (AccessRulesModified)
persistRules = AccessControlSections.Access;
if (AuditRulesModified)
persistRules |= AccessControlSections.Audit;
if (OwnerModified)
persistRules |= AccessControlSections.Owner;
if (GroupModified)
persistRules |= AccessControlSections.Group;
return persistRules;
}
[System.Security.SecurityCritical] // auto-generated
internal void Persist(SafeWaitHandle handle)
{
//
// Let the underlying ACL API's demand unmanaged code.
//
WriteLock();
try
{
AccessControlSections persistSections = GetAccessControlSectionsFromChanges();
if (persistSections == AccessControlSections.None)
return; // Don't need to persist anything.
base.Persist(handle, persistSections);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
finally
{
WriteUnlock();
}
}
public void AddAccessRule(EventWaitHandleAccessRule rule)
{
base.AddAccessRule(rule);
}
public void SetAccessRule(EventWaitHandleAccessRule rule)
{
base.SetAccessRule(rule);
}
public void ResetAccessRule(EventWaitHandleAccessRule rule)
{
base.ResetAccessRule(rule);
}
public bool RemoveAccessRule(EventWaitHandleAccessRule rule)
{
return base.RemoveAccessRule(rule);
}
public void RemoveAccessRuleAll(EventWaitHandleAccessRule rule)
{
base.RemoveAccessRuleAll(rule);
}
public void RemoveAccessRuleSpecific(EventWaitHandleAccessRule rule)
{
base.RemoveAccessRuleSpecific(rule);
}
public void AddAuditRule(EventWaitHandleAuditRule rule)
{
base.AddAuditRule(rule);
}
public void SetAuditRule(EventWaitHandleAuditRule rule)
{
base.SetAuditRule(rule);
}
public bool RemoveAuditRule(EventWaitHandleAuditRule rule)
{
return base.RemoveAuditRule(rule);
}
public void RemoveAuditRuleAll(EventWaitHandleAuditRule rule)
{
base.RemoveAuditRuleAll(rule);
}
public void RemoveAuditRuleSpecific(EventWaitHandleAuditRule rule)
{
base.RemoveAuditRuleSpecific(rule);
}
public override Type AccessRightType
{
get { return typeof(EventWaitHandleRights); }
}
public override Type AccessRuleType
{
get { return typeof(EventWaitHandleAccessRule); }
}
public override Type AuditRuleType
{
get { return typeof(EventWaitHandleAuditRule); }
}
}
}
| |
using System;
using System.Threading.Tasks;
using EasyNetQ.Consumer;
using EasyNetQ.FluentConfiguration;
using EasyNetQ.Producer;
using EasyNetQ.Topology;
using System.Linq;
using EasyNetQ.Internals;
namespace EasyNetQ
{
public class RabbitBus : IBus
{
private readonly IConventions conventions;
private readonly IAdvancedBus advancedBus;
private readonly IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy;
private readonly IMessageDeliveryModeStrategy messageDeliveryModeStrategy;
private readonly IRpc rpc;
private readonly ISendReceive sendReceive;
private readonly ConnectionConfiguration connectionConfiguration;
public RabbitBus(
IConventions conventions,
IAdvancedBus advancedBus,
IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy,
IMessageDeliveryModeStrategy messageDeliveryModeStrategy,
IRpc rpc,
ISendReceive sendReceive,
ConnectionConfiguration connectionConfiguration)
{
Preconditions.CheckNotNull(conventions, "conventions");
Preconditions.CheckNotNull(advancedBus, "advancedBus");
Preconditions.CheckNotNull(publishExchangeDeclareStrategy, "publishExchangeDeclareStrategy");
Preconditions.CheckNotNull(rpc, "rpc");
Preconditions.CheckNotNull(sendReceive, "sendReceive");
Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
this.conventions = conventions;
this.advancedBus = advancedBus;
this.publishExchangeDeclareStrategy = publishExchangeDeclareStrategy;
this.messageDeliveryModeStrategy = messageDeliveryModeStrategy;
this.rpc = rpc;
this.sendReceive = sendReceive;
this.connectionConfiguration = connectionConfiguration;
}
public virtual void Publish<T>(T message) where T : class
{
Preconditions.CheckNotNull(message, "message");
Publish(message, conventions.TopicNamingConvention(typeof(T)));
}
public virtual void Publish<T>(T message, string topic) where T : class
{
Preconditions.CheckNotNull(message, "message");
Preconditions.CheckNotNull(topic, "topic");
var messageType = typeof(T);
var easyNetQMessage = new Message<T>(message)
{
Properties =
{
DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType)
}
};
var exchange = publishExchangeDeclareStrategy.DeclareExchange(advancedBus, messageType, ExchangeType.Topic);
advancedBus.Publish(exchange, topic, false, easyNetQMessage);
}
public virtual Task PublishAsync<T>(T message) where T : class
{
Preconditions.CheckNotNull(message, "message");
return PublishAsync(message, conventions.TopicNamingConvention(typeof(T)));
}
public virtual async Task PublishAsync<T>(T message, string topic) where T : class
{
Preconditions.CheckNotNull(message, "message");
Preconditions.CheckNotNull(topic, "topic");
var messageType = typeof (T);
var easyNetQMessage = new Message<T>(message)
{
Properties =
{
DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType)
}
};
var exchange = await publishExchangeDeclareStrategy.DeclareExchangeAsync(advancedBus, messageType, ExchangeType.Topic).ConfigureAwait(false);
await advancedBus.PublishAsync(exchange, topic, false, easyNetQMessage).ConfigureAwait(false);
}
public virtual ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage) where T : class
{
return Subscribe(subscriptionId, onMessage, x => { });
}
public virtual ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage, Action<ISubscriptionConfiguration> configure) where T : class
{
Preconditions.CheckNotNull(subscriptionId, "subscriptionId");
Preconditions.CheckNotNull(onMessage, "onMessage");
Preconditions.CheckNotNull(configure, "configure");
return SubscribeAsync<T>(subscriptionId, msg => TaskHelpers.ExecuteSynchronously(() => onMessage(msg)), configure);
}
public virtual ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage) where T : class
{
return SubscribeAsync(subscriptionId, onMessage, x => { });
}
public virtual ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage, Action<ISubscriptionConfiguration> configure) where T : class
{
Preconditions.CheckNotNull(subscriptionId, "subscriptionId");
Preconditions.CheckNotNull(onMessage, "onMessage");
Preconditions.CheckNotNull(configure, "configure");
var configuration = new SubscriptionConfiguration(connectionConfiguration.PrefetchCount);
configure(configuration);
var queueName = conventions.QueueNamingConvention(typeof(T), subscriptionId);
var exchangeName = conventions.ExchangeNamingConvention(typeof(T));
var queue = advancedBus.QueueDeclare(queueName, autoDelete: configuration.AutoDelete, expires: configuration.Expires);
var exchange = advancedBus.ExchangeDeclare(exchangeName, ExchangeType.Topic);
foreach (var topic in configuration.Topics.DefaultIfEmpty("#"))
{
advancedBus.Bind(exchange, queue, topic);
}
var consumerCancellation = advancedBus.Consume<T>(
queue,
(message, messageReceivedInfo) => onMessage(message.Body),
x =>
{
x.WithPriority(configuration.Priority)
.WithCancelOnHaFailover(configuration.CancelOnHaFailover)
.WithPrefetchCount(configuration.PrefetchCount);
if (configuration.IsExclusive)
{
x.AsExclusive();
}
});
return new SubscriptionResult(exchange, queue, consumerCancellation);
}
public virtual TResponse Request<TRequest, TResponse>(TRequest request)
where TRequest : class
where TResponse : class
{
Preconditions.CheckNotNull(request, "request");
var task = RequestAsync<TRequest, TResponse>(request);
task.Wait();
return task.Result;
}
public virtual Task<TResponse> RequestAsync<TRequest, TResponse>(TRequest request)
where TRequest : class
where TResponse : class
{
Preconditions.CheckNotNull(request, "request");
return rpc.Request<TRequest, TResponse>(request);
}
public virtual IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder)
where TRequest : class
where TResponse : class
{
Preconditions.CheckNotNull(responder, "responder");
Func<TRequest, Task<TResponse>> taskResponder =
request => Task<TResponse>.Factory.StartNew(_ => responder(request), null);
return RespondAsync(taskResponder);
}
public IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class
{
Func<TRequest, Task<TResponse>> taskResponder =
request => Task<TResponse>.Factory.StartNew(_ => responder(request), null);
return RespondAsync(taskResponder, configure);
}
public virtual IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder)
where TRequest : class
where TResponse : class
{
return RespondAsync(responder, c => { });
}
public IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class
{
Preconditions.CheckNotNull(responder, "responder");
Preconditions.CheckNotNull(configure, "configure");
return rpc.Respond(responder, configure);
}
public virtual void Send<T>(string queue, T message)
where T : class
{
sendReceive.Send(queue, message);
}
public virtual Task SendAsync<T>(string queue, T message)
where T : class
{
return sendReceive.SendAsync(queue, message);
}
public virtual IDisposable Receive<T>(string queue, Action<T> onMessage)
where T : class
{
return sendReceive.Receive(queue, onMessage);
}
public virtual IDisposable Receive<T>(string queue, Action<T> onMessage, Action<IConsumerConfiguration> configure)
where T : class
{
return sendReceive.Receive(queue, onMessage, configure);
}
public virtual IDisposable Receive<T>(string queue, Func<T, Task> onMessage)
where T : class
{
return sendReceive.Receive(queue, onMessage);
}
public virtual IDisposable Receive<T>(string queue, Func<T, Task> onMessage, Action<IConsumerConfiguration> configure)
where T : class
{
return sendReceive.Receive(queue, onMessage, configure);
}
public virtual IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers)
{
return sendReceive.Receive(queue, addHandlers);
}
public virtual IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers, Action<IConsumerConfiguration> configure)
{
return sendReceive.Receive(queue, addHandlers, configure);
}
public virtual bool IsConnected
{
get { return advancedBus.IsConnected; }
}
public virtual IAdvancedBus Advanced
{
get { return advancedBus; }
}
public virtual void Dispose()
{
advancedBus.Dispose();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.