context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Text;
using osuTK;
namespace osu.Framework.Tests.Text
{
[TestFixture]
public class TextBuilderTest
{
private const float font_size = 1;
private const float x_offset = 1;
private const float y_offset = 2;
private const float x_advance = 3;
private const float width = 4;
private const float height = 5;
private const float kerning = -6;
private const float b_x_offset = 7;
private const float b_y_offset = 8;
private const float b_x_advance = 9;
private const float b_width = 10;
private const float b_height = 11;
private const float b_kerning = -12;
private const float m_x_offset = 13;
private const float m_y_offset = 14;
private const float m_x_advance = 15;
private const float m_width = 16;
private const float m_height = 17;
private const float m_kerning = -18;
private static readonly Vector2 spacing = new Vector2(19, 20);
private static readonly TestFontUsage normal_font = new TestFontUsage("test");
private static readonly TestFontUsage fixed_width_font = new TestFontUsage("test-fixedwidth", fixedWidth: true);
private readonly TestStore fontStore;
public TextBuilderTest()
{
fontStore = new TestStore(
(normal_font, new TestGlyph('a', x_offset, y_offset, x_advance, width, height, kerning)),
(normal_font, new TestGlyph('b', b_x_offset, b_y_offset, b_x_advance, b_width, b_height, b_kerning)),
(normal_font, new TestGlyph('m', m_x_offset, m_y_offset, m_x_advance, m_width, m_height, m_kerning)),
(fixed_width_font, new TestGlyph('a', x_offset, y_offset, x_advance, width, height, kerning)),
(fixed_width_font, new TestGlyph('b', b_x_offset, b_y_offset, b_x_advance, b_width, b_height, b_kerning)),
(fixed_width_font, new TestGlyph('m', m_x_offset, m_y_offset, m_x_advance, m_width, m_height, m_kerning))
);
}
/// <summary>
/// Tests that the size of a fresh text builder is zero.
/// </summary>
[Test]
public void TestInitialSizeIsZero()
{
var builder = new TextBuilder(fontStore, normal_font);
Assert.That(builder.Bounds, Is.EqualTo(Vector2.Zero));
}
/// <summary>
/// Tests that the first added character is correctly marked as being on a new line.
/// </summary>
[Test]
public void TestFirstCharacterIsOnNewLine()
{
var builder = new TextBuilder(fontStore, normal_font);
builder.AddText("a");
Assert.That(builder.Characters[0].OnNewLine, Is.True);
}
/// <summary>
/// Tests that the first added fixed-width character metrics match the glyph's.
/// </summary>
[Test]
public void TestFirstCharacterRectangleIsCorrect()
{
var builder = new TextBuilder(fontStore, normal_font);
builder.AddText("a");
Assert.That(builder.Characters[0].DrawRectangle.Left, Is.EqualTo(x_offset));
Assert.That(builder.Characters[0].DrawRectangle.Top, Is.EqualTo(y_offset));
Assert.That(builder.Characters[0].DrawRectangle.Width, Is.EqualTo(width));
Assert.That(builder.Characters[0].DrawRectangle.Height, Is.EqualTo(height));
}
/// <summary>
/// Tests that the first added character metrics match the glyph's.
/// </summary>
[Test]
public void TestFirstFixedWidthCharacterRectangleIsCorrect()
{
var builder = new TextBuilder(fontStore, fixed_width_font);
builder.AddText("a");
Assert.That(builder.Characters[0].DrawRectangle.Left, Is.EqualTo((m_width - width) / 2));
Assert.That(builder.Characters[0].DrawRectangle.Top, Is.EqualTo(y_offset));
Assert.That(builder.Characters[0].DrawRectangle.Width, Is.EqualTo(width));
Assert.That(builder.Characters[0].DrawRectangle.Height, Is.EqualTo(height));
}
/// <summary>
/// Tests that the current position is advanced after a character is added.
/// </summary>
[Test]
public void TestCurrentPositionAdvancedAfterCharacter()
{
var builder = new TextBuilder(fontStore, normal_font);
builder.AddText("a");
builder.AddText("a");
Assert.That(builder.Characters[1].DrawRectangle.Left, Is.EqualTo(x_advance + kerning + x_offset));
Assert.That(builder.Characters[1].DrawRectangle.Top, Is.EqualTo(y_offset));
Assert.That(builder.Characters[1].DrawRectangle.Width, Is.EqualTo(width));
Assert.That(builder.Characters[1].DrawRectangle.Height, Is.EqualTo(height));
}
/// <summary>
/// Tests that the current position is advanced after a fixed width character is added.
/// </summary>
[Test]
public void TestCurrentPositionAdvancedAfterFixedWidthCharacter()
{
var builder = new TextBuilder(fontStore, fixed_width_font);
builder.AddText("a");
builder.AddText("a");
Assert.That(builder.Characters[1].DrawRectangle.Left, Is.EqualTo(m_width + (m_width - width) / 2));
Assert.That(builder.Characters[1].DrawRectangle.Top, Is.EqualTo(y_offset));
Assert.That(builder.Characters[1].DrawRectangle.Width, Is.EqualTo(width));
Assert.That(builder.Characters[1].DrawRectangle.Height, Is.EqualTo(height));
}
/// <summary>
/// Tests that a new line added to an empty builder always uses the font height.
/// </summary>
[Test]
public void TestNewLineOnEmptyBuilderOffsetsPositionByFontSize()
{
var builder = new TextBuilder(fontStore, normal_font);
builder.AddNewLine();
builder.AddText("a");
Assert.That(builder.Characters[0].DrawRectangle.Top, Is.EqualTo(font_size + y_offset));
}
/// <summary>
/// Tests that a new line added to an empty line always uses the font height.
/// </summary>
[Test]
public void TestNewLineOnEmptyLineOffsetsPositionByFontSize()
{
var builder = new TextBuilder(fontStore, normal_font);
builder.AddNewLine();
builder.AddNewLine();
builder.AddText("a");
Assert.That(builder.Characters[0].DrawRectangle.Top, Is.EqualTo(y_offset + y_offset));
}
/// <summary>
/// Tests that a new line added to a builder that is using the font height as size offsets the y-position by the font size and not the glyph size.
/// </summary>
[Test]
public void TestNewLineUsesFontHeightWhenUsingFontHeightAsSize()
{
var builder = new TextBuilder(fontStore, normal_font);
builder.AddText("a");
builder.AddText("b");
builder.AddNewLine();
builder.AddText("a");
Assert.That(builder.Characters[2].DrawRectangle.Top, Is.EqualTo(font_size + y_offset));
}
/// <summary>
/// Tests that a new line added to a builder that is not using the font height as size offsets the y-position by the glyph size and not the font size.
/// </summary>
[Test]
public void TestNewLineUsesGlyphHeightWhenNotUsingFontHeightAsSize()
{
var builder = new TextBuilder(fontStore, normal_font, useFontSizeAsHeight: false);
builder.AddText("a");
builder.AddText("b");
builder.AddNewLine();
builder.AddText("a");
// b is the larger glyph
Assert.That(builder.Characters[2].DrawRectangle.Top, Is.EqualTo(b_y_offset + b_height + y_offset));
}
/// <summary>
/// Tests that the first added character on a new line is correctly marked as being on a new line.
/// </summary>
[Test]
public void TestFirstCharacterOnNewLineIsOnNewLine()
{
var builder = new TextBuilder(fontStore, normal_font);
builder.AddText("a");
builder.AddNewLine();
builder.AddText("a");
Assert.That(builder.Characters[1].OnNewLine, Is.True);
}
/// <summary>
/// Tests that no kerning is added for the first character of a new line.
/// </summary>
[Test]
public void TestFirstCharacterOnNewLineHasNoKerning()
{
var builder = new TextBuilder(fontStore, normal_font);
builder.AddText("a");
builder.AddNewLine();
builder.AddText("a");
Assert.That(builder.Characters[1].DrawRectangle.Left, Is.EqualTo(x_offset));
}
/// <summary>
/// Tests that the current position is correctly reset when the first character is removed.
/// </summary>
[Test]
public void TestRemoveFirstCharacterResetsCurrentPosition()
{
var builder = new TextBuilder(fontStore, normal_font, spacing: spacing);
builder.AddText("a");
builder.RemoveLastCharacter();
Assert.That(builder.Bounds, Is.EqualTo(Vector2.Zero));
builder.AddText("a");
Assert.That(builder.Characters[0].DrawRectangle.Top, Is.EqualTo(y_offset));
Assert.That(builder.Characters[0].DrawRectangle.Left, Is.EqualTo(x_offset));
}
/// <summary>
/// Tests that the current position is moved backwards and the character is removed when a character is removed.
/// </summary>
[Test]
public void TestRemoveCharacterOnSameLineRemovesCharacter()
{
var builder = new TextBuilder(fontStore, normal_font, spacing: spacing);
builder.AddText("a");
builder.AddText("a");
builder.RemoveLastCharacter();
Assert.That(builder.Bounds, Is.EqualTo(new Vector2(x_advance, font_size)));
builder.AddText("a");
Assert.That(builder.Characters[1].DrawRectangle.Top, Is.EqualTo(y_offset));
Assert.That(builder.Characters[1].DrawRectangle.Left, Is.EqualTo(x_advance + spacing.X + kerning + x_offset));
}
/// <summary>
/// Tests that the current position is moved to the end of the previous line, and that the character + new line is removed when a character is removed.
/// </summary>
[Test]
public void TestRemoveCharacterOnNewLineRemovesCharacterAndLine()
{
var builder = new TextBuilder(fontStore, normal_font, spacing: spacing);
builder.AddText("a");
builder.AddNewLine();
builder.AddText("a");
builder.RemoveLastCharacter();
Assert.That(builder.Bounds, Is.EqualTo(new Vector2(x_advance, font_size)));
builder.AddText("a");
Assert.That(builder.Characters[1].DrawRectangle.TopLeft, Is.EqualTo(new Vector2(x_advance + spacing.X + kerning + x_offset, y_offset)));
Assert.That(builder.Bounds, Is.EqualTo(new Vector2(x_advance + spacing.X + kerning + x_advance, font_size)));
}
/// <summary>
/// Tests that the custom user-provided spacing is added for a new character/line.
/// </summary>
[Test]
public void TestSpacingAdded()
{
var builder = new TextBuilder(fontStore, normal_font, spacing: spacing);
builder.AddText("a");
builder.AddText("a");
builder.AddNewLine();
builder.AddText("a");
Assert.That(builder.Characters[0].DrawRectangle.Left, Is.EqualTo(x_offset));
Assert.That(builder.Characters[1].DrawRectangle.Left, Is.EqualTo(x_advance + spacing.X + kerning + x_offset));
Assert.That(builder.Characters[2].DrawRectangle.Left, Is.EqualTo(x_offset));
Assert.That(builder.Characters[2].DrawRectangle.Top, Is.EqualTo(font_size + spacing.Y + y_offset));
}
/// <summary>
/// Tests that glyph lookup falls back to using the same character with no font name.
/// </summary>
[Test]
public void TestSameCharacterFallsBackWithNoFontName()
{
var font = new TestFontUsage("test");
var nullFont = new TestFontUsage(null);
var builder = new TextBuilder(new TestStore(
(font, new TestGlyph('b', 0, 0, 0, 0, 0, 0)),
(nullFont, new TestGlyph('a', 0, 0, 0, 0, 0, 0)),
(font, new TestGlyph('?', 0, 0, 0, 0, 0, 0)),
(nullFont, new TestGlyph('?', 0, 0, 0, 0, 0, 0))
), font);
builder.AddText("a");
Assert.That(builder.Characters[0].Character, Is.EqualTo('a'));
}
/// <summary>
/// Tests that glyph lookup falls back to using the fallback character with the provided font name.
/// </summary>
[Test]
public void TestFallBackCharacterFallsBackWithFontName()
{
var font = new TestFontUsage("test");
var nullFont = new TestFontUsage(null);
var builder = new TextBuilder(new TestStore(
(font, new TestGlyph('b', 0, 0, 0, 0, 0, 0)),
(nullFont, new TestGlyph('b', 0, 0, 0, 0, 0, 0)),
(font, new TestGlyph('?', 0, 0, 0, 0, 0, 0)),
(nullFont, new TestGlyph('?', 1, 0, 0, 0, 0, 0))
), font);
builder.AddText("a");
Assert.That(builder.Characters[0].Character, Is.EqualTo('?'));
Assert.That(builder.Characters[0].XOffset, Is.EqualTo(0));
}
/// <summary>
/// Tests that glyph lookup falls back to using the fallback character with no font name.
/// </summary>
[Test]
public void TestFallBackCharacterFallsBackWithNoFontName()
{
var font = new TestFontUsage("test");
var nullFont = new TestFontUsage(null);
var builder = new TextBuilder(new TestStore(
(font, new TestGlyph('b', 0, 0, 0, 0, 0, 0)),
(nullFont, new TestGlyph('b', 0, 0, 0, 0, 0, 0)),
(font, new TestGlyph('b', 0, 0, 0, 0, 0, 0)),
(nullFont, new TestGlyph('?', 1, 0, 0, 0, 0, 0))
), font);
builder.AddText("a");
Assert.That(builder.Characters[0].Character, Is.EqualTo('?'));
Assert.That(builder.Characters[0].XOffset, Is.EqualTo(1));
}
/// <summary>
/// Tests that a null glyph is correctly handled.
/// </summary>
[Test]
public void TestFailedCharacterLookup()
{
var font = new TestFontUsage("test");
var builder = new TextBuilder(new TestStore(), font);
builder.AddText("a");
Assert.That(builder.Bounds, Is.EqualTo(Vector2.Zero));
}
private readonly struct TestFontUsage
{
private readonly string family;
private readonly string weight;
private readonly bool italics;
private readonly bool fixedWidth;
public TestFontUsage(string family = null, string weight = null, bool italics = false, bool fixedWidth = false)
{
this.family = family;
this.weight = weight;
this.italics = italics;
this.fixedWidth = fixedWidth;
}
public static implicit operator FontUsage(TestFontUsage tfu)
=> new FontUsage(tfu.family, font_size, tfu.weight, tfu.italics, tfu.fixedWidth);
}
private class TestStore : ITexturedGlyphLookupStore
{
private readonly (FontUsage font, ITexturedCharacterGlyph glyph)[] glyphs;
public TestStore(params (FontUsage font, ITexturedCharacterGlyph glyph)[] glyphs)
{
this.glyphs = glyphs;
}
public ITexturedCharacterGlyph Get(string fontName, char character)
{
if (string.IsNullOrEmpty(fontName))
return glyphs.FirstOrDefault(g => g.glyph.Character == character).glyph;
return glyphs.FirstOrDefault(g => g.font.FontName == fontName && g.glyph.Character == character).glyph;
}
public Task<ITexturedCharacterGlyph> GetAsync(string fontName, char character) => throw new System.NotImplementedException();
}
private readonly struct TestGlyph : ITexturedCharacterGlyph
{
public Texture Texture => new Texture(1, 1);
public float XOffset { get; }
public float YOffset { get; }
public float XAdvance { get; }
public float Width { get; }
public float Height { get; }
public char Character { get; }
private readonly float glyphKerning;
public TestGlyph(char character, float xOffset, float yOffset, float xAdvance, float width, float height, float kerning)
{
glyphKerning = kerning;
Character = character;
XOffset = xOffset;
YOffset = yOffset;
XAdvance = xAdvance;
Width = width;
Height = height;
}
public float GetKerning<T>(T lastGlyph)
where T : ICharacterGlyph
=> glyphKerning;
}
}
}
| |
//-----------------------------------------------------------------------------
// Verve
// Copyright (C) - Violent Tulip
//-----------------------------------------------------------------------------
function VerveEditor::DeleteControls()
{
while ( VerveEditorGroupStack.getCount() > 0 )
{
VerveEditorGroupStack.getObject( 0 ).delete();
}
while ( VerveEditorTrackStack.getCount() > 0 )
{
VerveEditorTrackStack.getObject( 0 ).delete();
}
}
function VerveEditorStack::FindControl( %this, %object )
{
%trackCount = %this.getCount();
for ( %i = 0; %i < %trackCount; %i++ )
{
%track = %this.getObject( %i );
if ( %track.Proxy.getId() == %object.getId() )
{
return %track;
}
}
return -1;
}
function VerveEditorStack::FindControlIndex( %this, %object )
{
%trackCount = %this.getCount();
for ( %i = 0; %i < %trackCount; %i++ )
{
%track = %this.getObject( %i );
if ( %track.Proxy.getId() == %object.getId() )
{
return %i;
}
}
return -1;
}
//-------------------------------------------------------------------------
function VerveEditorTimeLine::onLoseFirstResponder( %this )
{
// Clear Selection.
%this.setSelection( false );
// Force OnSelectionUpdate.
%this.onSelectionUpdate();
}
function VerveEditorTimeLine::StopUpdate( %this )
{
// Cancel Event.
cancel( $VerveEditor::Controller::TickEvent );
}
function VerveEditorTimeLine::ControllerUpdate( %this )
{
// Cancel Event.
cancel( $VerveEditor::Controller::TickEvent );
%scrollParent = %this.getParentOfType( "VEditorScrollControl" );
if ( !isObject( %scrollParent ) )
{
// Woops!
return;
}
// Fetch Point.
%point = %this.toPoint( $VerveEditor::Controller.Time );
// Fetch Scroll Point.
%scrollPoint = %scrollParent.getScrollPositionX();
%scrollWidth = getWord( %scrollParent.getExtent(), 0 ) - 19;
if ( ( %point < %scrollPoint ) || ( %point > ( %scrollPoint + %scrollWidth ) ) )
{
// Scroll To View Time.
%scrollParent.setScrollPosition( %point - %scrollWidth * 0.50, 0 );
}
// Schedule Next Event.
$VerveEditor::Controller::TickEvent = %this.schedule( 100, "ControllerUpdate" );
}
function VerveEditorTimeLine::onSelectionUpdate( %this )
{
// Fetch Selection.
%selectionString = %this.getSelection();
%selectionActive = getWord( %selectionString, 0 );
if ( !%selectionActive )
{
// Clear Selection.
VerveEditorTrackTimeLine.setSelection( false );
}
else
{
if ( !getWord( VerveEditorTrackTimeLine.getSelection(), 0 ) )
{
// Clear Editor Selection.
VerveEditor::ClearSelection();
}
// Set Selection.
VerveEditorTrackTimeLine.setSelection( true, getWord( %selectionString, 1 ), getWord( %selectionString, 2 ) );
}
}
function VerveEditorTimeLine::onSelectionRightClick( %this, %point, %modifiers, %clickCount )
{
%this.DisplayContextMenu( getWord( %point, 0 ), getWord( %point, 1 ) );
}
function VerveEditorTimeLine::DisplayContextMenu( %this, %x, %y )
{
%contextMenu = $VerveEditor::VTimeLine::ContextMenu;
if ( !isObject( %contextMenu ) )
{
%contextMenu = new PopupMenu()
{
SuperClass = "VerveWindowMenu";
IsPopup = true;
Label = "VTimeLineMenu";
Position = 0;
Item[0] = "Insert Time Before" TAB "" TAB "VerveEditorTimeLine.InsertTimeBefore();";
Item[1] = "Insert Time After" TAB "" TAB "VerveEditorTimeLine.InsertTimeAfter();";
Item[2] = "" TAB "";
Item[3] = "Delete Time" TAB "" TAB "VerveEditorTimeLine.DeleteTime();";
};
%contextMenu.Init();
// Cache.
$VerveEditor::VTimeLine::ContextMenu = %contextMenu;
}
// Display.
%contextMenu.showPopup( VerveEditorWindow, %x, %y );
}
function VerveEditorTimeLine::InsertTimeBefore( %this )
{
// Fetch Selection.
%selectionString = %this.getSelection();
%selectionActive = getWord( %selectionString, 0 );
if ( !%selectionActive )
{
// Woops!
return;
}
// Determine Position.
%selectionPosition = getWord( %selectionString, 1 );
// Insert Time.
VerveEditor::InsertTime( %selectionPosition, getWord( %selectionString, 2 ) );
}
function VerveEditorTimeLine::InsertTimeAfter( %this )
{
// Fetch Selection.
%selectionString = %this.getSelection();
%selectionActive = getWord( %selectionString, 0 );
if ( !%selectionActive )
{
// Woops!
return;
}
// Determine Position.
%selectionPosition = getWord( %selectionString, 1 ) + getWord( %selectionString, 2 );
// Insert Time.
VerveEditor::InsertTime( %selectionPosition, getWord( %selectionString, 2 ) );
}
function VerveEditorTimeLine::DeleteTime( %this )
{
// Fetch Selection.
%selectionString = %this.getSelection();
%selectionActive = getWord( %selectionString, 0 );
if ( !%selectionActive )
{
// Woops!
return;
}
// Determine Position.
%selectionPosition = getWord( %selectionString, 1 );
// Delete Time.
VerveEditor::DeleteTime( %selectionPosition, getWord( %selectionString, 2 ) );
// Clear Selection.
%this.setSelection( false );
// Force OnSelectionUpdate.
%this.onSelectionUpdate();
}
//-------------------------------------------------------------------------
function VerveEditorTimeLineBackground::onMouseUp( %this, %point, %modifiers, %clickCount )
{
// Clear Selection.
VerveEditor::ClearSelection();
}
function VerveEditorTimeLineBackground::onRightMouseUp( %this, %point, %modifiers, %clickCount )
{
// Clear Selection.
VerveEditor::ClearSelection();
if ( !%this.Context )
{
// Return.
return;
}
// Display Context Menu.
$VerveEditor::Controller.schedule( 32, "DisplayContextMenu", getWord( %point, 0 ), getWord( %point, 1 ) );
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.InvalidDataContractException))]
namespace System.Runtime.Serialization
{
public abstract partial class DataContractResolver
{
protected DataContractResolver() { }
public abstract System.Type ResolveName(string typeName, string typeNamespace, System.Type declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver);
public abstract bool TryResolveType(System.Type type, System.Type declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver, out System.Xml.XmlDictionaryString typeName, out System.Xml.XmlDictionaryString typeNamespace);
}
public sealed partial class DataContractSerializer : System.Runtime.Serialization.XmlObjectSerializer
{
public DataContractSerializer(System.Type type) { }
public DataContractSerializer(System.Type type, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
public DataContractSerializer(System.Type type, System.Runtime.Serialization.DataContractSerializerSettings settings) { }
public DataContractSerializer(System.Type type, string rootName, string rootNamespace) { }
public DataContractSerializer(System.Type type, string rootName, string rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace) { }
public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
public System.Runtime.Serialization.DataContractResolver DataContractResolver { get { throw null; } }
public bool IgnoreExtensionDataObject { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<System.Type> KnownTypes { get { throw null; } }
public int MaxItemsInObjectGraph { get { throw null; } }
public bool PreserveObjectReferences { get { throw null; } }
public bool SerializeReadOnlyTypes { get { throw null; } }
public override bool IsStartObject(System.Xml.XmlDictionaryReader reader) { throw null; }
public override bool IsStartObject(System.Xml.XmlReader reader) { throw null; }
public override object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName) { throw null; }
public object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName, System.Runtime.Serialization.DataContractResolver dataContractResolver) { throw null; }
public override object ReadObject(System.Xml.XmlReader reader) { throw null; }
public override object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; }
public override void WriteEndObject(System.Xml.XmlDictionaryWriter writer) { }
public override void WriteEndObject(System.Xml.XmlWriter writer) { }
public void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph, System.Runtime.Serialization.DataContractResolver dataContractResolver) { }
public override void WriteObject(System.Xml.XmlWriter writer, object graph) { }
public override void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph) { }
public override void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { }
public override void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph) { }
public override void WriteStartObject(System.Xml.XmlWriter writer, object graph) { }
}
public static partial class DataContractSerializerExtensions
{
public static System.Runtime.Serialization.ISerializationSurrogateProvider GetSerializationSurrogateProvider(this DataContractSerializer serializer) { throw null; }
public static void SetSerializationSurrogateProvider(this DataContractSerializer serializer, System.Runtime.Serialization.ISerializationSurrogateProvider provider) { }
}
public partial class DataContractSerializerSettings
{
public DataContractSerializerSettings() { }
public System.Runtime.Serialization.DataContractResolver DataContractResolver { get { throw null; } set { } }
//CODEDOM public System.Runtime.Serialization.IDataContractSurrogate DataContractSurrogate { get { throw null; } set { } }
public bool IgnoreExtensionDataObject { get { throw null; } set { } }
public System.Collections.Generic.IEnumerable<System.Type> KnownTypes { get { throw null; } set { } }
public int MaxItemsInObjectGraph { get { throw null; } set { } }
public bool PreserveObjectReferences { get { throw null; } set { } }
public System.Xml.XmlDictionaryString RootName { get { throw null; } set { } }
public System.Xml.XmlDictionaryString RootNamespace { get { throw null; } set { } }
public bool SerializeReadOnlyTypes { get { throw null; } set { } }
}
public static partial class XmlSerializableServices
{
public static void AddDefaultSchema(System.Xml.Schema.XmlSchemaSet schemas, System.Xml.XmlQualifiedName typeQName) { }
public static System.Xml.XmlNode[] ReadNodes(System.Xml.XmlReader xmlReader) { throw null; }
public static void WriteNodes(System.Xml.XmlWriter xmlWriter, System.Xml.XmlNode[] nodes) { }
}
public static partial class XPathQueryGenerator
{
public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, System.Text.StringBuilder rootElementXpath, out System.Xml.XmlNamespaceManager namespaces) { throw null; }
public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, out System.Xml.XmlNamespaceManager namespaces) { throw null; }
}
public partial class XsdDataContractExporter
{
public XsdDataContractExporter() { }
public XsdDataContractExporter(System.Xml.Schema.XmlSchemaSet schemas) { }
public System.Runtime.Serialization.ExportOptions Options { get { throw null; } set { } }
public System.Xml.Schema.XmlSchemaSet Schemas { get { throw null; } }
public bool CanExport(System.Collections.Generic.ICollection<System.Reflection.Assembly> assemblies) { throw null; }
public bool CanExport(System.Collections.Generic.ICollection<System.Type> types) { throw null; }
public bool CanExport(System.Type type) { throw null; }
public void Export(System.Collections.Generic.ICollection<System.Reflection.Assembly> assemblies) { }
public void Export(System.Collections.Generic.ICollection<System.Type> types) { }
public void Export(System.Type type) { }
public System.Xml.XmlQualifiedName GetRootElementName(System.Type type) { throw null; }
public System.Xml.Schema.XmlSchemaType GetSchemaType(System.Type type) { throw null; }
public System.Xml.XmlQualifiedName GetSchemaTypeName(System.Type type) { throw null; }
}
public partial class ExportOptions
{
public ExportOptions() { }
//CODEDOM public System.Runtime.Serialization.IDataContractSurrogate DataContractSurrogate { get { throw null; } set { } }
public System.Collections.ObjectModel.Collection<System.Type> KnownTypes { get { throw null; } }
}
public sealed partial class ExtensionDataObject
{
internal ExtensionDataObject() { }
}
public partial interface IExtensibleDataObject
{
System.Runtime.Serialization.ExtensionDataObject ExtensionData { get; set; }
}
public abstract partial class XmlObjectSerializer
{
protected XmlObjectSerializer() { }
public abstract bool IsStartObject(System.Xml.XmlDictionaryReader reader);
public virtual bool IsStartObject(System.Xml.XmlReader reader) { throw null; }
public virtual object ReadObject(System.IO.Stream stream) { throw null; }
public virtual object ReadObject(System.Xml.XmlDictionaryReader reader) { throw null; }
public abstract object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName);
public virtual object ReadObject(System.Xml.XmlReader reader) { throw null; }
public virtual object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; }
public abstract void WriteEndObject(System.Xml.XmlDictionaryWriter writer);
public virtual void WriteEndObject(System.Xml.XmlWriter writer) { }
public virtual void WriteObject(System.IO.Stream stream, object graph) { }
public virtual void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph) { }
public virtual void WriteObject(System.Xml.XmlWriter writer, object graph) { }
public abstract void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph);
public virtual void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { }
public abstract void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph);
public virtual void WriteStartObject(System.Xml.XmlWriter writer, object graph) { }
}
}
namespace System.Xml
{
public partial interface IFragmentCapableXmlDictionaryWriter
{
bool CanFragment { get; }
void EndFragment();
void StartFragment(System.IO.Stream stream, bool generateSelfContainedTextFragment);
void WriteFragment(byte[] buffer, int offset, int count);
}
public partial interface IStreamProvider
{
System.IO.Stream GetStream();
void ReleaseStream(System.IO.Stream stream);
}
public partial interface IXmlBinaryReaderInitializer
{
void SetInput(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose);
void SetInput(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose);
}
public partial interface IXmlBinaryWriterInitializer
{
void SetOutput(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session, bool ownsStream);
}
public partial interface IXmlDictionary
{
bool TryLookup(int key, out System.Xml.XmlDictionaryString result);
bool TryLookup(string value, out System.Xml.XmlDictionaryString result);
bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result);
}
public partial interface IXmlTextReaderInitializer
{
void SetInput(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose);
void SetInput(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose);
}
public partial interface IXmlTextWriterInitializer
{
void SetOutput(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream);
}
public delegate void OnXmlDictionaryReaderClose(System.Xml.XmlDictionaryReader reader);
public partial class UniqueId
{
public UniqueId() { }
public UniqueId(byte[] guid) { }
public UniqueId(byte[] guid, int offset) { }
public UniqueId(char[] chars, int offset, int count) { }
public UniqueId(System.Guid guid) { }
public UniqueId(string value) { }
public int CharArrayLength { get { throw null; } }
public bool IsGuid { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Xml.UniqueId id1, System.Xml.UniqueId id2) { throw null; }
public static bool operator !=(System.Xml.UniqueId id1, System.Xml.UniqueId id2) { throw null; }
public int ToCharArray(char[] chars, int offset) { throw null; }
public override string ToString() { throw null; }
public bool TryGetGuid(byte[] buffer, int offset) { throw null; }
public bool TryGetGuid(out System.Guid guid) { throw null; }
}
public partial class XmlBinaryReaderSession : System.Xml.IXmlDictionary
{
public XmlBinaryReaderSession() { }
public System.Xml.XmlDictionaryString Add(int id, string value) { throw null; }
public void Clear() { }
public bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { throw null; }
public bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { throw null; }
public bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { throw null; }
}
public partial class XmlBinaryWriterSession
{
public XmlBinaryWriterSession() { }
public void Reset() { }
public virtual bool TryAdd(System.Xml.XmlDictionaryString value, out int key) { throw null; }
}
public partial class XmlDictionary : System.Xml.IXmlDictionary
{
public XmlDictionary() { }
public XmlDictionary(int capacity) { }
public static System.Xml.IXmlDictionary Empty { get { throw null; } }
public virtual System.Xml.XmlDictionaryString Add(string value) { throw null; }
public virtual bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { throw null; }
public virtual bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { throw null; }
public virtual bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { throw null; }
}
public abstract partial class XmlDictionaryReader : System.Xml.XmlReader
{
protected XmlDictionaryReader() { }
public virtual bool CanCanonicalize { get { throw null; } }
public virtual System.Xml.XmlDictionaryReaderQuotas Quotas { get { throw null; } }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateDictionaryReader(System.Xml.XmlReader reader) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas, int maxBufferSize, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas, int maxBufferSize, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateTextReader(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateTextReader(System.IO.Stream stream, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public virtual void EndCanonicalization() { }
public virtual string GetAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri) { throw null; }
public virtual int IndexOfLocalName(string[] localNames, string namespaceUri) { throw null; }
public virtual int IndexOfLocalName(System.Xml.XmlDictionaryString[] localNames, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual bool IsLocalName(string localName) { throw null; }
public virtual bool IsLocalName(System.Xml.XmlDictionaryString localName) { throw null; }
public virtual bool IsNamespaceUri(string namespaceUri) { throw null; }
public virtual bool IsNamespaceUri(System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual bool IsStartArray(out System.Type type) { throw null; }
public virtual bool IsStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
protected bool IsTextNode(System.Xml.XmlNodeType nodeType) { throw null; }
public virtual void MoveToStartElement() { }
public virtual void MoveToStartElement(string name) { }
public virtual void MoveToStartElement(string localName, string namespaceUri) { }
public virtual void MoveToStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public virtual int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, System.DateTime[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, System.Guid[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, short[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, int[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, long[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, System.TimeSpan[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.DateTime[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, double[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.Guid[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, short[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, int[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, long[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, float[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.TimeSpan[] array, int offset, int count) { throw null; }
public virtual bool[] ReadBooleanArray(string localName, string namespaceUri) { throw null; }
public virtual bool[] ReadBooleanArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public override object ReadContentAs(System.Type type, System.Xml.IXmlNamespaceResolver namespaceResolver) { throw null; }
public virtual byte[] ReadContentAsBase64() { throw null; }
public virtual byte[] ReadContentAsBinHex() { throw null; }
protected byte[] ReadContentAsBinHex(int maxByteArrayContentLength) { throw null; }
public virtual int ReadContentAsChars(char[] chars, int offset, int count) { throw null; }
public override decimal ReadContentAsDecimal() { throw null; }
public override float ReadContentAsFloat() { throw null; }
public virtual System.Guid ReadContentAsGuid() { throw null; }
public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri) { throw null; }
public override string ReadContentAsString() { throw null; }
protected string ReadContentAsString(int maxStringContentLength) { throw null; }
public virtual string ReadContentAsString(string[] strings, out int index) { throw null; }
public virtual string ReadContentAsString(System.Xml.XmlDictionaryString[] strings, out int index) { throw null; }
public virtual System.TimeSpan ReadContentAsTimeSpan() { throw null; }
public virtual System.Xml.UniqueId ReadContentAsUniqueId() { throw null; }
public virtual System.DateTime[] ReadDateTimeArray(string localName, string namespaceUri) { throw null; }
public virtual System.DateTime[] ReadDateTimeArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual decimal[] ReadDecimalArray(string localName, string namespaceUri) { throw null; }
public virtual decimal[] ReadDecimalArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual double[] ReadDoubleArray(string localName, string namespaceUri) { throw null; }
public virtual double[] ReadDoubleArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual byte[] ReadElementContentAsBase64() { throw null; }
public virtual byte[] ReadElementContentAsBinHex() { throw null; }
public override bool ReadElementContentAsBoolean() { throw null; }
public override System.DateTime ReadElementContentAsDateTime() { throw null; }
public override decimal ReadElementContentAsDecimal() { throw null; }
public override double ReadElementContentAsDouble() { throw null; }
public override float ReadElementContentAsFloat() { throw null; }
public virtual System.Guid ReadElementContentAsGuid() { throw null; }
public override int ReadElementContentAsInt() { throw null; }
public override long ReadElementContentAsLong() { throw null; }
public override string ReadElementContentAsString() { throw null; }
public virtual System.TimeSpan ReadElementContentAsTimeSpan() { throw null; }
public virtual System.Xml.UniqueId ReadElementContentAsUniqueId() { throw null; }
public virtual void ReadFullStartElement() { }
public virtual void ReadFullStartElement(string name) { }
public virtual void ReadFullStartElement(string localName, string namespaceUri) { }
public virtual void ReadFullStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public virtual System.Guid[] ReadGuidArray(string localName, string namespaceUri) { throw null; }
public virtual System.Guid[] ReadGuidArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual short[] ReadInt16Array(string localName, string namespaceUri) { throw null; }
public virtual short[] ReadInt16Array(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual int[] ReadInt32Array(string localName, string namespaceUri) { throw null; }
public virtual int[] ReadInt32Array(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual long[] ReadInt64Array(string localName, string namespaceUri) { throw null; }
public virtual long[] ReadInt64Array(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual float[] ReadSingleArray(string localName, string namespaceUri) { throw null; }
public virtual float[] ReadSingleArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual void ReadStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public override string ReadString() { throw null; }
protected string ReadString(int maxStringContentLength) { throw null; }
public virtual System.TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri) { throw null; }
public virtual System.TimeSpan[] ReadTimeSpanArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count) { throw null; }
public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[] inclusivePrefixes) { }
public virtual bool TryGetArrayLength(out int count) { throw null; }
public virtual bool TryGetBase64ContentLength(out int length) { throw null; }
public virtual bool TryGetLocalNameAsDictionaryString(out System.Xml.XmlDictionaryString localName) { throw null; }
public virtual bool TryGetNamespaceUriAsDictionaryString(out System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual bool TryGetValueAsDictionaryString(out System.Xml.XmlDictionaryString value) { throw null; }
}
public sealed partial class XmlDictionaryReaderQuotas
{
public XmlDictionaryReaderQuotas() { }
public static System.Xml.XmlDictionaryReaderQuotas Max { get { throw null; } }
[System.ComponentModel.DefaultValueAttribute(16384)]
public int MaxArrayLength { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(4096)]
public int MaxBytesPerRead { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(32)]
public int MaxDepth { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(16384)]
public int MaxNameTableCharCount { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(8192)]
public int MaxStringContentLength { get { throw null; } set { } }
public System.Xml.XmlDictionaryReaderQuotaTypes ModifiedQuotas { get { throw null; } }
public void CopyTo(System.Xml.XmlDictionaryReaderQuotas quotas) { }
}
[System.FlagsAttribute]
public enum XmlDictionaryReaderQuotaTypes
{
MaxArrayLength = 4,
MaxBytesPerRead = 8,
MaxDepth = 1,
MaxNameTableCharCount = 16,
MaxStringContentLength = 2,
}
public partial class XmlDictionaryString
{
public XmlDictionaryString(System.Xml.IXmlDictionary dictionary, string value, int key) { }
public System.Xml.IXmlDictionary Dictionary { get { throw null; } }
public static System.Xml.XmlDictionaryString Empty { get { throw null; } }
public int Key { get { throw null; } }
public string Value { get { throw null; } }
public override string ToString() { throw null; }
}
public abstract partial class XmlDictionaryWriter : System.Xml.XmlWriter
{
protected XmlDictionaryWriter() { }
public virtual bool CanCanonicalize { get { throw null; } }
public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session, bool ownsStream) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateDictionaryWriter(System.Xml.XmlWriter writer) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateMtomWriter(System.IO.Stream stream, System.Text.Encoding encoding, int maxSizeInBytes, string startInfo) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateMtomWriter(System.IO.Stream stream, System.Text.Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream, System.Text.Encoding encoding) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream) { throw null; }
public virtual void EndCanonicalization() { }
public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[] inclusivePrefixes) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.DateTime[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.Guid[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.TimeSpan[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.DateTime[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, double[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.Guid[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, short[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, int[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, long[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, float[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.TimeSpan[] array, int offset, int count) { }
public void WriteAttributeString(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
public void WriteAttributeString(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
public override System.Threading.Tasks.Task WriteBase64Async(byte[] buffer, int index, int count) { throw null; }
public void WriteElementString(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
public void WriteElementString(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
public virtual void WriteNode(System.Xml.XmlDictionaryReader reader, bool defattr) { }
public override void WriteNode(System.Xml.XmlReader reader, bool defattr) { }
public virtual void WriteQualifiedName(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public virtual void WriteStartAttribute(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public void WriteStartAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public virtual void WriteStartElement(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public void WriteStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public virtual void WriteString(System.Xml.XmlDictionaryString value) { }
protected virtual void WriteTextNode(System.Xml.XmlDictionaryReader reader, bool isAttribute) { }
public virtual void WriteValue(System.Guid value) { }
public virtual void WriteValue(System.TimeSpan value) { }
public virtual void WriteValue(System.Xml.IStreamProvider value) { }
public virtual void WriteValue(System.Xml.UniqueId value) { }
public virtual void WriteValue(System.Xml.XmlDictionaryString value) { }
public virtual System.Threading.Tasks.Task WriteValueAsync(System.Xml.IStreamProvider value) { throw null; }
public virtual void WriteXmlAttribute(string localName, string value) { }
public virtual void WriteXmlAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString value) { }
public virtual void WriteXmlnsAttribute(string prefix, string namespaceUri) { }
public virtual void WriteXmlnsAttribute(string prefix, System.Xml.XmlDictionaryString namespaceUri) { }
}
}
| |
using System;
using System.Text;
using System.Collections;
namespace Majestic12
{
/// <summary>
/// This class will control HTML tag heuristics that will allow faster matching of tags
/// to avoid long cycles as well as creation of same strings over and over again.
///
/// This is effectively a fancy hash lookup table with attributes being hashed in context of tag
/// </summary>
///<exclude/>
public class HTMLheuristics : IDisposable
{
/// <summary>
/// Maximum number of strings allowed to be set (all lower-cased)
/// </summary>
const int MAX_STRINGS=1024;
/// <summary>
/// Maximum number of chars to be taken into account
/// </summary>
const int MAX_CHARS=byte.MaxValue;
/// <summary>
/// Array in which we will keep char hints to quickly match ID (if non-zero) of tag
/// </summary>
short[,] sChars=new short[byte.MaxValue+1,byte.MaxValue+1];
/// <summary>
/// Strings used, once matched they will be returned to avoid creation of a brand new string
/// and all associated costs with it
/// </summary>
string[] sStrings=new string[MAX_STRINGS];
/// <summary>
/// Binary data represending tag strings is here: case sensitive: lower case for even even value, and odd for each odd
/// for the same string
/// </summary>
byte[][] bTagData=new byte[MAX_STRINGS*2][];
/// <summary>
/// List of added tags to avoid dups
/// </summary>
Hashtable oAddedTags=new Hashtable();
/// <summary>
/// Hash that will contain single char mapping hash
/// </summary>
byte[][] bAttributes=new byte[MAX_STRINGS*2][];
/// <summary>
/// Binary data represending attribute strings is here: case sensitive: lower case for even even value, and odd for each odd
/// for the same string
/// </summary>
byte[][] bAttrData=new byte[MAX_STRINGS*2][];
/// <summary>
/// List of added attributes to avoid dups
/// </summary>
Hashtable oAddedAttributes=new Hashtable();
string[] sAttrs=new string[MAX_STRINGS];
/// <summary>
/// This array will contain all double char strings
/// </summary>
static string[,] sAllTwoCharStrings=null;
/// <summary>
/// Static constructor
/// </summary>
static HTMLheuristics()
{
sAllTwoCharStrings=new string[(MAX_CHARS+1),(MAX_CHARS+1)];
// we will create all possible strings for two bytes combinations - this will allow
// to cater for all two char combinations at cost of mere 256kb of RAM per instance
for(int i=0; i<sAllTwoCharStrings.Length; i++)
{
byte bChar1=(byte)(i>>8);
byte bChar2=(byte)(i&0xFF);
sAllTwoCharStrings[bChar1,bChar2]=((string)(((char)bChar1).ToString()+((char)bChar2).ToString())).ToLower();
}
}
/// <summary>
/// Default constructor
/// </summary>
public HTMLheuristics()
{
}
/// <summary>
/// Adds tag to list of tracked tags (don't add too many, if you have got multiple same first
/// 2 chars then duplicates won't be added, so make sure the first added tags are the MOST LIKELY to be found)
/// </summary>
/// <param name="sTag">Tag: strictly ASCII only</param>
/// <param name="sAttributeNames">Comma delimited list of attributed</param>
/// <param name="bAddClosed">If true then closed version of tag added</param>
/// <returns>True if tag was added, false otherwise (it may already be added, or leads to hash clash)</returns>
public bool AddTag(string p_sTag,string sAttributeNames)
{
string sTag=p_sTag.ToLower().Trim();
if(sTag.Length==0 || sTag.Length>32 || oAddedTags.Contains(sTag))
return false;
if(oAddedTags.Count>=byte.MaxValue)
return false;
// ID should not be zero as it is an indicator of no match
short usID=(short)(oAddedTags.Count+1);
oAddedTags[sTag]=usID;
// remember tag string: it will be returned in case of matching
sStrings[usID]=sTag;
// add both lower and upper case tag values
if(!AddTag(sTag,usID,(short) (usID*2+0)))
return false;
if(!AddTag(sTag.ToUpper(),usID,(short)(usID*2+1)))
return false;
// allocate memory for attribute hashes for this tag
bAttrData[usID]=new byte[byte.MaxValue+1];
// now add attribute names
foreach(string p_sAName in sAttributeNames.ToLower().Split(','))
{
string sAName=p_sAName.Trim();
if(sAName.Length==0)
continue;
// only add attribute if we have not got it added for same first char of the same tag:
if(bAttrData[usID][sAName[0]]>0 || bAttrData[usID][char.ToUpper(sAName[0])]>0)
continue;
int iAttrID=oAddedAttributes.Count+1;
if(oAddedAttributes.Contains(sAName))
iAttrID=(int)oAddedAttributes[sAName];
else
{
oAddedAttributes[sAName]=iAttrID;
sAttrs[iAttrID]=sAName;
}
// add both lower and upper case tag values
AddAttribute(sAName,usID,(short)(iAttrID*2+0));
AddAttribute(sAName.ToUpper(),usID,(short)(iAttrID*2+1));
}
return true;
}
void AddAttribute(string sAttr,short usID,short usAttrID)
{
if(sAttr.Length==0)
return;
byte bChar=(byte)sAttr[0];
bAttributes[usAttrID]=Encoding.Default.GetBytes(sAttr);
bAttrData[usID][bChar]=(byte) usAttrID;
}
/// <summary>
/// Returns string for ID returned by GetMatch
/// </summary>
/// <param name="iID">ID</param>
/// <returns>string</returns>
public string GetString(int iID)
{
return sStrings[(iID>>1)];
}
public string GetTwoCharString(byte cChar1,byte cChar2)
{
return HTMLheuristics.sAllTwoCharStrings[cChar1,cChar2];
}
public byte[] GetStringData(int iID)
{
return bTagData[iID];
}
public short MatchTag(byte cChar1,byte cChar2)
{
return sChars[cChar1,cChar2];
}
public short MatchAttr(byte bChar,int iTagID)
{
return bAttrData[iTagID>>1][bChar];
}
public byte[] GetAttrData(int iAttrID)
{
return bAttributes[iAttrID];
}
public string GetAttr(int iAttrID)
{
return sAttrs[(iAttrID>>1)];
}
bool AddTag(string sTag,short usID,short usDataID)
{
if(sTag.Length==0)
return false;
bTagData[usDataID]=Encoding.Default.GetBytes(sTag);
if(sTag.Length==1)
{
// ok just one char, in which case we will mark possible second char that can be
// '>', ' ' and other whitespace
// we will use negative ID to hint that this is single char hit
if(!SetHash(sTag[0],' ',(short)(-1*usDataID)))
return false;
if(!SetHash(sTag[0],'\t',(short)(-1*usDataID)))
return false;
if(!SetHash(sTag[0],'\r',(short)(-1*usDataID)))
return false;
if(!SetHash(sTag[0],'\n',(short)(-1*usDataID)))
return false;
if(!SetHash(sTag[0],'>',(short)(-1*usDataID)))
return false;
}
else
{
if(!SetHash(sTag[0],sTag[1],usDataID))
return false;
}
return true;
}
bool SetHash(char cChar1,char cChar2,short usID)
{
// already exists
if(sChars[(byte)cChar1,(byte)cChar2]!=0)
return false;
sChars[(byte)cChar1,(byte)cChar2]=usID;
return true;
}
bool bDisposed=false;
/// <summary>
/// Disposes of resources
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool bDisposing)
{
if(!bDisposed)
{
sChars=null;
oAddedTags=null;
sStrings=null;
bTagData=null;
}
bDisposed=true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryAddTests
{
#region Test methods
[Fact]
public static void CheckByteAddTest()
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteAdd(array[i], array[j]);
}
}
}
[Fact]
public static void CheckSByteAddTest()
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteAdd(array[i], array[j]);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortAddTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortAdd(array[i], array[j], useInterpreter);
VerifyUShortAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortAddTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortAdd(array[i], array[j], useInterpreter);
VerifyShortAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntAddTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntAdd(array[i], array[j], useInterpreter);
VerifyUIntAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntAddTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntAdd(array[i], array[j], useInterpreter);
VerifyIntAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongAddTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongAdd(array[i], array[j], useInterpreter);
VerifyULongAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongAddTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongAdd(array[i], array[j], useInterpreter);
VerifyLongAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatAddTest(bool useInterpreter)
{
float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyFloatAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleAddTest(bool useInterpreter)
{
double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDoubleAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalAddTest(bool useInterpreter)
{
decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDecimalAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCharAddTest(bool useInterpreter)
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCharAdd(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteAdd(byte a, byte b)
{
Expression aExp = Expression.Constant(a, typeof(byte));
Expression bExp = Expression.Constant(b, typeof(byte));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
private static void VerifySByteAdd(sbyte a, sbyte b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte));
Expression bExp = Expression.Constant(b, typeof(sbyte));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
private static void VerifyUShortAdd(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Add(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort)(a + b)), f());
}
private static void VerifyUShortAddOvf(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.AddChecked(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
int expected = a + b;
if (expected < 0 || expected > ushort.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyShortAdd(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Add(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short)(a + b)), f());
}
private static void VerifyShortAddOvf(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.AddChecked(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
int expected = a + b;
if (expected < short.MinValue || expected > short.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyUIntAdd(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Add(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a + b), f());
}
private static void VerifyUIntAddOvf(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.AddChecked(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
long expected = a + (long)b;
if (expected < 0 || expected > uint.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyIntAdd(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Add(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a + b), f());
}
private static void VerifyIntAddOvf(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.AddChecked(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
long expected = a + (long)b;
if (expected < int.MinValue || expected > int.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyULongAdd(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Add(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a + b), f());
}
private static void VerifyULongAddOvf(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.AddChecked(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
ulong expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyLongAdd(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Add(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a + b), f());
}
private static void VerifyLongAddOvf(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.AddChecked(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
long expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyFloatAdd(float a, float b, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Add(
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
float expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyDoubleAdd(double a, double b, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Add(
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
double expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyDecimalAdd(decimal a, decimal b, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Add(
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
decimal expected = 0;
try
{
expected = a + b;
}
catch(OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyCharAdd(char a, char b)
{
Expression aExp = Expression.Constant(a, typeof(char));
Expression bExp = Expression.Constant(b, typeof(char));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.Add(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void CannotReduceChecked()
{
Expression exp = Expression.AddChecked(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Add(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.Add(Expression.Constant(""), null));
}
[Fact]
public static void CheckedThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.AddChecked(null, Expression.Constant("")));
}
[Fact]
public static void CheckedThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.AddChecked(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.Add(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.Add(Expression.Constant(1), value));
}
[Fact]
public static void CheckedThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.AddChecked(value, Expression.Constant(1)));
}
[Fact]
public static void CheckedThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.Add(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
BinaryExpression e1 = Expression.Add(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a + b)", e1.ToString());
BinaryExpression e2 = Expression.AddChecked(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a + b)", e2.ToString());
}
}
}
| |
#region Copyright
/*
Copyright 2014 Cluster Reply s.r.l.
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
/// -----------------------------------------------------------------------------------------------------------
/// Module : FtpAdapter.cs
/// Description : The main adapter class which inherits from Adapter
/// -----------------------------------------------------------------------------------------------------------
#region Using Directives
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel.Description;
using Microsoft.ServiceModel.Channels.Common;
#endregion
namespace Reply.Cluster.Mercury.Adapters.Ftp
{
public enum PollingType
{
Simple,
Managed
}
public enum OverwriteAction
{
None,
Replace,
Append
}
public class FtpAdapter : Adapter
{
// Scheme associated with the adapter
internal const string SCHEME = "ftp";
// Namespace for the proxy that will be generated from the adapter schema
internal const string SERVICENAMESPACE = "http://mercury.cluster.reply.eu/adapters/ftp/2014/05";
// Initializes the AdapterEnvironmentSettings class
private static AdapterEnvironmentSettings environmentSettings = new AdapterEnvironmentSettings();
#region Custom Generated Fields
private PollingType pollingType;
private int pollingInterval;
private string scheduleName;
private string tempFolder;
private string remoteBackup;
private string localBackup;
private OverwriteAction overwriteAction;
private bool zipFile;
#endregion Custom Generated Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the FtpAdapter class
/// </summary>
public FtpAdapter()
: base(environmentSettings)
{
Settings.Metadata.DefaultMetadataNamespace = SERVICENAMESPACE;
}
/// <summary>
/// Initializes a new instance of the FtpAdapter class with a binding
/// </summary>
public FtpAdapter(FtpAdapter binding)
: base(binding)
{
this.PollingType = binding.PollingType;
this.PollingInterval = binding.PollingInterval;
this.ScheduleName = binding.ScheduleName;
this.TempFolder = binding.TempFolder;
this.RemoteBackup = binding.RemoteBackup;
this.LocalBackup = binding.LocalBackup;
this.OverwriteAction = binding.OverwriteAction;
this.ZipFile = binding.ZipFile;
}
#endregion Constructor
#region Custom Generated Properties
[System.ComponentModel.Category("Polling")]
[System.Configuration.ConfigurationProperty("pollingType", DefaultValue = PollingType.Simple)]
public PollingType PollingType
{
get
{
return this.pollingType;
}
set
{
this.pollingType = value;
}
}
[System.ComponentModel.Category("Polling")]
[System.Configuration.ConfigurationProperty("pollingInterval", DefaultValue = 60)]
public int PollingInterval
{
get
{
return this.pollingInterval;
}
set
{
this.pollingInterval = value;
}
}
[System.ComponentModel.Category("Polling")]
[System.Configuration.ConfigurationProperty("ScheduleName")]
public string ScheduleName
{
get
{
return this.scheduleName;
}
set
{
this.scheduleName = value;
}
}
[System.ComponentModel.Category("Folders")]
[System.Configuration.ConfigurationProperty("TempFolder")]
public string TempFolder
{
get
{
return this.tempFolder;
}
set
{
this.tempFolder = value;
}
}
[System.ComponentModel.Category("Folders")]
[System.Configuration.ConfigurationProperty("RemoteBackup")]
public string RemoteBackup
{
get
{
return this.remoteBackup;
}
set
{
this.remoteBackup = value;
}
}
[System.ComponentModel.Category("Folders")]
[System.Configuration.ConfigurationProperty("LocalBackup")]
public string LocalBackup
{
get
{
return this.localBackup;
}
set
{
this.localBackup = value;
}
}
[System.ComponentModel.Category("Overwrite")]
[System.Configuration.ConfigurationProperty("overwriteAction", DefaultValue = OverwriteAction.None)]
public OverwriteAction OverwriteAction
{
get
{
return this.overwriteAction;
}
set
{
this.overwriteAction = value;
}
}
[System.ComponentModel.Category("Compression")]
[System.Configuration.ConfigurationProperty("zipFile", DefaultValue = false)]
public bool ZipFile
{
get
{
return this.zipFile;
}
set
{
this.zipFile = value;
}
}
#endregion Custom Generated Properties
#region Public Properties
/// <summary>
/// Gets the URI transport scheme that is used by the adapter
/// </summary>
public override string Scheme
{
get
{
return SCHEME;
}
}
#endregion Public Properties
#region Protected Methods
/// <summary>
/// Creates a ConnectionUri instance from the provided Uri
/// </summary>
protected override ConnectionUri BuildConnectionUri(Uri uri)
{
return new FtpAdapterConnectionUri(uri);
}
/// <summary>
/// Builds a connection factory from the ConnectionUri and ClientCredentials
/// </summary>
protected override IConnectionFactory BuildConnectionFactory(
ConnectionUri connectionUri
, ClientCredentials clientCredentials
, System.ServiceModel.Channels.BindingContext context)
{
return new FtpAdapterConnectionFactory(connectionUri, clientCredentials, this);
}
/// <summary>
/// Returns a clone of the adapter object
/// </summary>
protected override Adapter CloneAdapter()
{
return new FtpAdapter(this);
}
/// <summary>
/// Indicates whether the provided TConnectionHandler is supported by the adapter or not
/// </summary>
protected override bool IsHandlerSupported<TConnectionHandler>()
{
return (
typeof(IOutboundHandler) == typeof(TConnectionHandler)
|| typeof(IInboundHandler) == typeof(TConnectionHandler));
}
/// <summary>
/// Gets the namespace that is used when generating schema and WSDL
/// </summary>
protected override string Namespace
{
get
{
return SERVICENAMESPACE;
}
}
#endregion Protected Methods
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.ScriptEngine.Shared
{
[Serializable]
public class EventAbortException : Exception
{
public EventAbortException()
{
}
protected EventAbortException(
SerializationInfo info,
StreamingContext context)
{
}
}
[Serializable]
public class SelfDeleteException : Exception
{
public SelfDeleteException()
{
}
protected SelfDeleteException(
SerializationInfo info,
StreamingContext context)
{
}
}
[Serializable]
public class ScriptDeleteException : Exception
{
public ScriptDeleteException()
{
}
protected ScriptDeleteException(
SerializationInfo info,
StreamingContext context)
{
}
}
/// <summary>
/// Used to signal when the script is stopping in co-operation with the script engine
/// (instead of through Thread.Abort()).
/// </summary>
[Serializable]
public class ScriptCoopStopException : Exception
{
public ScriptCoopStopException()
{
}
protected ScriptCoopStopException(
SerializationInfo info,
StreamingContext context)
{
}
}
public class DetectParams
{
public const int AGENT = 1;
public const int ACTIVE = 2;
public const int PASSIVE = 4;
public const int SCRIPTED = 8;
public const int OS_NPC = 0x01000000;
public DetectParams()
{
Key = UUID.Zero;
OffsetPos = new LSL_Types.Vector3();
LinkNum = 0;
Group = UUID.Zero;
Name = String.Empty;
Owner = UUID.Zero;
Position = new LSL_Types.Vector3();
Rotation = new LSL_Types.Quaternion();
Type = 0;
Velocity = new LSL_Types.Vector3();
initializeSurfaceTouch();
}
public UUID Key;
public LSL_Types.Vector3 OffsetPos;
public int LinkNum;
public UUID Group;
public string Name;
public UUID Owner;
public LSL_Types.Vector3 Position;
public LSL_Types.Quaternion Rotation;
public int Type;
public LSL_Types.Vector3 Velocity;
private LSL_Types.Vector3 touchST;
public LSL_Types.Vector3 TouchST { get { return touchST; } }
private LSL_Types.Vector3 touchNormal;
public LSL_Types.Vector3 TouchNormal { get { return touchNormal; } }
private LSL_Types.Vector3 touchBinormal;
public LSL_Types.Vector3 TouchBinormal { get { return touchBinormal; } }
private LSL_Types.Vector3 touchPos;
public LSL_Types.Vector3 TouchPos { get { return touchPos; } }
private LSL_Types.Vector3 touchUV;
public LSL_Types.Vector3 TouchUV { get { return touchUV; } }
private int touchFace;
public int TouchFace { get { return touchFace; } }
// This can be done in two places including the constructor
// so be carefull what gets added here
private void initializeSurfaceTouch()
{
touchST = new LSL_Types.Vector3(-1.0, -1.0, 0.0);
touchNormal = new LSL_Types.Vector3();
touchBinormal = new LSL_Types.Vector3();
touchPos = new LSL_Types.Vector3();
touchUV = new LSL_Types.Vector3(-1.0, -1.0, 0.0);
touchFace = -1;
}
/*
* Set up the surface touch detected values
*/
public SurfaceTouchEventArgs SurfaceTouchArgs
{
set
{
if (value == null)
{
// Initialise to defaults if no value
initializeSurfaceTouch();
}
else
{
// Set the values from the touch data provided by the client
touchST = new LSL_Types.Vector3(value.STCoord);
touchUV = new LSL_Types.Vector3(value.UVCoord);
touchNormal = new LSL_Types.Vector3(value.Normal);
touchBinormal = new LSL_Types.Vector3(value.Binormal);
touchPos = new LSL_Types.Vector3(value.Position);
touchFace = value.FaceIndex;
}
}
}
public void Populate(Scene scene)
{
SceneObjectPart part = scene.GetSceneObjectPart(Key);
if (part == null) // Avatar, maybe?
{
ScenePresence presence = scene.GetScenePresence(Key);
if (presence == null)
return;
Name = presence.Firstname + " " + presence.Lastname;
Owner = Key;
Position = new LSL_Types.Vector3(presence.AbsolutePosition);
Rotation = new LSL_Types.Quaternion(
presence.Rotation.X,
presence.Rotation.Y,
presence.Rotation.Z,
presence.Rotation.W);
Velocity = new LSL_Types.Vector3(presence.Velocity);
Type = 0x01; // Avatar
if (presence.PresenceType == PresenceType.Npc)
Type = 0x20;
if (presence.Velocity != Vector3.Zero)
Type |= ACTIVE;
Group = presence.ControllingClient.ActiveGroupId;
return;
}
part = part.ParentGroup.RootPart; // We detect objects only
LinkNum = 0; // Not relevant
Group = part.GroupID;
Name = part.Name;
Owner = part.OwnerID;
if (part.Velocity == Vector3.Zero)
Type = PASSIVE;
else
Type = ACTIVE;
foreach (SceneObjectPart p in part.ParentGroup.Parts)
{
if (p.Inventory.ContainsScripts())
{
Type |= SCRIPTED; // Scripted
break;
}
}
Position = new LSL_Types.Vector3(part.AbsolutePosition);
Quaternion wr = part.ParentGroup.GroupRotation;
Rotation = new LSL_Types.Quaternion(wr.X, wr.Y, wr.Z, wr.W);
Velocity = new LSL_Types.Vector3(part.Velocity);
}
public void Populate(Scene scene, DetectedObject obj)
{
if(obj.keyUUID == UUID.Zero) // land
{
Position = new LSL_Types.Vector3(obj.posVector);
Rotation.s = 1.0;
return;
}
if((obj.colliderType & 0x21) != 0) // avatar or npc
{
ScenePresence presence = scene.GetScenePresence(obj.keyUUID);
if (presence == null)
return;
Name = obj.nameStr;
Key = obj.keyUUID;
Owner = obj.ownerUUID;
Group = obj.groupUUID;
Position = new LSL_Types.Vector3(obj.posVector);
Rotation = new LSL_Types.Quaternion(obj.rotQuat);
Velocity = new LSL_Types.Vector3(obj.velVector);
LinkNum = obj.linkNumber;
Type = obj.colliderType;
return;
}
SceneObjectPart part = scene.GetSceneObjectPart(obj.keyUUID);
if(part == null)
return;
Name = obj.nameStr;
Key = obj.keyUUID;
Owner = obj.ownerUUID;
Group = obj.groupUUID;
Position = new LSL_Types.Vector3(obj.posVector);
Rotation = new LSL_Types.Quaternion(obj.rotQuat);
Velocity = new LSL_Types.Vector3(obj.velVector);
LinkNum = obj.linkNumber;
if(obj.velVector == Vector3.Zero)
Type = 4;
else
Type = 2;
part = part.ParentGroup.RootPart;
foreach (SceneObjectPart p in part.ParentGroup.Parts)
{
if (p.Inventory.ContainsScripts())
{
// at sl a physical prim is active also if has active scripts
// assuming all scripts are in run state to save time
if((part.Flags & PrimFlags.Physics) != 0 )
Type = 10; // script + active
else
Type |= SCRIPTED; // Scripted
break;
}
}
}
}
/// <summary>
/// Holds all the data required to execute a scripting event.
/// </summary>
public class EventParams
{
public EventParams(string eventName, Object[] eventParams, DetectParams[] detectParams)
{
EventName = eventName;
Params = eventParams;
DetectParams = detectParams;
}
public string EventName;
public Object[] Params;
public DetectParams[] DetectParams;
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using fyiReporting.RDL;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for ReportCtl.
/// </summary>
internal class PropertyCtl : System.Windows.Forms.UserControl
{
private DesignXmlDraw _Draw;
private DesignCtl _DesignCtl;
private ICollection _NameCollection = null;
private Label label1;
private PropertyGrid pgSelected;
private Button bClose;
private ComboBox cbReportItems;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private readonly string REPORT = "*Report*";
private readonly string GROUP = "*Group Selection*";
private readonly string NONAME = "*Unnamed*";
internal PropertyCtl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
}
internal void Reset()
{
_Draw = null;
_DesignCtl = null;
this.pgSelected.SelectedObject = null;
cbReportItems.Items.Clear();
_NameCollection = null;
}
internal void ResetSelection(DesignXmlDraw d, DesignCtl dc)
{
_Draw = d;
_DesignCtl = dc;
if (_Draw == null)
{
this.pgSelected.SelectedObject = null;
cbReportItems.Items.Clear();
return;
}
SetPropertyNames();
if (_Draw.SelectedCount == 0)
{
this.pgSelected.SelectedObject = new PropertyReport(_Draw, dc);
cbReportItems.SelectedItem = REPORT;
}
else if (SingleReportItemType())
{
XmlNode n = _Draw.SelectedList[0];
if (_Draw.SelectedCount > 1)
{
int si = cbReportItems.Items.Add(GROUP);
cbReportItems.SelectedIndex = si;
}
else
{
XmlAttribute xAttr = n.Attributes["Name"];
if (xAttr == null)
{
int si = cbReportItems.Items.Add(NONAME);
cbReportItems.SelectedIndex = si;
}
else
cbReportItems.SelectedItem = xAttr.Value;
}
switch (n.Name)
{
case "Textbox":
this.pgSelected.SelectedObject = new PropertyTextbox(_Draw, dc, _Draw.SelectedList);
break;
case "Rectangle":
this.pgSelected.SelectedObject = new PropertyRectangle(_Draw, dc, _Draw.SelectedList);
break;
case "Chart":
this.pgSelected.SelectedObject = new PropertyChart(_Draw, dc, _Draw.SelectedList);
break;
case "Image":
this.pgSelected.SelectedObject = new PropertyImage(_Draw, dc, _Draw.SelectedList);
break;
case "List":
this.pgSelected.SelectedObject = new PropertyList(_Draw, dc, _Draw.SelectedList);
break;
case "Subreport":
this.pgSelected.SelectedObject = new PropertySubreport(_Draw, dc, _Draw.SelectedList);
break;
case "CustomReportItem":
default:
this.pgSelected.SelectedObject = new PropertyReportItem(_Draw, dc, _Draw.SelectedList);
break;
}
}
else
{
int si = cbReportItems.Items.Add(GROUP);
cbReportItems.SelectedIndex = si;
this.pgSelected.SelectedObject = new PropertyReportItem(_Draw, dc, _Draw.SelectedList);
}
}
/// <summary>
/// Fills out the names of the report items available in the report and all other objects with names
/// </summary>
private void SetPropertyNames()
{
if (_NameCollection != _Draw.ReportNames.ReportItemNames)
{
cbReportItems.Items.Clear();
_NameCollection = _Draw.ReportNames.ReportItemNames;
}
else
{ // ensure our list count is the same as the number of report items
int count = cbReportItems.Items.Count;
if (cbReportItems.Items.Contains(this.REPORT))
count--;
if (cbReportItems.Items.Contains(this.GROUP))
count--;
if (cbReportItems.Items.Contains(this.NONAME))
count--;
if (count != _NameCollection.Count)
cbReportItems.Items.Clear(); // we need to rebuild
}
if (cbReportItems.Items.Count == 0)
{
cbReportItems.Items.Add(this.REPORT);
foreach (object o in _NameCollection)
{
cbReportItems.Items.Add(o);
}
}
else
{
try
{
cbReportItems.Items.Remove(this.GROUP);
}
catch { }
try
{
cbReportItems.Items.Remove(this.NONAME);
}
catch { }
}
}
/// <summary>
/// Returns true if all selected reportitems are of the same type
/// </summary>
/// <returns></returns>
private bool SingleReportItemType()
{
if (_Draw.SelectedCount == 1)
return true;
string t = _Draw.SelectedList[0].Name;
if (t == "CustomReportItem") // when multiple CustomReportItem don't do group change.
return false;
for (int i = 1; i < _Draw.SelectedList.Count; i++)
{
if (t != _Draw.SelectedList[i].Name)
return false;
}
return true;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.pgSelected = new System.Windows.Forms.PropertyGrid();
this.bClose = new System.Windows.Forms.Button();
this.cbReportItems = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// label1
//
this.label1.BackColor = System.Drawing.SystemColors.Control;
this.label1.Dock = System.Windows.Forms.DockStyle.Top;
this.label1.ForeColor = System.Drawing.SystemColors.InfoText;
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(240, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Properties";
//
// pgSelected
//
this.pgSelected.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pgSelected.Location = new System.Drawing.Point(0, 40);
this.pgSelected.Name = "pgSelected";
this.pgSelected.Size = new System.Drawing.Size(240, 240);
this.pgSelected.TabIndex = 2;
//
// bClose
//
this.bClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.bClose.CausesValidation = false;
this.bClose.FlatAppearance.BorderSize = 0;
this.bClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bClose.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bClose.Location = new System.Drawing.Point(223, -2);
this.bClose.Name = "bClose";
this.bClose.Size = new System.Drawing.Size(15, 20);
this.bClose.TabIndex = 3;
this.bClose.Text = "x";
this.bClose.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this.bClose.UseVisualStyleBackColor = true;
this.bClose.Click += new System.EventHandler(this.bClose_Click);
//
// cbReportItems
//
this.cbReportItems.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cbReportItems.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbReportItems.FormattingEnabled = true;
this.cbReportItems.Location = new System.Drawing.Point(0, 18);
this.cbReportItems.Name = "cbReportItems";
this.cbReportItems.Size = new System.Drawing.Size(240, 21);
this.cbReportItems.TabIndex = 4;
this.cbReportItems.SelectedIndexChanged += new System.EventHandler(this.cbReportItems_SelectedIndexChanged);
//
// PropertyCtl
//
this.Controls.Add(this.cbReportItems);
this.Controls.Add(this.bClose);
this.Controls.Add(this.pgSelected);
this.Controls.Add(this.label1);
this.Name = "PropertyCtl";
this.Size = new System.Drawing.Size(240, 280);
this.ResumeLayout(false);
}
#endregion
private void bClose_Click(object sender, EventArgs e)
{
RdlDesigner rd = this.Parent as RdlDesigner;
if (rd == null)
return;
rd.ShowProperties(false);
}
private void cbReportItems_SelectedIndexChanged(object sender, EventArgs e)
{
string ri_name = cbReportItems.SelectedItem as string;
if (ri_name == GROUP || ri_name == NONAME)
return;
if (ri_name == REPORT)
{
// handle request for change to report property
if (_Draw.SelectedCount == 0) // we're already on report
return;
_DesignCtl.SetSelection(null);
return;
}
// handle request to change selected report item
XmlNode ri_node = _Draw.ReportNames.GetRINodeFromName(ri_name);
if (ri_node == null)
return;
if (_Draw.SelectedCount == 1 &&
_Draw.SelectedList[0] == ri_node)
return; // we're already selected!
_DesignCtl.SetSelection(ri_node);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;
using WeifenLuo.WinFormsUI.Docking;
using System.IO;
using System.Text;
using System.Xml;
using System.Globalization;
namespace WeifenLuo.WinFormsUI.Docking
{
partial class DockPanel
{
private static class Persistor
{
private const string ConfigFileVersion = "1.0";
private static string[] CompatibleConfigFileVersions = new string[] { };
private class DummyContent : DockContent
{
}
private struct DockPanelStruct
{
private double m_dockLeftPortion;
public double DockLeftPortion
{
get { return m_dockLeftPortion; }
set { m_dockLeftPortion = value; }
}
private double m_dockRightPortion;
public double DockRightPortion
{
get { return m_dockRightPortion; }
set { m_dockRightPortion = value; }
}
private double m_dockTopPortion;
public double DockTopPortion
{
get { return m_dockTopPortion; }
set { m_dockTopPortion = value; }
}
private double m_dockBottomPortion;
public double DockBottomPortion
{
get { return m_dockBottomPortion; }
set { m_dockBottomPortion = value; }
}
private int m_indexActiveDocumentPane;
public int IndexActiveDocumentPane
{
get { return m_indexActiveDocumentPane; }
set { m_indexActiveDocumentPane = value; }
}
private int m_indexActivePane;
public int IndexActivePane
{
get { return m_indexActivePane; }
set { m_indexActivePane = value; }
}
}
private struct ContentStruct
{
private string m_persistString;
public string PersistString
{
get { return m_persistString; }
set { m_persistString = value; }
}
private double m_autoHidePortion;
public double AutoHidePortion
{
get { return m_autoHidePortion; }
set { m_autoHidePortion = value; }
}
private bool m_isHidden;
public bool IsHidden
{
get { return m_isHidden; }
set { m_isHidden = value; }
}
private bool m_isFloat;
public bool IsFloat
{
get { return m_isFloat; }
set { m_isFloat = value; }
}
}
private struct PaneStruct
{
private DockState m_dockState;
public DockState DockState
{
get { return m_dockState; }
set { m_dockState = value; }
}
private int m_indexActiveContent;
public int IndexActiveContent
{
get { return m_indexActiveContent; }
set { m_indexActiveContent = value; }
}
private int[] m_indexContents;
public int[] IndexContents
{
get { return m_indexContents; }
set { m_indexContents = value; }
}
private int m_zOrderIndex;
public int ZOrderIndex
{
get { return m_zOrderIndex; }
set { m_zOrderIndex = value; }
}
}
private struct NestedPane
{
private int m_indexPane;
public int IndexPane
{
get { return m_indexPane; }
set { m_indexPane = value; }
}
private int m_indexPrevPane;
public int IndexPrevPane
{
get { return m_indexPrevPane; }
set { m_indexPrevPane = value; }
}
private DockAlignment m_alignment;
public DockAlignment Alignment
{
get { return m_alignment; }
set { m_alignment = value; }
}
private double m_proportion;
public double Proportion
{
get { return m_proportion; }
set { m_proportion = value; }
}
}
private struct DockWindowStruct
{
private DockState m_dockState;
public DockState DockState
{
get { return m_dockState; }
set { m_dockState = value; }
}
private int m_zOrderIndex;
public int ZOrderIndex
{
get { return m_zOrderIndex; }
set { m_zOrderIndex = value; }
}
private NestedPane[] m_nestedPanes;
public NestedPane[] NestedPanes
{
get { return m_nestedPanes; }
set { m_nestedPanes = value; }
}
}
private struct FloatWindowStruct
{
private Rectangle m_bounds;
public Rectangle Bounds
{
get { return m_bounds; }
set { m_bounds = value; }
}
private int m_zOrderIndex;
public int ZOrderIndex
{
get { return m_zOrderIndex; }
set { m_zOrderIndex = value; }
}
private NestedPane[] m_nestedPanes;
public NestedPane[] NestedPanes
{
get { return m_nestedPanes; }
set { m_nestedPanes = value; }
}
}
public static void SaveAsXml(DockPanel dockPanel, string fileName)
{
SaveAsXml(dockPanel, fileName, Encoding.Unicode);
}
public static void SaveAsXml(DockPanel dockPanel, string fileName, Encoding encoding)
{
FileStream fs = new FileStream(fileName, FileMode.Create);
try
{
SaveAsXml(dockPanel, fs, encoding);
}
finally
{
fs.Close();
}
}
public static void SaveAsXml(DockPanel dockPanel, Stream stream, Encoding encoding)
{
SaveAsXml(dockPanel, stream, encoding, false);
}
public static void SaveAsXml(DockPanel dockPanel, Stream stream, Encoding encoding, bool upstream)
{
XmlTextWriter xmlOut = new XmlTextWriter(stream, encoding);
// Use indenting for readability
xmlOut.Formatting = Formatting.Indented;
if (!upstream)
xmlOut.WriteStartDocument();
// Always begin file with identification and warning
xmlOut.WriteComment(Strings.DockPanel_Persistor_XmlFileComment1);
xmlOut.WriteComment(Strings.DockPanel_Persistor_XmlFileComment2);
// Associate a version number with the root element so that future version of the code
// will be able to be backwards compatible or at least recognise out of date versions
xmlOut.WriteStartElement("DockPanel");
xmlOut.WriteAttributeString("FormatVersion", ConfigFileVersion);
xmlOut.WriteAttributeString("DockLeftPortion", dockPanel.DockLeftPortion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("DockRightPortion", dockPanel.DockRightPortion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("DockTopPortion", dockPanel.DockTopPortion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("DockBottomPortion", dockPanel.DockBottomPortion.ToString(CultureInfo.InvariantCulture));
if (!Win32Helper.IsRunningOnMono)
{
xmlOut.WriteAttributeString("ActiveDocumentPane", dockPanel.Panes.IndexOf(dockPanel.ActiveDocumentPane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("ActivePane", dockPanel.Panes.IndexOf(dockPanel.ActivePane).ToString(CultureInfo.InvariantCulture));
}
// Contents
xmlOut.WriteStartElement("Contents");
xmlOut.WriteAttributeString("Count", dockPanel.Contents.Count.ToString(CultureInfo.InvariantCulture));
foreach (IDockContent content in dockPanel.Contents)
{
xmlOut.WriteStartElement("Content");
xmlOut.WriteAttributeString("ID", dockPanel.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("PersistString", content.DockHandler.PersistString);
xmlOut.WriteAttributeString("AutoHidePortion", content.DockHandler.AutoHidePortion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("IsHidden", content.DockHandler.IsHidden.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("IsFloat", content.DockHandler.IsFloat.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
// Panes
xmlOut.WriteStartElement("Panes");
xmlOut.WriteAttributeString("Count", dockPanel.Panes.Count.ToString(CultureInfo.InvariantCulture));
foreach (DockPane pane in dockPanel.Panes)
{
xmlOut.WriteStartElement("Pane");
xmlOut.WriteAttributeString("ID", dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("DockState", pane.DockState.ToString());
xmlOut.WriteAttributeString("ActiveContent", dockPanel.Contents.IndexOf(pane.ActiveContent).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteStartElement("Contents");
xmlOut.WriteAttributeString("Count", pane.Contents.Count.ToString(CultureInfo.InvariantCulture));
foreach (IDockContent content in pane.Contents)
{
xmlOut.WriteStartElement("Content");
xmlOut.WriteAttributeString("ID", pane.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("RefID", dockPanel.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
// DockWindows
xmlOut.WriteStartElement("DockWindows");
int dockWindowId = 0;
foreach (DockWindow dw in dockPanel.DockWindows)
{
xmlOut.WriteStartElement("DockWindow");
xmlOut.WriteAttributeString("ID", dockWindowId.ToString(CultureInfo.InvariantCulture));
dockWindowId++;
xmlOut.WriteAttributeString("DockState", dw.DockState.ToString());
xmlOut.WriteAttributeString("ZOrderIndex", dockPanel.Controls.IndexOf(dw).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteStartElement("NestedPanes");
xmlOut.WriteAttributeString("Count", dw.NestedPanes.Count.ToString(CultureInfo.InvariantCulture));
foreach (DockPane pane in dw.NestedPanes)
{
xmlOut.WriteStartElement("Pane");
xmlOut.WriteAttributeString("ID", dw.NestedPanes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("RefID", dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
NestedDockingStatus status = pane.NestedDockingStatus;
xmlOut.WriteAttributeString("PrevPane", dockPanel.Panes.IndexOf(status.PreviousPane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("Alignment", status.Alignment.ToString());
xmlOut.WriteAttributeString("Proportion", status.Proportion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
// FloatWindows
RectangleConverter rectConverter = new RectangleConverter();
xmlOut.WriteStartElement("FloatWindows");
xmlOut.WriteAttributeString("Count", dockPanel.FloatWindows.Count.ToString(CultureInfo.InvariantCulture));
foreach (FloatWindow fw in dockPanel.FloatWindows)
{
xmlOut.WriteStartElement("FloatWindow");
xmlOut.WriteAttributeString("ID", dockPanel.FloatWindows.IndexOf(fw).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("Bounds", rectConverter.ConvertToInvariantString(fw.Bounds));
xmlOut.WriteAttributeString("ZOrderIndex", fw.DockPanel.FloatWindows.IndexOf(fw).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteStartElement("NestedPanes");
xmlOut.WriteAttributeString("Count", fw.NestedPanes.Count.ToString(CultureInfo.InvariantCulture));
foreach (DockPane pane in fw.NestedPanes)
{
xmlOut.WriteStartElement("Pane");
xmlOut.WriteAttributeString("ID", fw.NestedPanes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("RefID", dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
NestedDockingStatus status = pane.NestedDockingStatus;
xmlOut.WriteAttributeString("PrevPane", dockPanel.Panes.IndexOf(status.PreviousPane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("Alignment", status.Alignment.ToString());
xmlOut.WriteAttributeString("Proportion", status.Proportion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement(); // </FloatWindows>
xmlOut.WriteEndElement();
if (!upstream)
{
xmlOut.WriteEndDocument();
xmlOut.Close();
}
else
xmlOut.Flush();
}
public static void LoadFromXml(DockPanel dockPanel, string fileName, DeserializeDockContent deserializeContent)
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
try
{
LoadFromXml(dockPanel, fs, deserializeContent);
}
finally
{
fs.Close();
}
}
public static void LoadFromXml(DockPanel dockPanel, Stream stream, DeserializeDockContent deserializeContent)
{
LoadFromXml(dockPanel, stream, deserializeContent, true);
}
private static ContentStruct[] LoadContents(XmlTextReader xmlIn)
{
int countOfContents = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
ContentStruct[] contents = new ContentStruct[countOfContents];
MoveToNextElement(xmlIn);
for (int i = 0; i < countOfContents; i++)
{
int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "Content" || id != i)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
contents[i].PersistString = xmlIn.GetAttribute("PersistString");
contents[i].AutoHidePortion = Convert.ToDouble(xmlIn.GetAttribute("AutoHidePortion"), CultureInfo.InvariantCulture);
contents[i].IsHidden = Convert.ToBoolean(xmlIn.GetAttribute("IsHidden"), CultureInfo.InvariantCulture);
contents[i].IsFloat = Convert.ToBoolean(xmlIn.GetAttribute("IsFloat"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
}
return contents;
}
private static PaneStruct[] LoadPanes(XmlTextReader xmlIn)
{
EnumConverter dockStateConverter = new EnumConverter(typeof(DockState));
int countOfPanes = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
PaneStruct[] panes = new PaneStruct[countOfPanes];
MoveToNextElement(xmlIn);
for (int i = 0; i < countOfPanes; i++)
{
int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "Pane" || id != i)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
panes[i].DockState = (DockState)dockStateConverter.ConvertFrom(xmlIn.GetAttribute("DockState"));
panes[i].IndexActiveContent = Convert.ToInt32(xmlIn.GetAttribute("ActiveContent"), CultureInfo.InvariantCulture);
panes[i].ZOrderIndex = -1;
MoveToNextElement(xmlIn);
if (xmlIn.Name != "Contents")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
int countOfPaneContents = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
panes[i].IndexContents = new int[countOfPaneContents];
MoveToNextElement(xmlIn);
for (int j = 0; j < countOfPaneContents; j++)
{
int id2 = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "Content" || id2 != j)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
panes[i].IndexContents[j] = Convert.ToInt32(xmlIn.GetAttribute("RefID"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
}
}
return panes;
}
private static DockWindowStruct[] LoadDockWindows(XmlTextReader xmlIn, DockPanel dockPanel)
{
EnumConverter dockStateConverter = new EnumConverter(typeof(DockState));
EnumConverter dockAlignmentConverter = new EnumConverter(typeof(DockAlignment));
int countOfDockWindows = dockPanel.DockWindows.Count;
DockWindowStruct[] dockWindows = new DockWindowStruct[countOfDockWindows];
MoveToNextElement(xmlIn);
for (int i = 0; i < countOfDockWindows; i++)
{
int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "DockWindow" || id != i)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
dockWindows[i].DockState = (DockState)dockStateConverter.ConvertFrom(xmlIn.GetAttribute("DockState"));
dockWindows[i].ZOrderIndex = Convert.ToInt32(xmlIn.GetAttribute("ZOrderIndex"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
if (xmlIn.Name != "DockList" && xmlIn.Name != "NestedPanes")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
int countOfNestedPanes = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
dockWindows[i].NestedPanes = new NestedPane[countOfNestedPanes];
MoveToNextElement(xmlIn);
for (int j = 0; j < countOfNestedPanes; j++)
{
int id2 = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "Pane" || id2 != j)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
dockWindows[i].NestedPanes[j].IndexPane = Convert.ToInt32(xmlIn.GetAttribute("RefID"), CultureInfo.InvariantCulture);
dockWindows[i].NestedPanes[j].IndexPrevPane = Convert.ToInt32(xmlIn.GetAttribute("PrevPane"), CultureInfo.InvariantCulture);
dockWindows[i].NestedPanes[j].Alignment = (DockAlignment)dockAlignmentConverter.ConvertFrom(xmlIn.GetAttribute("Alignment"));
dockWindows[i].NestedPanes[j].Proportion = Convert.ToDouble(xmlIn.GetAttribute("Proportion"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
}
}
return dockWindows;
}
private static FloatWindowStruct[] LoadFloatWindows(XmlTextReader xmlIn)
{
EnumConverter dockAlignmentConverter = new EnumConverter(typeof(DockAlignment));
RectangleConverter rectConverter = new RectangleConverter();
int countOfFloatWindows = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
FloatWindowStruct[] floatWindows = new FloatWindowStruct[countOfFloatWindows];
MoveToNextElement(xmlIn);
for (int i = 0; i < countOfFloatWindows; i++)
{
int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "FloatWindow" || id != i)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
floatWindows[i].Bounds = (Rectangle)rectConverter.ConvertFromInvariantString(xmlIn.GetAttribute("Bounds"));
floatWindows[i].ZOrderIndex = Convert.ToInt32(xmlIn.GetAttribute("ZOrderIndex"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
if (xmlIn.Name != "DockList" && xmlIn.Name != "NestedPanes")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
int countOfNestedPanes = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
floatWindows[i].NestedPanes = new NestedPane[countOfNestedPanes];
MoveToNextElement(xmlIn);
for (int j = 0; j < countOfNestedPanes; j++)
{
int id2 = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "Pane" || id2 != j)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
floatWindows[i].NestedPanes[j].IndexPane = Convert.ToInt32(xmlIn.GetAttribute("RefID"), CultureInfo.InvariantCulture);
floatWindows[i].NestedPanes[j].IndexPrevPane = Convert.ToInt32(xmlIn.GetAttribute("PrevPane"), CultureInfo.InvariantCulture);
floatWindows[i].NestedPanes[j].Alignment = (DockAlignment)dockAlignmentConverter.ConvertFrom(xmlIn.GetAttribute("Alignment"));
floatWindows[i].NestedPanes[j].Proportion = Convert.ToDouble(xmlIn.GetAttribute("Proportion"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
}
}
return floatWindows;
}
public static void LoadFromXml(DockPanel dockPanel, Stream stream, DeserializeDockContent deserializeContent, bool closeStream)
{
if (dockPanel.Contents.Count != 0)
throw new InvalidOperationException(Strings.DockPanel_LoadFromXml_AlreadyInitialized);
XmlTextReader xmlIn = new XmlTextReader(stream);
xmlIn.WhitespaceHandling = WhitespaceHandling.None;
xmlIn.MoveToContent();
while (!xmlIn.Name.Equals("DockPanel"))
{
if (!MoveToNextElement(xmlIn))
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
}
string formatVersion = xmlIn.GetAttribute("FormatVersion");
if (!IsFormatVersionValid(formatVersion))
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidFormatVersion);
DockPanelStruct dockPanelStruct = new DockPanelStruct();
dockPanelStruct.DockLeftPortion = Convert.ToDouble(xmlIn.GetAttribute("DockLeftPortion"), CultureInfo.InvariantCulture);
dockPanelStruct.DockRightPortion = Convert.ToDouble(xmlIn.GetAttribute("DockRightPortion"), CultureInfo.InvariantCulture);
dockPanelStruct.DockTopPortion = Convert.ToDouble(xmlIn.GetAttribute("DockTopPortion"), CultureInfo.InvariantCulture);
dockPanelStruct.DockBottomPortion = Convert.ToDouble(xmlIn.GetAttribute("DockBottomPortion"), CultureInfo.InvariantCulture);
dockPanelStruct.IndexActiveDocumentPane = Convert.ToInt32(xmlIn.GetAttribute("ActiveDocumentPane"), CultureInfo.InvariantCulture);
dockPanelStruct.IndexActivePane = Convert.ToInt32(xmlIn.GetAttribute("ActivePane"), CultureInfo.InvariantCulture);
// Load Contents
MoveToNextElement(xmlIn);
if (xmlIn.Name != "Contents")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
ContentStruct[] contents = LoadContents(xmlIn);
// Load Panes
if (xmlIn.Name != "Panes")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
PaneStruct[] panes = LoadPanes(xmlIn);
// Load DockWindows
if (xmlIn.Name != "DockWindows")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
DockWindowStruct[] dockWindows = LoadDockWindows(xmlIn, dockPanel);
// Load FloatWindows
if (xmlIn.Name != "FloatWindows")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
FloatWindowStruct[] floatWindows = LoadFloatWindows(xmlIn);
if (closeStream)
xmlIn.Close();
dockPanel.SuspendLayout(true);
dockPanel.DockLeftPortion = dockPanelStruct.DockLeftPortion;
dockPanel.DockRightPortion = dockPanelStruct.DockRightPortion;
dockPanel.DockTopPortion = dockPanelStruct.DockTopPortion;
dockPanel.DockBottomPortion = dockPanelStruct.DockBottomPortion;
// Set DockWindow ZOrders
int prevMaxDockWindowZOrder = int.MaxValue;
for (int i = 0; i < dockWindows.Length; i++)
{
int maxDockWindowZOrder = -1;
int index = -1;
for (int j = 0; j < dockWindows.Length; j++)
{
if (dockWindows[j].ZOrderIndex > maxDockWindowZOrder && dockWindows[j].ZOrderIndex < prevMaxDockWindowZOrder)
{
maxDockWindowZOrder = dockWindows[j].ZOrderIndex;
index = j;
}
}
dockPanel.DockWindows[dockWindows[index].DockState].BringToFront();
prevMaxDockWindowZOrder = maxDockWindowZOrder;
}
// Create Contents
for (int i = 0; i < contents.Length; i++)
{
IDockContent content = deserializeContent(contents[i].PersistString);
if (content == null)
content = new DummyContent();
content.DockHandler.DockPanel = dockPanel;
content.DockHandler.AutoHidePortion = contents[i].AutoHidePortion;
content.DockHandler.IsHidden = true;
content.DockHandler.IsFloat = contents[i].IsFloat;
}
// Create panes
for (int i = 0; i < panes.Length; i++)
{
DockPane pane = null;
for (int j = 0; j < panes[i].IndexContents.Length; j++)
{
IDockContent content = dockPanel.Contents[panes[i].IndexContents[j]];
if (j == 0)
pane = dockPanel.DockPaneFactory.CreateDockPane(content, panes[i].DockState, false);
else if (panes[i].DockState == DockState.Float)
content.DockHandler.FloatPane = pane;
else
content.DockHandler.PanelPane = pane;
}
}
// Assign Panes to DockWindows
for (int i = 0; i < dockWindows.Length; i++)
{
for (int j = 0; j < dockWindows[i].NestedPanes.Length; j++)
{
DockWindow dw = dockPanel.DockWindows[dockWindows[i].DockState];
int indexPane = dockWindows[i].NestedPanes[j].IndexPane;
DockPane pane = dockPanel.Panes[indexPane];
int indexPrevPane = dockWindows[i].NestedPanes[j].IndexPrevPane;
DockPane prevPane = (indexPrevPane == -1) ? dw.NestedPanes.GetDefaultPreviousPane(pane) : dockPanel.Panes[indexPrevPane];
DockAlignment alignment = dockWindows[i].NestedPanes[j].Alignment;
double proportion = dockWindows[i].NestedPanes[j].Proportion;
pane.DockTo(dw, prevPane, alignment, proportion);
if (panes[indexPane].DockState == dw.DockState)
panes[indexPane].ZOrderIndex = dockWindows[i].ZOrderIndex;
}
}
// Create float windows
for (int i = 0; i < floatWindows.Length; i++)
{
FloatWindow fw = null;
for (int j = 0; j < floatWindows[i].NestedPanes.Length; j++)
{
int indexPane = floatWindows[i].NestedPanes[j].IndexPane;
DockPane pane = dockPanel.Panes[indexPane];
if (j == 0)
fw = dockPanel.FloatWindowFactory.CreateFloatWindow(dockPanel, pane, floatWindows[i].Bounds);
else
{
int indexPrevPane = floatWindows[i].NestedPanes[j].IndexPrevPane;
DockPane prevPane = indexPrevPane == -1 ? null : dockPanel.Panes[indexPrevPane];
DockAlignment alignment = floatWindows[i].NestedPanes[j].Alignment;
double proportion = floatWindows[i].NestedPanes[j].Proportion;
pane.DockTo(fw, prevPane, alignment, proportion);
}
if (panes[indexPane].DockState == fw.DockState)
panes[indexPane].ZOrderIndex = floatWindows[i].ZOrderIndex;
}
}
// sort IDockContent by its Pane's ZOrder
int[] sortedContents = null;
if (contents.Length > 0)
{
sortedContents = new int[contents.Length];
for (int i = 0; i < contents.Length; i++)
sortedContents[i] = i;
int lastDocument = contents.Length;
for (int i = 0; i < contents.Length - 1; i++)
{
for (int j = i + 1; j < contents.Length; j++)
{
DockPane pane1 = dockPanel.Contents[sortedContents[i]].DockHandler.Pane;
int ZOrderIndex1 = pane1 == null ? 0 : panes[dockPanel.Panes.IndexOf(pane1)].ZOrderIndex;
DockPane pane2 = dockPanel.Contents[sortedContents[j]].DockHandler.Pane;
int ZOrderIndex2 = pane2 == null ? 0 : panes[dockPanel.Panes.IndexOf(pane2)].ZOrderIndex;
if (ZOrderIndex1 > ZOrderIndex2)
{
int temp = sortedContents[i];
sortedContents[i] = sortedContents[j];
sortedContents[j] = temp;
}
}
}
}
// show non-document IDockContent first to avoid screen flickers
for (int i = 0; i < contents.Length; i++)
{
IDockContent content = dockPanel.Contents[sortedContents[i]];
if (content.DockHandler.Pane != null && content.DockHandler.Pane.DockState != DockState.Document)
content.DockHandler.IsHidden = contents[sortedContents[i]].IsHidden;
}
// after all non-document IDockContent, show document IDockContent
for (int i = 0; i < contents.Length; i++)
{
IDockContent content = dockPanel.Contents[sortedContents[i]];
if (content.DockHandler.Pane != null && content.DockHandler.Pane.DockState == DockState.Document)
content.DockHandler.IsHidden = contents[sortedContents[i]].IsHidden;
}
for (int i = 0; i < panes.Length; i++)
dockPanel.Panes[i].ActiveContent = panes[i].IndexActiveContent == -1 ? null : dockPanel.Contents[panes[i].IndexActiveContent];
if (dockPanelStruct.IndexActiveDocumentPane != -1)
dockPanel.Panes[dockPanelStruct.IndexActiveDocumentPane].Activate();
if (dockPanelStruct.IndexActivePane != -1)
dockPanel.Panes[dockPanelStruct.IndexActivePane].Activate();
for (int i = dockPanel.Contents.Count - 1; i >= 0; i--)
if (dockPanel.Contents[i] is DummyContent)
dockPanel.Contents[i].DockHandler.Form.Close();
dockPanel.ResumeLayout(true, true);
}
private static bool MoveToNextElement(XmlTextReader xmlIn)
{
if (!xmlIn.Read())
return false;
while (xmlIn.NodeType == XmlNodeType.EndElement)
{
if (!xmlIn.Read())
return false;
}
return true;
}
private static bool IsFormatVersionValid(string formatVersion)
{
if (formatVersion == ConfigFileVersion)
return true;
foreach (string s in CompatibleConfigFileVersions)
if (s == formatVersion)
return true;
return false;
}
}
public void SaveAsXml(string fileName)
{
Persistor.SaveAsXml(this, fileName);
}
public void SaveAsXml(string fileName, Encoding encoding)
{
Persistor.SaveAsXml(this, fileName, encoding);
}
public void SaveAsXml(Stream stream, Encoding encoding)
{
Persistor.SaveAsXml(this, stream, encoding);
}
public void SaveAsXml(Stream stream, Encoding encoding, bool upstream)
{
Persistor.SaveAsXml(this, stream, encoding, upstream);
}
public void LoadFromXml(string fileName, DeserializeDockContent deserializeContent)
{
Persistor.LoadFromXml(this, fileName, deserializeContent);
}
public void LoadFromXml(Stream stream, DeserializeDockContent deserializeContent)
{
Persistor.LoadFromXml(this, stream, deserializeContent);
}
public void LoadFromXml(Stream stream, DeserializeDockContent deserializeContent, bool closeStream)
{
Persistor.LoadFromXml(this, stream, deserializeContent, closeStream);
}
}
}
| |
using System;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.View;
using Android.Support.V4.Widget;
using Android.Util;
using Android.Views;
using Android.Views.Accessibility;
using Java.Interop;
namespace Cheesebaron.SlidingUpPanel
{
public class SlidingUpPanelLayout : ViewGroup
{
private new const string Tag = "SlidingUpPanelLayout";
private const int DefaultPanelHeight = 68;
private const int DefaultShadowHeight = 4;
private const int DefaultMinFlingVelocity = 400;
private const bool DefaultOverlayFlag = false;
private static readonly Color DefaultFadeColor = new Color(0, 0, 0, 99);
private static readonly int[] DefaultAttrs = { Android.Resource.Attribute.Gravity };
private readonly int _minFlingVelocity = DefaultMinFlingVelocity;
private Color _coveredFadeColor = DefaultFadeColor;
private readonly Paint _coveredFadePaint = new Paint();
private int _panelHeight = -1;
private readonly int _shadowHeight = -1;
private readonly bool _isSlidingUp;
private bool _canSlide;
private View _dragView;
private readonly int _dragViewResId = -1;
private View _slideableView;
private SlideState _slideState = SlideState.Collapsed;
private float _slideOffset;
private int _slideRange;
private bool _isUnableToDrag;
private readonly int _scrollTouchSlop;
private float _initialMotionX;
private float _initialMotionY;
private float _anchorPoint;
private readonly ViewDragHelper _dragHelper;
private bool _firstLayout = true;
private readonly Rect _tmpRect = new Rect();
public event SlidingUpPanelSlideEventHandler PanelSlide;
public event SlidingUpPanelEventHandler PanelCollapsed;
public event SlidingUpPanelEventHandler PanelExpanded;
public event SlidingUpPanelEventHandler PanelAnchored;
public bool IsExpanded
{
get { return _slideState == SlideState.Expanded; }
}
public bool IsAnchored
{
get { return _slideState == SlideState.Anchored; }
}
public bool IsSlideable
{
get { return _canSlide; }
}
public Color CoveredFadeColor
{
get { return _coveredFadeColor; }
set
{
_coveredFadeColor = value;
Invalidate();
}
}
public int PanelHeight
{
get { return _panelHeight; }
set
{
_panelHeight = value;
RequestLayout();
}
}
public View DragView
{
get { return _dragView; }
set { _dragView = value; }
}
public float AnchorPoint
{
get { return _anchorPoint; }
set
{
if (value > 0 && value < 1)
_anchorPoint = value;
}
}
public Drawable ShadowDrawable { get; set; }
public bool SlidingEnabled { get; set; }
public bool OverlayContent { get; set; }
public bool IsUsingDragViewTouchEvents { get; set; }
private int SlidingTop
{
get
{
if (_slideableView != null)
{
return _isSlidingUp
? MeasuredHeight - PaddingBottom - _slideableView.MeasuredHeight
: MeasuredHeight - PaddingBottom - (_slideableView.MeasuredHeight * 2);
}
return MeasuredHeight - PaddingBottom;
}
}
public bool PaneVisible
{
get
{
if (ChildCount < 2)
return false;
var slidingPane = GetChildAt(1);
return slidingPane.Visibility == ViewStates.Visible;
}
}
public SlidingUpPanelLayout(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer) { }
public SlidingUpPanelLayout(Context context)
: this(context, null) { }
public SlidingUpPanelLayout(Context context, IAttributeSet attrs)
: this(context, attrs, 0) { }
public SlidingUpPanelLayout(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
// not really relevan in Xamarin.Android but keeping for a possible
// future update which will render layouts in the Designer.
if (IsInEditMode) return;
if (attrs != null)
{
var defAttrs = context.ObtainStyledAttributes(attrs, DefaultAttrs);
if (defAttrs.Length() > 0)
{
var gravity = defAttrs.GetInt(0, (int)GravityFlags.NoGravity);
var gravityFlag = (GravityFlags) gravity;
if (gravityFlag != GravityFlags.Top && gravityFlag != GravityFlags.Bottom)
throw new ArgumentException("gravity must be set to either top or bottom");
_isSlidingUp = gravityFlag == GravityFlags.Bottom;
}
defAttrs.Recycle();
var ta = context.ObtainStyledAttributes(attrs, Resource.Styleable.SlidingUpPanelLayout);
if (ta.Length() > 0)
{
_panelHeight = ta.GetDimensionPixelSize(Resource.Styleable.SlidingUpPanelLayout_collapsedHeight, -1);
_shadowHeight = ta.GetDimensionPixelSize(Resource.Styleable.SlidingUpPanelLayout_shadowHeight, -1);
_minFlingVelocity = ta.GetInt(Resource.Styleable.SlidingUpPanelLayout_flingVelocity,
DefaultMinFlingVelocity);
_coveredFadeColor = ta.GetColor(Resource.Styleable.SlidingUpPanelLayout_fadeColor, DefaultFadeColor);
_dragViewResId = ta.GetResourceId(Resource.Styleable.SlidingUpPanelLayout_dragView, -1);
OverlayContent = ta.GetBoolean(Resource.Styleable.SlidingUpPanelLayout_overlay, DefaultOverlayFlag);
}
ta.Recycle();
}
var density = context.Resources.DisplayMetrics.Density;
if (_panelHeight == -1)
_panelHeight = (int) (DefaultPanelHeight * density + 0.5f);
if (_shadowHeight == -1)
_shadowHeight = (int) (DefaultShadowHeight * density + 0.5f);
SetWillNotDraw(false);
_dragHelper = ViewDragHelper.Create(this, 0.5f, new DragHelperCallback(this));
_dragHelper.MinVelocity = _minFlingVelocity * density;
_canSlide = true;
SlidingEnabled = true;
var vc = ViewConfiguration.Get(context);
_scrollTouchSlop = vc.ScaledTouchSlop;
}
protected override void OnFinishInflate()
{
base.OnFinishInflate();
if (_dragViewResId != -1)
_dragView = FindViewById(_dragViewResId);
}
private void OnPanelSlide(View panel)
{
if (PanelSlide != null)
PanelSlide(this, new SlidingUpPanelSlideEventArgs {Panel = panel, SlideOffset = _slideOffset});
}
private void OnPanelCollapsed(View panel)
{
if (PanelCollapsed != null)
PanelCollapsed(this, new SlidingUpPanelEventArgs { Panel = panel });
SendAccessibilityEvent(EventTypes.WindowStateChanged);
}
private void OnPanelAnchored(View panel)
{
if (PanelAnchored != null)
PanelAnchored(this, new SlidingUpPanelEventArgs { Panel = panel });
SendAccessibilityEvent(EventTypes.WindowStateChanged);
}
private void OnPanelExpanded(View panel)
{
if (PanelExpanded != null)
PanelExpanded(this, new SlidingUpPanelEventArgs { Panel = panel });
SendAccessibilityEvent(EventTypes.WindowStateChanged);
}
private void UpdateObscuredViewVisibility()
{
if (ChildCount == 0) return;
var leftBound = PaddingLeft;
var rightBound = Width - PaddingLeft;
var topBound = PaddingTop;
var bottomBound = Height - PaddingBottom;
int left;
int right;
int top;
int bottom;
if (_slideableView != null && HasOpaqueBackground(_slideableView))
{
left = _slideableView.Left;
right = _slideableView.Right;
top = _slideableView.Top;
bottom = _slideableView.Bottom;
}
else
left = right = top = bottom = 0;
var child = GetChildAt(0);
var clampedChildLeft = Math.Max(leftBound, child.Left);
var clampedChildTop = Math.Max(topBound, child.Top);
var clampedChildRight = Math.Max(rightBound, child.Right);
var clampedChildBottom = Math.Max(bottomBound, child.Bottom);
ViewStates vis;
if (clampedChildLeft >= left && clampedChildTop >= top &&
clampedChildRight <= right && clampedChildBottom <= bottom)
vis = ViewStates.Invisible;
else
vis = ViewStates.Visible;
child.Visibility = vis;
}
private void SetAllChildrenVisible()
{
for (var i = 0; i < ChildCount; i++)
{
var child = GetChildAt(i);
if (child.Visibility == ViewStates.Invisible)
child.Visibility = ViewStates.Visible;
}
}
private static bool HasOpaqueBackground(View view)
{
var bg = view.Background;
if (bg != null)
return bg.Opacity == (int) Format.Opaque;
return false;
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
_firstLayout = true;
}
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
_firstLayout = true;
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
var widthMode = MeasureSpec.GetMode(widthMeasureSpec);
var widthSize = MeasureSpec.GetSize(widthMeasureSpec);
var heightMode = MeasureSpec.GetMode(heightMeasureSpec);
var heightSize = MeasureSpec.GetSize(heightMeasureSpec);
if (widthMode != MeasureSpecMode.Exactly)
throw new InvalidOperationException("Width must have an exact value or match_parent");
if (heightMode != MeasureSpecMode.Exactly)
throw new InvalidOperationException("Height must have an exact value or match_parent");
var layoutHeight = heightSize - PaddingTop - PaddingBottom;
var panelHeight = _panelHeight;
if (ChildCount > 2)
Log.Error(Tag, "OnMeasure: More than two child views are not supported.");
else
panelHeight = 0;
_slideableView = null;
_canSlide = false;
for (var i = 0; i < ChildCount; i++)
{
var child = GetChildAt(i);
var lp = (LayoutParams) child.LayoutParameters;
var height = layoutHeight;
if (child.Visibility == ViewStates.Gone)
{
lp.DimWhenOffset = false;
continue;
}
if (i == 1)
{
lp.Slideable = true;
lp.DimWhenOffset = true;
_slideableView = child;
_canSlide = true;
}
else
{
if (!OverlayContent)
height -= panelHeight;
}
int childWidthSpec;
if (lp.Width == ViewGroup.LayoutParams.WrapContent)
childWidthSpec = MeasureSpec.MakeMeasureSpec(widthSize, MeasureSpecMode.AtMost);
else if (lp.Width == ViewGroup.LayoutParams.MatchParent)
childWidthSpec = MeasureSpec.MakeMeasureSpec(widthSize, MeasureSpecMode.Exactly);
else
childWidthSpec = MeasureSpec.MakeMeasureSpec(lp.Width, MeasureSpecMode.Exactly);
int childHeightSpec;
if (lp.Height == ViewGroup.LayoutParams.WrapContent)
childHeightSpec = MeasureSpec.MakeMeasureSpec(height, MeasureSpecMode.AtMost);
else if (lp.Height == ViewGroup.LayoutParams.MatchParent)
childHeightSpec = MeasureSpec.MakeMeasureSpec(height, MeasureSpecMode.Exactly);
else
childHeightSpec = MeasureSpec.MakeMeasureSpec(lp.Height, MeasureSpecMode.Exactly);
child.Measure(childWidthSpec, childHeightSpec);
}
SetMeasuredDimension(widthSize, heightSize);
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
if (_firstLayout)
{
switch (_slideState)
{
case SlideState.Expanded:
_slideOffset = _canSlide ? 0.0f : 1.0f;
break;
case SlideState.Anchored:
_slideOffset = _canSlide ? _anchorPoint : 1.0f;
break;
case SlideState.Collapsed:
_slideOffset = 1.0f;
break;
}
}
for (var i = 0; i < ChildCount; i++)
{
var child = GetChildAt(i);
if (child.Visibility == ViewStates.Gone)
continue;
var lp = (LayoutParams) child.LayoutParameters;
var childHeight = child.MeasuredHeight;
if (lp.Slideable)
_slideRange = childHeight - _panelHeight;
int childTop;
if (_isSlidingUp)
childTop = lp.Slideable ? SlidingTop + (int) (_slideRange * _slideOffset) : PaddingTop;
else
childTop = lp.Slideable ? SlidingTop - (int)(_slideRange * _slideOffset) : PaddingTop + PanelHeight;
var childBottom = childTop + childHeight;
var childLeft = PaddingLeft;
var childRight = childLeft + child.MeasuredWidth;
child.Layout(childLeft, childTop, childRight, childBottom);
}
if (_firstLayout)
UpdateObscuredViewVisibility();
_firstLayout = false;
}
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
base.OnSizeChanged(w, h, oldw, oldh);
if (h != oldh)
_firstLayout = true;
}
public override bool OnInterceptTouchEvent(MotionEvent ev)
{
var action = MotionEventCompat.GetActionMasked(ev);
if (!_canSlide || !SlidingEnabled || (_isUnableToDrag && action != (int) MotionEventActions.Down))
{
_dragHelper?.Cancel();
return base.OnInterceptTouchEvent(ev);
}
if (action == (int) MotionEventActions.Cancel || action == (int) MotionEventActions.Up)
{
_dragHelper?.Cancel();
return false;
}
var x = ev.GetX();
var y = ev.GetY();
var interceptTap = false;
switch (action)
{
case (int)MotionEventActions.Down:
_isUnableToDrag = false;
_initialMotionX = x;
_initialMotionY = y;
if (IsDragViewUnder((int) x, (int) y) && !IsUsingDragViewTouchEvents)
interceptTap = true;
break;
case (int)MotionEventActions.Move:
var adx = Math.Abs(x - _initialMotionX);
var ady = Math.Abs(y - _initialMotionY);
var dragSlop = _dragHelper?.TouchSlop ?? 0;
if (IsUsingDragViewTouchEvents)
{
if (adx > _scrollTouchSlop && ady < _scrollTouchSlop)
return base.OnInterceptTouchEvent(ev);
if (ady > _scrollTouchSlop)
interceptTap = IsDragViewUnder((int) x, (int) y);
}
if ((ady > dragSlop && adx > ady) || !IsDragViewUnder((int) x, (int) y))
{
_dragHelper?.Cancel();
_isUnableToDrag = true;
return false;
}
break;
}
var interceptForDrag = _dragHelper.ShouldInterceptTouchEvent(ev);
return interceptForDrag || interceptTap;
}
public override bool OnTouchEvent(MotionEvent ev)
{
if (!_canSlide || !SlidingEnabled)
return base.OnTouchEvent(ev);
_dragHelper?.ProcessTouchEvent(ev);
var action = (int)ev.Action;
switch (action & MotionEventCompat.ActionMask)
{
case (int)MotionEventActions.Down:
{
var x = ev.GetX();
var y = ev.GetY();
_initialMotionX = x;
_initialMotionY = y;
break;
}
case (int)MotionEventActions.Up:
{
var x = ev.GetX();
var y = ev.GetY();
var dx = x - _initialMotionX;
var dy = y - _initialMotionY;
var slop = _dragHelper?.TouchSlop ?? 0;
var dragView = _dragView ?? _slideableView;
if (dx * dx + dy * dy < slop * slop && IsDragViewUnder((int)x, (int)y))
{
dragView.PlaySoundEffect(SoundEffects.Click);
if (!IsExpanded && !IsAnchored)
ExpandPane(_anchorPoint);
else
CollapsePane();
}
break;
}
}
return true;
}
private bool IsDragViewUnder(int x, int y)
{
var dragView = _dragView ?? _slideableView;
if (dragView == null) return false;
var viewLocation = new int[2];
dragView.GetLocationOnScreen(viewLocation);
var parentLocation = new int[2];
GetLocationOnScreen(parentLocation);
var screenX = parentLocation[0] + x;
var screenY = parentLocation[1] + y;
return screenX >= viewLocation[0] && screenX < viewLocation[0] + dragView.Width &&
screenY >= viewLocation[1] && screenY < viewLocation[1] + dragView.Height;
}
public bool CollapsePane()
{
if (_firstLayout || SmoothSlideTo(1.0f))
return true;
return false;
}
public bool ExpandPane()
{
return ExpandPane(0);
}
public bool ExpandPane(float slideOffset)
{
if (!PaneVisible)
ShowPane();
return _firstLayout || SmoothSlideTo(slideOffset);
}
public void ShowPane()
{
if (ChildCount < 2) return;
var slidingPane = GetChildAt(1);
slidingPane.Visibility = ViewStates.Visible;
RequestLayout();
}
public void HidePane()
{
if (_slideableView == null) return;
_slideableView.Visibility = ViewStates.Gone;
RequestLayout();
}
private void OnPanelDragged(int newTop)
{
_slideOffset = _isSlidingUp
? (float) (newTop - SlidingTop) / _slideRange
: (float) (SlidingTop - newTop) / _slideRange;
OnPanelSlide(_slideableView);
}
protected override bool DrawChild(Canvas canvas, View child, long drawingTime)
{
var lp = (LayoutParams) child.LayoutParameters;
var save = canvas.Save();
var drawScrim = false;
if (_canSlide && !lp.Slideable && _slideableView != null)
{
if (!OverlayContent)
{
canvas.GetClipBounds(_tmpRect);
if (_isSlidingUp)
_tmpRect.Bottom = Math.Min(_tmpRect.Bottom, _slideableView.Top);
else
_tmpRect.Top = Math.Max(_tmpRect.Top, _slideableView.Bottom);
canvas.ClipRect(_tmpRect);
}
if (_slideOffset < 1)
drawScrim = true;
}
var result = base.DrawChild(canvas, child, drawingTime);
canvas.RestoreToCount(save);
if (drawScrim)
{
var baseAlpha = (_coveredFadeColor.ToArgb() & 0xff000000) >> 24;
var imag = (int) (baseAlpha * (1 - _slideOffset));
var color = imag << 24 | (_coveredFadeColor.ToArgb() & 0xffffff);
_coveredFadePaint.Color = new Color(color);
canvas.DrawRect(_tmpRect, _coveredFadePaint);
}
return result;
}
private bool SmoothSlideTo(float slideOffset)
{
if (!_canSlide) return false;
var y = _isSlidingUp
? (int) (SlidingTop + slideOffset * _slideRange)
: (int) (SlidingTop - slideOffset * _slideRange);
if (!(_dragHelper?.SmoothSlideViewTo(_slideableView, _slideableView.Left, y) ?? false)) return false;
SetAllChildrenVisible();
ViewCompat.PostInvalidateOnAnimation(this);
return true;
}
public override void ComputeScroll()
{
if (_dragHelper == null) return;
if (!_dragHelper.ContinueSettling(true)) return;
if (!_canSlide)
{
_dragHelper.Abort();
return;
}
ViewCompat.PostInvalidateOnAnimation(this);
}
public override void Draw(Canvas canvas)
{
base.Draw(canvas);
if (_slideableView == null) return;
if (ShadowDrawable == null) return;
var right = _slideableView.Right;
var left = _slideableView.Left;
int top;
int bottom;
if (_isSlidingUp)
{
top = _slideableView.Top - _shadowHeight;
bottom = _slideableView.Top;
}
else
{
top = _slideableView.Bottom;
bottom = _slideableView.Bottom + _shadowHeight;
}
ShadowDrawable.SetBounds(left, top, right, bottom);
ShadowDrawable.Draw(canvas);
}
protected bool CanScroll(View view, bool checkV, int dx, int x, int y)
{
var viewGroup = view as ViewGroup;
if (viewGroup == null) return checkV && ViewCompat.CanScrollHorizontally(view, -dx);
var scrollX = viewGroup.ScrollX;
var scrollY = viewGroup.ScrollY;
var count = viewGroup.ChildCount;
for (var i = count - 1; i >= 0; i--)
{
var child = viewGroup.GetChildAt(i);
if (x + scrollX >= child.Left && x + scrollX < child.Right &&
y + scrollY >= child.Top && y + scrollY < child.Bottom &&
CanScroll(child, true, dx, x + scrollX - child.Left, y + scrollY - child.Top))
return true;
}
return checkV && ViewCompat.CanScrollHorizontally(view, -dx);
}
protected override ViewGroup.LayoutParams GenerateDefaultLayoutParams()
{
return new LayoutParams();
}
protected override ViewGroup.LayoutParams GenerateLayoutParams(ViewGroup.LayoutParams p)
{
var param = p as MarginLayoutParams;
return param != null ? new LayoutParams(param) : new LayoutParams(p);
}
protected override bool CheckLayoutParams(ViewGroup.LayoutParams p)
{
var param = p as LayoutParams;
return param != null && base.CheckLayoutParams(p);
}
public override ViewGroup.LayoutParams GenerateLayoutParams(IAttributeSet attrs)
{
return new LayoutParams(Context, attrs);
}
public new class LayoutParams : MarginLayoutParams
{
private static readonly int[] Attrs = {
Android.Resource.Attribute.LayoutWidth
};
public bool Slideable { get; set; }
public bool DimWhenOffset { get; set; }
public Paint DimPaint { get; set; }
public LayoutParams()
: base(MatchParent, MatchParent) { }
public LayoutParams(int width, int height)
: base(width, height) { }
public LayoutParams(ViewGroup.LayoutParams source)
: base(source) { }
public LayoutParams(MarginLayoutParams source)
: base(source) { }
public LayoutParams(LayoutParams source)
: base(source) { }
public LayoutParams(Context c, IAttributeSet attrs)
: base(c, attrs)
{
var a = c.ObtainStyledAttributes(attrs, Attrs);
a.Recycle();
}
}
private class DragHelperCallback : ViewDragHelper.Callback
{
//This class is a bit nasty, as C# does not allow calling variables directly
//like stupid Java does.
private readonly SlidingUpPanelLayout _panelLayout;
public DragHelperCallback(SlidingUpPanelLayout layout)
{
_panelLayout = layout;
}
public override bool TryCaptureView(View child, int pointerId)
{
return !_panelLayout._isUnableToDrag && ((LayoutParams) child.LayoutParameters).Slideable;
}
public override void OnViewDragStateChanged(int state)
{
var anchoredTop = (int) (_panelLayout._anchorPoint * _panelLayout._slideRange);
if (_panelLayout._dragHelper != null && _panelLayout._dragHelper.ViewDragState == ViewDragHelper.StateIdle)
{
if (FloatNearlyEqual(_panelLayout._slideOffset, 0))
{
if (_panelLayout._slideState != SlideState.Expanded)
{
_panelLayout.UpdateObscuredViewVisibility();
_panelLayout.OnPanelExpanded(_panelLayout._slideableView);
_panelLayout._slideState = SlideState.Expanded;
}
}
else if (FloatNearlyEqual(_panelLayout._slideOffset, (float)anchoredTop / _panelLayout._slideRange))
{
if (_panelLayout._slideState != SlideState.Anchored)
{
_panelLayout.UpdateObscuredViewVisibility();
_panelLayout.OnPanelAnchored(_panelLayout._slideableView);
_panelLayout._slideState = SlideState.Anchored;
}
}
else if (_panelLayout._slideState != SlideState.Collapsed)
{
_panelLayout.OnPanelCollapsed(_panelLayout._slideableView);
_panelLayout._slideState = SlideState.Collapsed;
}
}
}
public override void OnViewCaptured(View capturedChild, int activePointerId)
{
_panelLayout.SetAllChildrenVisible();
}
public override void OnViewPositionChanged(View changedView, int left, int top, int dx, int dy)
{
_panelLayout.OnPanelDragged(top);
_panelLayout.Invalidate();
}
public override void OnViewReleased(View releasedChild, float xvel, float yvel)
{
var top = _panelLayout._isSlidingUp
? _panelLayout.SlidingTop
: _panelLayout.SlidingTop - _panelLayout._slideRange;
if (!FloatNearlyEqual(_panelLayout._anchorPoint, 0))
{
int anchoredTop;
float anchorOffset;
if (_panelLayout._isSlidingUp)
{
anchoredTop = (int) (_panelLayout._anchorPoint * _panelLayout._slideRange);
anchorOffset = (float) anchoredTop / _panelLayout._slideRange;
}
else
{
anchoredTop = _panelLayout._panelHeight -
(int) (_panelLayout._anchorPoint * _panelLayout._slideRange);
anchorOffset = (float)(_panelLayout._panelHeight - anchoredTop) / _panelLayout._slideRange;
}
if (yvel > 0 || (FloatNearlyEqual(yvel, 0) && _panelLayout._slideOffset >= (1f + anchorOffset) / 2))
top += _panelLayout._slideRange;
else if (FloatNearlyEqual(yvel, 0) && _panelLayout._slideOffset < (1f + anchorOffset) / 2 &&
_panelLayout._slideOffset >= anchorOffset / 2)
top += (int) (_panelLayout._slideRange * _panelLayout._anchorPoint);
}
else if (yvel > 0 || (FloatNearlyEqual(yvel, 0) && _panelLayout._slideOffset > 0.5f))
top += _panelLayout._slideRange;
_panelLayout._dragHelper?.SettleCapturedViewAt(releasedChild.Left, top);
_panelLayout.Invalidate();
}
public override int GetViewVerticalDragRange(View child)
{
return _panelLayout._slideRange;
}
public override int ClampViewPositionVertical(View child, int top, int dy)
{
int topBound;
int bottomBound;
if (_panelLayout._isSlidingUp)
{
topBound = _panelLayout.SlidingTop;
bottomBound = topBound + _panelLayout._slideRange;
}
else
{
bottomBound = _panelLayout.PaddingTop;
topBound = bottomBound - _panelLayout._slideRange;
}
return Math.Min(Math.Max(top, topBound), bottomBound);
}
}
protected override IParcelable OnSaveInstanceState()
{
var superState = base.OnSaveInstanceState();
var savedState = new SavedState(superState, _slideState);
return savedState;
}
protected override void OnRestoreInstanceState(IParcelable state)
{
try
{
var savedState = (SavedState) state;
base.OnRestoreInstanceState(savedState.SuperState);
_slideState = savedState.State;
}
catch
{
base.OnRestoreInstanceState(state);
}
}
public class SavedState : BaseSavedState
{
public SlideState State { get; private set; }
public SavedState(IParcelable superState, SlideState item)
: base(superState)
{
State = item;
}
public SavedState(Parcel parcel)
: base(parcel)
{
try
{
State = (SlideState) parcel.ReadInt();
}
catch
{
State = SlideState.Collapsed;
}
}
public override void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
{
base.WriteToParcel(dest, flags);
dest.WriteInt((int)State);
}
[ExportField("CREATOR")]
public static SavedStateCreator InitializeCreator()
{
return new SavedStateCreator();
}
public class SavedStateCreator : Java.Lang.Object, IParcelableCreator
{
public Java.Lang.Object CreateFromParcel(Parcel source)
{
return new SavedState(source);
}
public Java.Lang.Object[] NewArray(int size)
{
return new SavedState[size];
}
}
}
public static bool FloatNearlyEqual(float a, float b, float epsilon)
{
var absA = Math.Abs(a);
var absB = Math.Abs(b);
var diff = Math.Abs(a - b);
if (a == b) // shortcut, handles infinities
return true;
if (a == 0 || b == 0 || diff < float.MinValue)
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * float.MinValue);
// use relative error
return diff / (absA + absB) < epsilon;
}
public static bool FloatNearlyEqual(float a, float b)
{
return FloatNearlyEqual(a, b, 0.00001f);
}
}
}
| |
/*
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Services.InventoryService
{
public class XInventoryService : ServiceBase, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected IXInventoryData m_Database;
protected bool m_AllowDelete = true;
protected string m_ConfigName = "InventoryService";
public XInventoryService(IConfigSource config)
: this(config, "InventoryService")
{
}
public XInventoryService(IConfigSource config, string configName) : base(config)
{
if (configName != string.Empty)
m_ConfigName = configName;
string dllName = String.Empty;
string connString = String.Empty;
//string realm = "Inventory"; // OSG version doesn't use this
//
// Try reading the [InventoryService] section first, if it exists
//
IConfig authConfig = config.Configs[m_ConfigName];
if (authConfig != null)
{
dllName = authConfig.GetString("StorageProvider", dllName);
connString = authConfig.GetString("ConnectionString", connString);
m_AllowDelete = authConfig.GetBoolean("AllowDelete", true);
// realm = authConfig.GetString("Realm", realm);
}
//
// Try reading the [DatabaseService] section, if it exists
//
IConfig dbConfig = config.Configs["DatabaseService"];
if (dbConfig != null)
{
if (dllName == String.Empty)
dllName = dbConfig.GetString("StorageProvider", String.Empty);
if (connString == String.Empty)
connString = dbConfig.GetString("ConnectionString", String.Empty);
}
//
// We tried, but this doesn't exist. We can't proceed.
//
if (dllName == String.Empty)
throw new Exception("No StorageProvider configured");
m_Database = LoadPlugin<IXInventoryData>(dllName,
new Object[] {connString, String.Empty});
if (m_Database == null)
throw new Exception("Could not find a storage interface in the given module");
}
public virtual bool CreateUserInventory(UUID principalID)
{
// This is braindeaad. We can't ever communicate that we fixed
// an existing inventory. Well, just return root folder status,
// but check sanity anyway.
//
bool result = false;
InventoryFolderBase rootFolder = GetRootFolder(principalID);
if (rootFolder == null)
{
/* hard-code 8 here, so no update will ever fail us if such an update should happen */
rootFolder = ConvertToOpenSim(CreateFolder(principalID, UUID.Zero, (int)8 /* AssetType.RootFolder */, "My Inventory"));
result = true;
}
XInventoryFolder[] sysFolders = GetSystemFolders(principalID, rootFolder.ID);
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Animation) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Animation, "Animations");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Bodypart) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Bodypart, "Body Parts");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.CallingCard) return true; return false; }))
{
XInventoryFolder folder = CreateFolder(principalID, rootFolder.ID, (int)AssetType.CallingCard, "Calling Cards");
folder = CreateFolder(principalID, folder.folderID, (int)AssetType.CallingCard, "Friends");
CreateFolder(principalID, folder.folderID, (int)AssetType.CallingCard, "All");
}
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Clothing) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Clothing, "Clothing");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.CurrentOutfitFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.CurrentOutfitFolder, "Current Outfit");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.FavoriteFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.FavoriteFolder, "Favorites");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Gesture) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Gesture, "Gestures");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Landmark) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Landmark, "Landmarks");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.LostAndFoundFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.LostAndFoundFolder, "Lost And Found");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Notecard) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Notecard, "Notecards");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Object) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Object, "Objects");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.SnapshotFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.SnapshotFolder, "Photo Album");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.LSLText) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.LSLText, "Scripts");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Sound) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Sound, "Sounds");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Texture) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Texture, "Textures");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.TrashFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.TrashFolder, "Trash");
return result;
}
protected XInventoryFolder CreateFolder(UUID principalID, UUID parentID, int type, string name)
{
XInventoryFolder newFolder = new XInventoryFolder();
newFolder.folderName = name;
newFolder.type = type;
newFolder.version = 1;
newFolder.folderID = UUID.Random();
newFolder.agentID = principalID;
newFolder.parentFolderID = parentID;
m_Database.StoreFolder(newFolder);
return newFolder;
}
protected virtual XInventoryFolder[] GetSystemFolders(UUID principalID, UUID rootID)
{
// m_log.DebugFormat("[XINVENTORY SERVICE]: Getting system folders for {0}", principalID);
XInventoryFolder[] allFolders = m_Database.GetFolders(
new string[] { "agentID", "parentFolderID" },
new string[] { principalID.ToString(), rootID.ToString() });
XInventoryFolder[] sysFolders = Array.FindAll(
allFolders,
delegate (XInventoryFolder f)
{
if (f.type > 0)
return true;
return false;
});
// m_log.DebugFormat(
// "[XINVENTORY SERVICE]: Found {0} system folders for {1}", sysFolders.Length, principalID);
return sysFolders;
}
public virtual List<InventoryFolderBase> GetInventorySkeleton(UUID principalID)
{
XInventoryFolder[] allFolders = m_Database.GetFolders(
new string[] { "agentID" },
new string[] { principalID.ToString() });
if (allFolders.Length == 0)
return null;
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
foreach (XInventoryFolder x in allFolders)
{
//m_log.DebugFormat("[XINVENTORY SERVICE]: Adding folder {0} to skeleton", x.folderName);
folders.Add(ConvertToOpenSim(x));
}
return folders;
}
public virtual InventoryFolderBase GetRootFolder(UUID principalID)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "parentFolderID"},
new string[] { principalID.ToString(), UUID.Zero.ToString() });
if (folders.Length == 0)
return null;
XInventoryFolder root = null;
foreach (XInventoryFolder folder in folders)
{
if (folder.folderName == "My Inventory")
{
root = folder;
break;
}
}
if (root == null) // oops
root = folders[0];
return ConvertToOpenSim(root);
}
public virtual InventoryFolderBase GetFolderForType(UUID principalID, AssetType type)
{
// m_log.DebugFormat("[XINVENTORY SERVICE]: Getting folder type {0} for user {1}", type, principalID);
InventoryFolderBase rootFolder = GetRootFolder(principalID);
if (rootFolder == null)
{
m_log.WarnFormat(
"[XINVENTORY]: Found no root folder for {0} in GetFolderForType() when looking for {1}",
principalID, type);
return null;
}
return GetSystemFolderForType(rootFolder, type);
}
private InventoryFolderBase GetSystemFolderForType(InventoryFolderBase rootFolder, AssetType type)
{
// m_log.DebugFormat("[XINVENTORY SERVICE]: Getting folder type {0} for user {1}", type, principalID);
if (type == AssetType.RootFolder)
return rootFolder;
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "parentFolderID", "type"},
new string[] { rootFolder.Owner.ToString(), rootFolder.ID.ToString(), ((int)type).ToString() });
if (folders.Length == 0)
{
// m_log.WarnFormat("[XINVENTORY SERVICE]: Found no folder for type {0} for user {1}", type, principalID);
return null;
}
// m_log.DebugFormat(
// "[XINVENTORY SERVICE]: Found folder {0} {1} for type {2} for user {3}",
// folders[0].folderName, folders[0].folderID, type, principalID);
return ConvertToOpenSim(folders[0]);
}
public virtual InventoryCollection GetFolderContent(UUID principalID, UUID folderID)
{
// This method doesn't receive a valud principal id from the
// connector. So we disregard the principal and look
// by ID.
//
//m_log.DebugFormat("[XINVENTORY SERVICE]: Fetch contents for folder {0}", folderID.ToString());
InventoryCollection inventory = new InventoryCollection();
inventory.UserID = principalID;
inventory.Folders = new List<InventoryFolderBase>();
inventory.Items = new List<InventoryItemBase>();
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "parentFolderID"},
new string[] { folderID.ToString() });
foreach (XInventoryFolder x in folders)
{
//m_log.DebugFormat("[XINVENTORY]: Adding folder {0} to response", x.folderName);
inventory.Folders.Add(ConvertToOpenSim(x));
}
XInventoryItem[] items = m_Database.GetItems(
new string[] { "parentFolderID"},
new string[] { folderID.ToString() });
foreach (XInventoryItem i in items)
{
//m_log.DebugFormat("[XINVENTORY]: Adding item {0} to response", i.inventoryName);
inventory.Items.Add(ConvertToOpenSim(i));
}
return inventory;
}
public virtual List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID)
{
// m_log.DebugFormat("[XINVENTORY]: Fetch items for folder {0}", folderID);
// Since we probably don't get a valid principal here, either ...
//
List<InventoryItemBase> invItems = new List<InventoryItemBase>();
XInventoryItem[] items = m_Database.GetItems(
new string[] { "parentFolderID" },
new string[] { folderID.ToString() });
foreach (XInventoryItem i in items)
invItems.Add(ConvertToOpenSim(i));
return invItems;
}
public virtual bool AddFolder(InventoryFolderBase folder)
{
// m_log.DebugFormat("[XINVENTORY]: Add folder {0} type {1} in parent {2}", folder.Name, folder.Type, folder.ParentID);
InventoryFolderBase check = GetFolder(folder);
if (check != null)
return false;
if (folder.Type != (short)AssetType.Folder && folder.Type != (short)AssetType.Unknown)
{
InventoryFolderBase rootFolder = GetRootFolder(folder.Owner);
if (rootFolder == null)
{
m_log.WarnFormat(
"[XINVENTORY]: Found no root folder for {0} in AddFolder() when looking for {1}",
folder.Owner, folder.Type);
return false;
}
// Check we're not trying to add this as a system folder.
if (folder.ParentID == rootFolder.ID)
{
InventoryFolderBase existingSystemFolder
= GetSystemFolderForType(rootFolder, (AssetType)folder.Type);
if (existingSystemFolder != null)
{
m_log.WarnFormat(
"[XINVENTORY]: System folder of type {0} already exists when tried to add {1} to {2} for {3}",
folder.Type, folder.Name, folder.ParentID, folder.Owner);
return false;
}
}
}
XInventoryFolder xFolder = ConvertFromOpenSim(folder);
return m_Database.StoreFolder(xFolder);
}
public virtual bool UpdateFolder(InventoryFolderBase folder)
{
// m_log.DebugFormat("[XINVENTORY]: Update folder {0} {1} ({2})", folder.Name, folder.Type, folder.ID);
XInventoryFolder xFolder = ConvertFromOpenSim(folder);
InventoryFolderBase check = GetFolder(folder);
if (check == null)
return AddFolder(folder);
if ((check.Type != (short)AssetType.Unknown || xFolder.type != (short)AssetType.Unknown)
&& (check.Type != (short)AssetType.OutfitFolder || xFolder.type != (short)AssetType.OutfitFolder))
{
if (xFolder.version < check.Version)
{
// m_log.DebugFormat("[XINVENTORY]: {0} < {1} can't do", xFolder.version, check.Version);
return false;
}
check.Version = (ushort)xFolder.version;
xFolder = ConvertFromOpenSim(check);
// m_log.DebugFormat(
// "[XINVENTORY]: Storing version only update to system folder {0} {1} {2}",
// xFolder.folderName, xFolder.version, xFolder.type);
return m_Database.StoreFolder(xFolder);
}
if (xFolder.version < check.Version)
xFolder.version = check.Version;
xFolder.folderID = check.ID;
return m_Database.StoreFolder(xFolder);
}
public virtual bool MoveFolder(InventoryFolderBase folder)
{
return m_Database.MoveFolder(folder.ID.ToString(), folder.ParentID.ToString());
}
// We don't check the principal's ID here
//
public virtual bool DeleteFolders(UUID principalID, List<UUID> folderIDs)
{
return DeleteFolders(principalID, folderIDs, true);
}
public virtual bool DeleteFolders(UUID principalID, List<UUID> folderIDs, bool onlyIfTrash)
{
if (!m_AllowDelete)
return false;
// Ignore principal ID, it's bogus at connector level
//
foreach (UUID id in folderIDs)
{
if (onlyIfTrash && !ParentIsTrash(id))
continue;
//m_log.InfoFormat("[XINVENTORY SERVICE]: Delete folder {0}", id);
InventoryFolderBase f = new InventoryFolderBase();
f.ID = id;
PurgeFolder(f, onlyIfTrash);
m_Database.DeleteFolders("folderID", id.ToString());
}
return true;
}
public virtual bool PurgeFolder(InventoryFolderBase folder)
{
return PurgeFolder(folder, true);
}
public virtual bool PurgeFolder(InventoryFolderBase folder, bool onlyIfTrash)
{
if (!m_AllowDelete)
return false;
if (onlyIfTrash && !ParentIsTrash(folder.ID))
return false;
XInventoryFolder[] subFolders = m_Database.GetFolders(
new string[] { "parentFolderID" },
new string[] { folder.ID.ToString() });
foreach (XInventoryFolder x in subFolders)
{
PurgeFolder(ConvertToOpenSim(x), onlyIfTrash);
m_Database.DeleteFolders("folderID", x.folderID.ToString());
}
m_Database.DeleteItems("parentFolderID", folder.ID.ToString());
return true;
}
public virtual bool AddItem(InventoryItemBase item)
{
// m_log.DebugFormat(
// "[XINVENTORY SERVICE]: Adding item {0} {1} to folder {2} for {3}", item.Name, item.ID, item.Folder, item.Owner);
return m_Database.StoreItem(ConvertFromOpenSim(item));
}
public virtual bool UpdateItem(InventoryItemBase item)
{
if (!m_AllowDelete)
if (item.AssetType == (sbyte)AssetType.Link || item.AssetType == (sbyte)AssetType.LinkFolder)
return false;
// m_log.InfoFormat(
// "[XINVENTORY SERVICE]: Updating item {0} {1} in folder {2}", item.Name, item.ID, item.Folder);
InventoryItemBase retrievedItem = GetItem(item);
if (retrievedItem == null)
{
m_log.WarnFormat(
"[XINVENTORY SERVICE]: Tried to update item {0} {1}, owner {2} but no existing item found.",
item.Name, item.ID, item.Owner);
return false;
}
// Do not allow invariants to change. Changes to folder ID occur in MoveItems()
if (retrievedItem.InvType != item.InvType
|| retrievedItem.AssetType != item.AssetType
|| retrievedItem.Folder != item.Folder
|| retrievedItem.CreatorIdentification != item.CreatorIdentification
|| retrievedItem.Owner != item.Owner)
{
m_log.WarnFormat(
"[XINVENTORY SERVICE]: Caller to UpdateItem() for {0} {1} tried to alter property(s) that should be invariant, (InvType, AssetType, Folder, CreatorIdentification, Owner), existing ({2}, {3}, {4}, {5}, {6}), update ({7}, {8}, {9}, {10}, {11})",
retrievedItem.Name,
retrievedItem.ID,
retrievedItem.InvType,
retrievedItem.AssetType,
retrievedItem.Folder,
retrievedItem.CreatorIdentification,
retrievedItem.Owner,
item.InvType,
item.AssetType,
item.Folder,
item.CreatorIdentification,
item.Owner);
item.InvType = retrievedItem.InvType;
item.AssetType = retrievedItem.AssetType;
item.Folder = retrievedItem.Folder;
item.CreatorIdentification = retrievedItem.CreatorIdentification;
item.Owner = retrievedItem.Owner;
}
return m_Database.StoreItem(ConvertFromOpenSim(item));
}
public virtual bool MoveItems(UUID principalID, List<InventoryItemBase> items)
{
// Principal is b0rked. *sigh*
//
foreach (InventoryItemBase i in items)
{
m_Database.MoveItem(i.ID.ToString(), i.Folder.ToString());
}
return true;
}
public virtual bool DeleteItems(UUID principalID, List<UUID> itemIDs)
{
if (!m_AllowDelete)
{
// We must still allow links and links to folders to be deleted, otherwise they will build up
// in the player's inventory until they can no longer log in. Deletions of links due to code bugs or
// similar is inconvenient but on a par with accidental movement of items. The original item is never
// touched.
foreach (UUID id in itemIDs)
{
if (!m_Database.DeleteItems(
new string[] { "inventoryID", "assetType" },
new string[] { id.ToString(), ((sbyte)AssetType.Link).ToString() }))
{
m_Database.DeleteItems(
new string[] { "inventoryID", "assetType" },
new string[] { id.ToString(), ((sbyte)AssetType.LinkFolder).ToString() });
}
}
}
else
{
// Just use the ID... *facepalms*
//
foreach (UUID id in itemIDs)
m_Database.DeleteItems("inventoryID", id.ToString());
}
return true;
}
public virtual InventoryItemBase GetItem(InventoryItemBase item)
{
XInventoryItem[] items = m_Database.GetItems(
new string[] { "inventoryID" },
new string[] { item.ID.ToString() });
if (items.Length == 0)
return null;
return ConvertToOpenSim(items[0]);
}
public virtual InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "folderID"},
new string[] { folder.ID.ToString() });
if (folders.Length == 0)
return null;
return ConvertToOpenSim(folders[0]);
}
public virtual List<InventoryItemBase> GetActiveGestures(UUID principalID)
{
XInventoryItem[] items = m_Database.GetActiveGestures(principalID);
if (items.Length == 0)
return new List<InventoryItemBase>();
List<InventoryItemBase> ret = new List<InventoryItemBase>();
foreach (XInventoryItem x in items)
ret.Add(ConvertToOpenSim(x));
return ret;
}
// Unused.
//
public bool HasInventoryForUser(UUID userID)
{
return false;
}
// CM Helpers
//
protected InventoryFolderBase ConvertToOpenSim(XInventoryFolder folder)
{
InventoryFolderBase newFolder = new InventoryFolderBase();
newFolder.ParentID = folder.parentFolderID;
newFolder.Type = (short)folder.type;
// Viewer can't understand anything that's not in it's LLFolderType enum
if (newFolder.Type == InventoryItemBase.SUITCASE_FOLDER_TYPE)
newFolder.Type = InventoryItemBase.SUITCASE_FOLDER_FAKE_TYPE;
newFolder.Version = (ushort)folder.version;
newFolder.Name = folder.folderName;
newFolder.Owner = folder.agentID;
newFolder.ID = folder.folderID;
return newFolder;
}
protected XInventoryFolder ConvertFromOpenSim(InventoryFolderBase folder)
{
XInventoryFolder newFolder = new XInventoryFolder();
newFolder.parentFolderID = folder.ParentID;
newFolder.type = (int)folder.Type;
newFolder.version = (int)folder.Version;
newFolder.folderName = folder.Name;
newFolder.agentID = folder.Owner;
newFolder.folderID = folder.ID;
return newFolder;
}
protected InventoryItemBase ConvertToOpenSim(XInventoryItem item)
{
InventoryItemBase newItem = new InventoryItemBase();
newItem.AssetID = item.assetID;
newItem.AssetType = item.assetType;
newItem.Name = item.inventoryName;
newItem.Owner = item.avatarID;
newItem.ID = item.inventoryID;
newItem.InvType = item.invType;
newItem.Folder = item.parentFolderID;
newItem.CreatorIdentification = item.creatorID;
newItem.Description = item.inventoryDescription;
newItem.NextPermissions = (uint)item.inventoryNextPermissions;
newItem.CurrentPermissions = (uint)item.inventoryCurrentPermissions;
newItem.BasePermissions = (uint)item.inventoryBasePermissions;
newItem.EveryOnePermissions = (uint)item.inventoryEveryOnePermissions;
newItem.GroupPermissions = (uint)item.inventoryGroupPermissions;
newItem.GroupID = item.groupID;
if (item.groupOwned == 0)
newItem.GroupOwned = false;
else
newItem.GroupOwned = true;
newItem.SalePrice = item.salePrice;
newItem.SaleType = (byte)item.saleType;
newItem.Flags = (uint)item.flags;
newItem.CreationDate = item.creationDate;
return newItem;
}
protected XInventoryItem ConvertFromOpenSim(InventoryItemBase item)
{
XInventoryItem newItem = new XInventoryItem();
newItem.assetID = item.AssetID;
newItem.assetType = item.AssetType;
newItem.inventoryName = item.Name;
newItem.avatarID = item.Owner;
newItem.inventoryID = item.ID;
newItem.invType = item.InvType;
newItem.parentFolderID = item.Folder;
newItem.creatorID = item.CreatorIdentification;
newItem.inventoryDescription = item.Description;
newItem.inventoryNextPermissions = (int)item.NextPermissions;
newItem.inventoryCurrentPermissions = (int)item.CurrentPermissions;
newItem.inventoryBasePermissions = (int)item.BasePermissions;
newItem.inventoryEveryOnePermissions = (int)item.EveryOnePermissions;
newItem.inventoryGroupPermissions = (int)item.GroupPermissions;
newItem.groupID = item.GroupID;
if (item.GroupOwned)
newItem.groupOwned = 1;
else
newItem.groupOwned = 0;
newItem.salePrice = item.SalePrice;
newItem.saleType = (int)item.SaleType;
newItem.flags = (int)item.Flags;
newItem.creationDate = item.CreationDate;
return newItem;
}
private bool ParentIsTrash(UUID folderID)
{
XInventoryFolder[] folder = m_Database.GetFolders(new string[] {"folderID"}, new string[] {folderID.ToString()});
if (folder.Length < 1)
return false;
if (folder[0].type == (int)AssetType.TrashFolder)
return true;
UUID parentFolder = folder[0].parentFolderID;
while (parentFolder != UUID.Zero)
{
XInventoryFolder[] parent = m_Database.GetFolders(new string[] {"folderID"}, new string[] {parentFolder.ToString()});
if (parent.Length < 1)
return false;
if (parent[0].type == (int)AssetType.TrashFolder)
return true;
if (parent[0].type == (int)AssetType.RootFolder)
return false;
parentFolder = parent[0].parentFolderID;
}
return false;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Examplinvi.AccountActivity.ASP.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace UserManager.Massive {
public static class ObjectExtensions {
/// <summary>
/// Extension method for adding in a bunch of parameters
/// </summary>
public static void AddParams(this DbCommand cmd, params object[] args) {
foreach (var item in args) {
AddParam(cmd, item);
}
}
/// <summary>
/// Extension for adding single parameter
/// </summary>
public static void AddParam(this DbCommand cmd, object item) {
var p = cmd.CreateParameter();
p.ParameterName = string.Format("@{0}", cmd.Parameters.Count);
if (item == null) {
p.Value = DBNull.Value;
} else {
if (item.GetType() == typeof(Guid)) {
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
} else if (item.GetType() == typeof(ExpandoObject)) {
var d = (IDictionary<string, object>)item;
p.Value = d.Values.FirstOrDefault();
} else {
p.Value = item;
}
if (item.GetType() == typeof(string))
p.Size = ((string)item).Length > 4000 ? -1 : 4000;
}
cmd.Parameters.Add(p);
}
/// <summary>
/// Turns an IDataReader to a Dynamic list of things
/// </summary>
public static List<dynamic> ToExpandoList(this IDataReader rdr) {
var result = new List<dynamic>();
while (rdr.Read()) {
result.Add(rdr.RecordToExpando());
}
return result;
}
public static dynamic RecordToExpando(this IDataReader rdr) {
dynamic e = new ExpandoObject();
var d = e as IDictionary<string, object>;
for (int i = 0; i < rdr.FieldCount; i++)
d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]);
return e;
}
/// <summary>
/// Turns the object into an ExpandoObject
/// </summary>
public static dynamic ToExpando(this object o) {
var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case
if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))) {
var nv = (NameValueCollection)o;
nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i));
} else {
var props = o.GetType().GetProperties();
foreach (var item in props) {
d.Add(item.Name, item.GetValue(o, null));
}
}
return result;
}
/// <summary>
/// Turns the object into a Dictionary
/// </summary>
public static IDictionary<string, object> ToDictionary(this object thingy) {
return (IDictionary<string, object>)thingy.ToExpando();
}
}
/// <summary>
/// Convenience class for opening/executing data
/// </summary>
public static class DB {
public static DynamicModel Current {
get {
if (ConfigurationManager.ConnectionStrings.Count > 1) {
return new DynamicModel(ConfigurationManager.ConnectionStrings[1].Name);
}
throw new InvalidOperationException("Need a connection string name - can't determine what it is");
}
}
}
/// <summary>
/// A class that wraps your database table in Dynamic Funtime
/// </summary>
public class DynamicModel : DynamicObject {
DbProviderFactory _factory;
string ConnectionString;
public static DynamicModel Open(string connectionStringName) {
dynamic dm = new DynamicModel(connectionStringName);
return dm;
}
public DynamicModel(string connectionStringName, string tableName = "",
string primaryKeyField = "", string descriptorField = "") {
TableName = tableName == "" ? this.GetType().Name : tableName;
PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;
DescriptorField = descriptorField;
var _providerName = "System.Data.SqlClient";
if (!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName))
_providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName;
_factory = DbProviderFactories.GetFactory(_providerName);
ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
/// <summary>
/// Creates a new Expando from a Form POST - white listed against the columns in the DB
/// </summary>
public dynamic CreateFrom(NameValueCollection coll) {
dynamic result = new ExpandoObject();
var dc = (IDictionary<string, object>)result;
var schema = Schema;
//loop the collection, setting only what's in the Schema
foreach (var item in coll.Keys) {
var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower());
if (exists) {
var key = item.ToString();
var val = coll[key];
dc.Add(key, val);
}
}
return result;
}
/// <summary>
/// Gets a default value for the column
/// </summary>
public dynamic DefaultValue(dynamic column) {
dynamic result = null;
string def = column.COLUMN_DEFAULT;
if (String.IsNullOrEmpty(def)) {
result = null;
} else if (def == "getdate()" || def == "(getdate())") {
result = DateTime.Now.ToShortDateString();
} else if (def == "newid()") {
result = Guid.NewGuid().ToString();
} else {
result = def.Replace("(", "").Replace(")", "");
}
return result;
}
/// <summary>
/// Creates an empty Expando set with defaults from the DB
/// </summary>
public dynamic Prototype {
get {
dynamic result = new ExpandoObject();
var schema = Schema;
foreach (dynamic column in schema) {
var dc = (IDictionary<string, object>)result;
dc.Add(column.COLUMN_NAME, DefaultValue(column));
}
result._Table = this;
return result;
}
}
public string DescriptorField { get; protected set; }
/// <summary>
/// List out all the schema bits for use with ... whatever
/// </summary>
IEnumerable<dynamic> _schema;
public IEnumerable<dynamic> Schema {
get {
if (_schema == null)
_schema = Query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @0", TableName);
return _schema;
}
}
/// <summary>
/// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert
/// </summary>
public virtual IEnumerable<dynamic> Query(string sql, params object[] args) {
using (var conn = OpenConnection()) {
var rdr = CreateCommand(sql, conn, args).ExecuteReader();
while (rdr.Read()) {
yield return rdr.RecordToExpando(); ;
}
//Added by Ashish - Connection Pool Issues
if (rdr != null)
{
rdr.Close();
}
}
}
public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args) {
using (var rdr = CreateCommand(sql, connection, args).ExecuteReader()) {
while (rdr.Read()) {
yield return rdr.RecordToExpando(); ;
}
//Added by Ashish - Connection Pool Issues
if (rdr != null)
{
rdr.Close();
}
}
}
/// <summary>
/// Returns a single result
/// </summary>
public virtual object Scalar(string sql, params object[] args) {
object result = null;
using (var conn = OpenConnection()) {
result = CreateCommand(sql, conn, args).ExecuteScalar();
}
return result;
}
/// <summary>
/// Creates a DBCommand that you can use for loving your database.
/// </summary>
DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) {
var result = _factory.CreateCommand();
result.Connection = conn;
result.CommandText = sql;
if (args.Length > 0)
result.AddParams(args);
return result;
}
/// <summary>
/// Returns and OpenConnection
/// </summary>
public virtual DbConnection OpenConnection() {
var result = _factory.CreateConnection();
result.ConnectionString = ConnectionString;
result.Open();
return result;
}
/// <summary>
/// Builds a set of Insert and Update commands based on the passed-on objects.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual List<DbCommand> BuildCommands(params object[] things) {
var commands = new List<DbCommand>();
foreach (var item in things) {
if (HasPrimaryKey(item)) {
commands.Add(CreateUpdateCommand(item.ToExpando(), GetPrimaryKey(item)));
} else {
commands.Add(CreateInsertCommand(item.ToExpando()));
}
}
return commands;
}
public virtual int Execute(DbCommand command) {
return Execute(new DbCommand[] { command });
}
public virtual int Execute(string sql, params object[] args) {
return Execute(CreateCommand(sql, null, args));
}
/// <summary>
/// Executes a series of DBCommands in a transaction
/// </summary>
public virtual int Execute(IEnumerable<DbCommand> commands) {
var result = 0;
using (var conn = OpenConnection()) {
using (var tx = conn.BeginTransaction()) {
foreach (var cmd in commands) {
cmd.Connection = conn;
cmd.Transaction = tx;
result += cmd.ExecuteNonQuery();
}
tx.Commit();
}
}
return result;
}
public virtual string PrimaryKeyField { get; set; }
/// <summary>
/// Conventionally introspects the object passed in for a field that
/// looks like a PK. If you've named your PrimaryKeyField, this becomes easy
/// </summary>
public virtual bool HasPrimaryKey(object o) {
return o.ToDictionary().ContainsKey(PrimaryKeyField);
}
/// <summary>
/// If the object passed in has a property with the same name as your PrimaryKeyField
/// it is returned here.
/// </summary>
public virtual object GetPrimaryKey(object o) {
object result = null;
o.ToDictionary().TryGetValue(PrimaryKeyField, out result);
return result;
}
public virtual string TableName { get; set; }
/// <summary>
/// Returns all records complying with the passed-in WHERE clause and arguments,
/// ordered as specified, limited (TOP) by limit.
/// </summary>
public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args) {
string sql = BuildSelect(where, orderBy, limit);
return Query(string.Format(sql, columns, TableName), args);
}
private static string BuildSelect(string where, string orderBy, int limit) {
string sql = limit > 0 ? "SELECT TOP " + limit + " {0} FROM {1} " : "SELECT {0} FROM {1} ";
if (!string.IsNullOrEmpty(where))
sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : " WHERE " + where;
if (!String.IsNullOrEmpty(orderBy))
sql += orderBy.Trim().StartsWith("order by", StringComparison.OrdinalIgnoreCase) ? orderBy : " ORDER BY " + orderBy;
return sql;
}
/// <summary>
/// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
/// </summary>
public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
{
return BuildPagedResult(where: where, orderBy: orderBy, columns: columns, pageSize: pageSize, currentPage: currentPage, args: args);
}
public virtual dynamic Paged(string sql, string primaryKey, string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
{
return BuildPagedResult(sql, primaryKey, where, orderBy, columns, pageSize, currentPage, args);
}
private dynamic BuildPagedResult(string sql = "", string primaryKeyField = "", string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
{
dynamic result = new ExpandoObject();
var countSQL = "";
if (!string.IsNullOrEmpty(sql))
countSQL = string.Format("SELECT COUNT({0}) FROM ({1}) AS PagedTable", primaryKeyField, sql);
else
countSQL = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName);
if (String.IsNullOrEmpty(orderBy))
{
orderBy = string.IsNullOrEmpty(primaryKeyField) ? PrimaryKeyField : primaryKeyField;
}
if (!string.IsNullOrEmpty(where))
{
if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase))
{
where = " WHERE " + where;
}
}
var query = "";
if (!string.IsNullOrEmpty(sql))
query = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM ({3}) AS PagedTable {4}) AS Paged ", columns, pageSize, orderBy, sql, where);
else
query = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where);
var pageStart = (currentPage - 1) * pageSize;
query += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize));
countSQL += where;
result.TotalRecords = Scalar(countSQL, args);
result.TotalPages = result.TotalRecords / pageSize;
if (result.TotalRecords % pageSize > 0)
result.TotalPages += 1;
result.Items = Query(string.Format(query, columns, TableName), args);
return result;
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(string where, params object[] args) {
var sql = string.Format("SELECT * FROM {0} WHERE {1}", TableName, where);
return Query(sql, args).FirstOrDefault();
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(object key, string columns = "*") {
var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField);
return Query(sql, key).FirstOrDefault();
}
/// <summary>
/// This will return a string/object dictionary for dropdowns etc
/// </summary>
public virtual IDictionary<string, object> KeyValues(string orderBy = "") {
if (String.IsNullOrEmpty(DescriptorField))
throw new InvalidOperationException("There's no DescriptorField set - do this in your constructor to describe the text value you want to see");
var sql = string.Format("SELECT {0},{1} FROM {2} ", PrimaryKeyField, DescriptorField, TableName);
if (!String.IsNullOrEmpty(orderBy))
sql += "ORDER BY " + orderBy;
var results = Query(sql).ToList().Cast<IDictionary<string, object>>();
return results.ToDictionary(key => key[PrimaryKeyField].ToString(), value => value[DescriptorField]);
}
/// <summary>
/// This will return an Expando as a Dictionary
/// </summary>
public virtual IDictionary<string, object> ItemAsDictionary(ExpandoObject item) {
return (IDictionary<string, object>)item;
}
//Checks to see if a key is present based on the passed-in value
public virtual bool ItemContainsKey(string key, ExpandoObject item) {
var dc = ItemAsDictionary(item);
return dc.ContainsKey(key);
}
/// <summary>
/// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual int Save(params object[] things) {
foreach (var item in things) {
if (!IsValid(item)) {
throw new InvalidOperationException("Can't save this item: " + String.Join("; ", Errors.ToArray()));
}
}
var commands = BuildCommands(things);
return Execute(commands);
}
public virtual DbCommand CreateInsertCommand(dynamic expando) {
DbCommand result = null;
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var sbVals = new StringBuilder();
var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})";
result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings) {
sbKeys.AppendFormat("{0},", item.Key);
sbVals.AppendFormat("@{0},", counter.ToString());
result.AddParam(item.Value);
counter++;
}
if (counter > 0) {
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1);
var vals = sbVals.ToString().Substring(0, sbVals.Length - 1);
var sql = string.Format(stub, TableName, keys, vals);
result.CommandText = sql;
} else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set");
return result;
}
/// <summary>
/// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
/// </summary>
public virtual DbCommand CreateUpdateCommand(dynamic expando, object key) {
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}";
var args = new List<object>();
var result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings) {
var val = item.Value;
if (!item.Key.Equals(PrimaryKeyField, StringComparison.OrdinalIgnoreCase) && item.Value != null) {
result.AddParam(val);
sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter.ToString());
counter++;
}
}
if (counter > 0) {
//add the key
result.AddParam(key);
//strip the last commas
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4);
result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter);
} else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs");
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args) {
var sql = string.Format("DELETE FROM {0} ", TableName);
if (key != null) {
sql += string.Format("WHERE {0}=@0", PrimaryKeyField);
args = new object[] { key };
} else if (!string.IsNullOrEmpty(where)) {
sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where;
}
return CreateCommand(sql, null, args);
}
public bool IsValid(dynamic item) {
Errors.Clear();
Validate(item);
return Errors.Count == 0;
}
//Temporary holder for error messages
public IList<string> Errors = new List<string>();
/// <summary>
/// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString
/// </summary>
public virtual dynamic Insert(object o) {
var ex = o.ToExpando();
if (!IsValid(ex)) {
throw new InvalidOperationException("Can't insert: " + String.Join("; ", Errors.ToArray()));
}
if (BeforeSave(ex)) {
using (dynamic conn = OpenConnection()) {
var cmd = CreateInsertCommand(ex);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT @@IDENTITY as newID";
ex.ID = cmd.ExecuteScalar();
Inserted(ex);
}
return ex;
} else {
return null;
}
}
/// <summary>
/// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString
/// </summary>
public virtual int Update(object o, object key) {
var ex = o.ToExpando();
if (!IsValid(ex)) {
throw new InvalidOperationException("Can't Update: " + String.Join("; ", Errors.ToArray()));
}
var result = 0;
if (BeforeSave(ex)) {
result = Execute(CreateUpdateCommand(ex, key));
Updated(ex);
}
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public int Delete(object key = null, string where = "", params object[] args) {
var deleted = this.Single(key);
var result = 0;
if (BeforeDelete(deleted)) {
result = Execute(CreateDeleteCommand(where: where, key: key, args: args));
Deleted(deleted);
}
return result;
}
public void DefaultTo(string key, object value, dynamic item) {
if (!ItemContainsKey(key, item)) {
var dc = (IDictionary<string, object>)item;
dc[key] = value;
}
}
//Hooks
public virtual void Validate(dynamic item) { }
public virtual void Inserted(dynamic item) { }
public virtual void Updated(dynamic item) { }
public virtual void Deleted(dynamic item) { }
public virtual bool BeforeDelete(dynamic item) { return true; }
public virtual bool BeforeSave(dynamic item) { return true; }
//validation methods
public virtual void ValidatesPresenceOf(object value, string message = "Required") {
if (value == null)
Errors.Add(message);
if (String.IsNullOrEmpty(value.ToString()))
Errors.Add(message);
}
//fun methods
public virtual void ValidatesNumericalityOf(object value, string message = "Should be a number") {
var type = value.GetType().Name;
var numerics = new string[] { "Int32", "Int16", "Int64", "Decimal", "Double", "Single", "Float" };
if (!numerics.Contains(type)) {
Errors.Add(message);
}
}
public virtual void ValidateIsCurrency(object value, string message = "Should be money") {
if (value == null)
Errors.Add(message);
decimal val = decimal.MinValue;
decimal.TryParse(value.ToString(), out val);
if (val == decimal.MinValue)
Errors.Add(message);
}
public int Count() {
return Count(TableName);
}
public int Count(string tableName, string where="", params object[] args) {
return (int)Scalar("SELECT COUNT(*) FROM " + tableName+" "+ where, args);
}
/// <summary>
/// A helpful query tool
/// </summary>
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
//parse the method
var constraints = new List<string>();
var counter = 0;
var info = binder.CallInfo;
// accepting named args only... SKEET!
if (info.ArgumentNames.Count != args.Length) {
throw new InvalidOperationException("Please use named arguments for this type of query - the column name, orderby, columns, etc");
}
//first should be "FindBy, Last, Single, First"
var op = binder.Name;
var columns = " * ";
string orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField);
string sql = "";
string where = "";
var whereArgs = new List<object>();
//loop the named args - see if we have order, columns and constraints
if (info.ArgumentNames.Count > 0) {
for (int i = 0; i < args.Length; i++) {
var name = info.ArgumentNames[i].ToLower();
switch (name) {
case "orderby":
orderBy = " ORDER BY " + args[i];
break;
case "columns":
columns = args[i].ToString();
break;
default:
constraints.Add(string.Format(" {0} = @{1}", name, counter));
whereArgs.Add(args[i]);
counter++;
break;
}
}
}
//Build the WHERE bits
if (constraints.Count > 0) {
where = " WHERE " + string.Join(" AND ", constraints.ToArray());
}
//probably a bit much here but... yeah this whole thing needs to be refactored...
if (op.ToLower() == "count") {
result = Scalar("SELECT COUNT(*) FROM " + TableName + where, whereArgs.ToArray());
} else if (op.ToLower() == "sum") {
result = Scalar("SELECT SUM(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
} else if (op.ToLower() == "max") {
result = Scalar("SELECT MAX(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
} else if (op.ToLower() == "min") {
result = Scalar("SELECT MIN(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
} else if (op.ToLower() == "avg") {
result = Scalar("SELECT AVG(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
} else {
//build the SQL
sql = "SELECT TOP 1 " + columns + " FROM " + TableName + where;
var justOne = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get") || op.StartsWith("Single");
//Be sure to sort by DESC on the PK (PK Sort is the default)
if (op.StartsWith("Last")) {
orderBy = orderBy + " DESC ";
} else {
//default to multiple
sql = "SELECT " + columns + " FROM " + TableName + where;
}
if (justOne) {
//return a single record
result = Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault();
} else {
//return lots
result = Query(sql + orderBy, whereArgs.ToArray());
}
}
return true;
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.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.
//
#endregion
[assembly: Elmah.Scc("$Id: Error.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Diagnostics;
using System.Globalization;
using System.Security;
using System.Security.Principal;
using System.Web;
using System.Xml;
using Thread = System.Threading.Thread;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
#endregion
/// <summary>
/// Represents a logical application error (as opposed to the actual
/// exception it may be representing).
/// </summary>
[ Serializable ]
public sealed class Error : ICloneable
{
private readonly Exception _exception;
private string _applicationName;
private string _hostName;
private string _typeName;
private string _source;
private string _message;
private string _detail;
private string _user;
private DateTime _time;
private int _statusCode;
private string _webHostHtmlMessage;
private NameValueCollection _serverVariables;
private NameValueCollection _queryString;
private NameValueCollection _form;
private NameValueCollection _cookies;
private NameValueCollection _exceptionData;
/// <summary>
/// Initializes a new instance of the <see cref="Error"/> class.
/// </summary>
public Error() {}
/// <summary>
/// Initializes a new instance of the <see cref="Error"/> class
/// from a given <see cref="Exception"/> instance.
/// </summary>
public Error(Exception e) :
this(e, null) {}
/// <summary>
/// Initializes a new instance of the <see cref="Error"/> class
/// from a given <see cref="Exception"/> instance and
/// <see cref="HttpContext"/> instance representing the HTTP
/// context during the exception.
/// </summary>
public Error(Exception e, HttpContext context)
{
if (e == null)
throw new ArgumentNullException("e");
_exception = e;
Exception baseException = e.GetBaseException();
//
// Load the basic information.
//
_hostName = Environment.TryGetMachineName(context);
_typeName = baseException.GetType().FullName;
_message = baseException.Message;
_source = baseException.Source;
_detail = e.ToString();
_user = Mask.NullString(Thread.CurrentPrincipal.Identity.Name);
_time = DateTime.Now;
//
// If this is an HTTP exception, then get the status code
// and detailed HTML message provided by the host.
//
HttpException httpException = e as HttpException;
if (httpException != null)
{
_statusCode = httpException.GetHttpCode();
_webHostHtmlMessage = TryGetHtmlErrorMessage(httpException);
}
//
// If the HTTP context is available, then capture the
// collections that represent the state request as well as
// the user.
//
if (context != null)
{
IPrincipal webUser = context.User;
if (webUser != null
&& Mask.NullString(webUser.Identity.Name).Length > 0)
{
_user = webUser.Identity.Name;
}
HttpRequest request = context.Request;
_serverVariables = CopyCollection(request.ServerVariables);
if (_serverVariables != null)
{
// Hack for issue #140:
// http://code.google.com/p/elmah/issues/detail?id=140
const string authPasswordKey = "AUTH_PASSWORD";
string authPassword = _serverVariables[authPasswordKey];
if (authPassword != null) // yes, mask empty too!
_serverVariables[authPasswordKey] = "*****";
}
_queryString = CopyCollection(request.QueryString);
_form = CopyCollection(request.Form);
_cookies = CopyCollection(request.Cookies);
}
}
private static string TryGetHtmlErrorMessage(HttpException e)
{
Debug.Assert(e != null);
try
{
return e.GetHtmlErrorMessage();
}
catch (SecurityException se)
{
// In partial trust environments, HttpException.GetHtmlErrorMessage()
// has been known to throw:
// System.Security.SecurityException: Request for the
// permission of type 'System.Web.AspNetHostingPermission' failed.
//
// See issue #179 for more background:
// http://code.google.com/p/elmah/issues/detail?id=179
Trace.WriteLine(se);
return null;
}
}
/// <summary>
/// Gets the <see cref="Exception"/> instance used to initialize this
/// instance.
/// </summary>
/// <remarks>
/// This is a run-time property only that is not written or read
/// during XML serialization via <see cref="ErrorXml.Decode"/> and
/// <see cref="ErrorXml.Encode(Error,XmlWriter)"/>.
/// </remarks>
public Exception Exception
{
get { return _exception; }
}
/// <summary>
/// Gets or sets the name of application in which this error occurred.
/// </summary>
public string ApplicationName
{
get { return Mask.NullString(_applicationName); }
set { _applicationName = value; }
}
/// <summary>
/// Gets or sets name of host machine where this error occurred.
/// </summary>
public string HostName
{
get { return Mask.NullString(_hostName); }
set { _hostName = value; }
}
/// <summary>
/// Gets or sets the type, class or category of the error.
/// </summary>
public string Type
{
get { return Mask.NullString(_typeName); }
set { _typeName = value; }
}
/// <summary>
/// Gets or sets the source that is the cause of the error.
/// </summary>
public string Source
{
get { return Mask.NullString(_source); }
set { _source = value; }
}
/// <summary>
/// Gets or sets a brief text describing the error.
/// </summary>
public string Message
{
get { return Mask.NullString(_message); }
set { _message = value; }
}
/// <summary>
/// Gets or sets a detailed text describing the error, such as a
/// stack trace.
/// </summary>
public string Detail
{
get { return Mask.NullString(_detail); }
set { _detail = value; }
}
/// <summary>
/// Gets or sets the user logged into the application at the time
/// of the error.
/// </summary>
public string User
{
get { return Mask.NullString(_user); }
set { _user = value; }
}
/// <summary>
/// Gets or sets the date and time (in local time) at which the
/// error occurred.
/// </summary>
public DateTime Time
{
get { return _time; }
set { _time = value; }
}
/// <summary>
/// Gets or sets the HTTP status code of the output returned to the
/// client for the error.
/// </summary>
/// <remarks>
/// For cases where this value cannot always be reliably determined,
/// the value may be reported as zero.
/// </remarks>
public int StatusCode
{
get { return _statusCode; }
set { _statusCode = value; }
}
/// <summary>
/// Gets or sets the HTML message generated by the web host (ASP.NET)
/// for the given error.
/// </summary>
public string WebHostHtmlMessage
{
get { return Mask.NullString(_webHostHtmlMessage); }
set { _webHostHtmlMessage = value; }
}
/// <summary>
/// Gets a collection representing the Web server variables
/// captured as part of diagnostic data for the error.
/// </summary>
public NameValueCollection ServerVariables
{
get { return FaultIn(ref _serverVariables); }
}
/// <summary>
/// Gets a collection representing the Web query string variables
/// captured as part of diagnostic data for the error.
/// </summary>
public NameValueCollection QueryString
{
get { return FaultIn(ref _queryString); }
}
/// <summary>
/// Gets a collection representing the form variables captured as
/// part of diagnostic data for the error.
/// </summary>
public NameValueCollection Form
{
get { return FaultIn(ref _form); }
}
/// <summary>
/// Gets a collection representing the client cookies
/// captured as part of diagnostic data for the error.
/// </summary>
public NameValueCollection Cookies
{
get { return FaultIn(ref _cookies); }
}
/// <summary>
/// Gets a collection representing the exception data (Exception.Data) only for .net, current and two InnerExcepation data
/// captured as part of diagnostic data for the error.
/// </summary>
public NameValueCollection ExceptionData
{
get { return FaultIn(ref _exceptionData); }
}
/// <summary>
/// Returns the value of the <see cref="Message"/> property.
/// </summary>
public override string ToString()
{
return this.Message;
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
object ICloneable.Clone()
{
//
// Make a base shallow copy of all the members.
//
Error copy = (Error) MemberwiseClone();
//
// Now make a deep copy of items that are mutable.
//
copy._serverVariables = CopyCollection(_serverVariables);
copy._queryString = CopyCollection(_queryString);
copy._form = CopyCollection(_form);
copy._cookies = CopyCollection(_cookies);
return copy;
}
private static NameValueCollection CopyCollection(NameValueCollection collection)
{
if (collection == null || collection.Count == 0)
return null;
return new NameValueCollection(collection);
}
private static NameValueCollection CopyCollection(HttpCookieCollection cookies)
{
if (cookies == null || cookies.Count == 0)
return null;
NameValueCollection copy = new NameValueCollection(cookies.Count);
for (int i = 0; i < cookies.Count; i++)
{
HttpCookie cookie = cookies[i];
//
// NOTE: We drop the Path and Domain properties of the
// cookie for sake of simplicity.
//
copy.Add(cookie.Name, cookie.Value);
}
return copy;
}
private static NameValueCollection FaultIn(ref NameValueCollection collection)
{
if (collection == null)
collection = new NameValueCollection();
return collection;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System;
using System.IO;
namespace UMA
{
[System.Serializable]
public class UMAResourcesIndexData
{
//there is no need to be able to edit this index in a release because you cannot add anything to resources in a built game
//to update resources you would need to update the game and so you would update the index this creates.
#region special types
[System.Serializable]
public class TypeIndex
{
public string type;
public NameIndex[] typeFiles;
public TypeIndex() { }
public TypeIndex(string _type, int _nameHash, string _path = "")
{
type = _type;
typeFiles = new NameIndex[1];
typeFiles[0] = new NameIndex(_nameHash, _path);
}
public int Count()
{
return typeFiles.Length;
}
public void Add(int nameHash, string path)
{
bool found = false;
for (int i = 0; i < typeFiles.Length; i++)
{
if (typeFiles[i].nameHash == nameHash)
{
typeFiles[i].path = path;
found = true;
}
}
if (!found)
{
var list = new NameIndex[typeFiles.Length + 1];
Array.Copy(typeFiles, list, typeFiles.Length);
list[typeFiles.Length] = new NameIndex(nameHash, path);
typeFiles = list;
}
}
public void Remove(int nameHash)
{
var list = new NameIndex[typeFiles.Length - 1];
int listi = 0;
for (int i = 0; i < typeFiles.Length; i++)
{
if (typeFiles[i].nameHash != nameHash)
{
list[listi].nameHash = typeFiles[i].nameHash;
list[listi].path = typeFiles[i].path;
listi++;
}
}
typeFiles = list;
}
public string Get(int nameHash)
{
for (int i = 0; i < typeFiles.Length; i++)
{
if (typeFiles[i].nameHash == nameHash)
{
return typeFiles[i].path;
}
}
return "";
}
}
[System.Serializable]
public class NameIndex
{
public int nameHash;
public string path;
public NameIndex()
{
}
public NameIndex(int _nameHash, string _path)
{
nameHash = _nameHash;
path = _path;
}
}
#endregion
public TypeIndex[] data = new TypeIndex[0];
public int Count()
{
int totalCount = 0;
for (int i = 0; i < data.Length; i++)
{
totalCount += data[i].Count();
}
return totalCount;
}
#if UNITY_EDITOR
/// <summary>
/// Adds a path terporarily to the index. To add it permanently use UMAResourcesIndex.Instance.Add
/// </summary>
/// <param name="obj"></param>
/// <param name="objName"></param>
public void AddPath(UnityEngine.Object obj, string objName)
{
AddPath(obj, UMAUtils.StringToHash(objName));
}
/// <summary>
/// Adds a path terporarily to the index. To add it permanently use UMAResourcesIndex.Instance.Add
/// </summary>
/// <param name="obj"></param>
/// <param name="objNameHash"></param>
public void AddPath(UnityEngine.Object obj, int objNameHash)
{
if (obj == null)
return;
var objFullPath = AssetDatabase.GetAssetPath(obj);
var objResourcesPathArray = objFullPath.Split(new string[] { "Resources/" }, StringSplitOptions.RemoveEmptyEntries);
var extension = Path.GetExtension(objResourcesPathArray[1]);
var objResourcesPath = objResourcesPathArray[1];
if (extension != "")
{
objResourcesPath = objResourcesPath.Replace(extension, "");
}
bool hadType = false;
for (int i = 0; i < data.Length; i++)
{
if (data[i].type == obj.GetType().ToString())
{
data[i].Add(objNameHash, objResourcesPath);
hadType = true;
}
}
if (!hadType)
{
var list = new TypeIndex[data.Length + 1];
Array.Copy(data, list, data.Length);
list[data.Length] = new TypeIndex(obj.GetType().ToString(), objNameHash, objResourcesPath);
data = list;
}
}
#endif
public void Remove(System.Type type)
{
var list = new TypeIndex[data.Length - 1];
int listi = 0;
for (int i = 0; i < data.Length; i++)
{
if (data[i].type != type.ToString())
{
list[listi] = data[i];
listi++;
}
}
data = list;
}
public void Remove<T>(string thisName) where T : UnityEngine.Object
{
Remove<T>(UMAUtils.StringToHash(thisName));
}
public void Remove<T>(int nameHash) where T : UnityEngine.Object
{
for (int i = 0; i < data.Length; i++)
{
if (data[i].type == typeof(T).ToString())
{
data[i].Remove(nameHash);
if (data[i].Count() == 0)
Remove(typeof(T));
}
}
}
/// <summary>
/// Get a path out of the index, optionally filtering result based on specified folders
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="thisName"></param>
/// <param name="foldersToSearch"></param>
/// <returns></returns>
public string GetPath<T>(string thisName, string[] foldersToSearch = null) where T : UnityEngine.Object
{
return GetPath<T>(UMAUtils.StringToHash(thisName), foldersToSearch);
}
/// <summary>
/// Get a path out of the index, optionally filtering result based on specified folders
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="nameHash"></param>
/// <param name="foldersToSearch"></param>
/// <returns></returns>
public string GetPath<T>(int nameHash, string[] foldersToSearch = null) where T : UnityEngine.Object
{
for (int i = 0; i < data.Length; i++)
{
if (data[i].type == typeof(T).ToString())
{
var foundPath = data[i].Get(nameHash);
if (foldersToSearch != null && foldersToSearch.Length > 0)
{
for (int ii = 0; ii < foldersToSearch.Length; ii++)
{
if (foundPath.IndexOf(foldersToSearch[ii]) > -1)
{
return foundPath;
}
}
}
else
{
return foundPath;
}
}
}
return "";
}
public string[] GetPaths<T>(string[] foldersToSearch = null) where T : UnityEngine.Object
{
List<string> foundPaths = new List<string>();
for (int i = 0; i < data.Length; i++)
{
if (data[i].type == typeof(T).ToString())
{
for (int ii = 0; ii < data[i].typeFiles.Length; ii++)
{
if (foldersToSearch != null && foldersToSearch.Length > 0)
{
for (int iii = 0; iii < foldersToSearch.Length; iii++)
{
if (data[i].typeFiles[ii].path.IndexOf(foldersToSearch[iii]) > -1)
{
foundPaths.Add(data[i].typeFiles[ii].path);
break;
}
}
}
else
{
foundPaths.Add(data[i].typeFiles[ii].path);
}
}
}
}
return foundPaths.ToArray();
}
}
}
| |
/*
Copyright (c) 2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Globalization;
namespace PHP.Core.Parsers
{
#region PhpStringBuilder
/// <summary>
/// The PHP-semantic string builder. Binary or Unicode string builder.
/// </summary>
internal class PhpStringBuilder
{
#region Fields & Properties
/// <summary>
/// Currently used encoding.
/// </summary>
private readonly Encoding/*!*/encoding;
private readonly byte[] encodeBytes = new byte[4];
private readonly char[] encodeChars = new char[5];
private StringBuilder _unicodeBuilder;
private List<byte> _binaryBuilder;
private bool IsUnicode { get { return !IsBinary; } }
private bool IsBinary { get { return _binaryBuilder != null; } }
private Text.Span span;
/// <summary>
/// Length of contained data (string or byte[]).
/// </summary>
public int Length
{
get
{
if (_unicodeBuilder != null)
return _unicodeBuilder.Length;
else if (_binaryBuilder != null)
return _binaryBuilder.Count;
else
return 0;
}
}
private StringBuilder UnicodeBuilder
{
get
{
if (_unicodeBuilder == null)
{
if (_binaryBuilder != null && _binaryBuilder.Count > 0)
{
byte[] bytes = _binaryBuilder.ToArray();
_unicodeBuilder = new StringBuilder(encoding.GetString(bytes,0,bytes.Length ));
}
else
{
_unicodeBuilder = new StringBuilder();
}
_binaryBuilder = null;
}
return _unicodeBuilder;
}
}
private List<byte> BinaryBuilder
{
get
{
if (_binaryBuilder == null)
{
if (_unicodeBuilder != null && _unicodeBuilder.Length > 0)
{
_binaryBuilder = new List<byte>(encoding.GetBytes(_unicodeBuilder.ToString()));
}
else
{
_binaryBuilder = new List<byte>();
}
_unicodeBuilder = null;
}
return _binaryBuilder;
}
}
#endregion
#region Results
/// <summary>
/// The result of builder: String or byte[].
/// </summary>
public object Result
{
get
{
if (IsBinary)
return BinaryBuilder.ToArray();
else
return UnicodeBuilder.ToString();
}
}
public PHP.Core.AST.Literal CreateLiteral()
{
if (IsBinary)
return new PHP.Core.AST.BinaryStringLiteral(span, BinaryBuilder.ToArray());
else
return new PHP.Core.AST.StringLiteral(span, UnicodeBuilder.ToString());
}
#endregion
#region Construct
/// <summary>
/// Initialize the PhpStringBuilder.
/// </summary>
/// <param name="encoding"></param>
/// <param name="binary"></param>
/// <param name="initialLength"></param>
public PhpStringBuilder(Encoding/*!*/encoding, bool binary, int initialLength)
{
Debug.Assert(encoding != null);
this.encoding = encoding;
this.span = Text.Span.Invalid;
//if (binary)
// _binaryBuilder = new List<byte>(initialLength);
//else
_unicodeBuilder = new StringBuilder(initialLength);
}
public PhpStringBuilder(Encoding/*!*/encoding, string/*!*/value, Text.Span span)
:this(encoding, false, value.Length)
{
Append(value, span);
}
#endregion
#region Append
private void Append(Text.Span span)
{
if (this.span.IsValid)
{
if (span.IsValid)
this.span = Text.Span.Combine(this.span, span);
}
else
{
this.span = span;
}
}
public void Append(string str, Text.Span span)
{
Append(span);
Append(str);
}
public void Append(string str)
{
if (IsUnicode)
UnicodeBuilder.Append(str);
else
{
BinaryBuilder.AddRange(encoding.GetBytes(str));
}
}
public void Append(char c, Text.Span span)
{
Append(span);
Append(c);
}
public void Append(char c)
{
if (IsUnicode)
UnicodeBuilder.Append(c);
else
{
encodeChars[0] = c;
int count = encoding.GetBytes(encodeChars, 0, 1, encodeBytes, 0);
for (int i = 0; i < count; ++i)
BinaryBuilder.Add(encodeBytes[i]);
}
}
public void Append(byte b, Text.Span span)
{
Append(span);
Append(b);
}
public void Append(byte b)
{
// force binary string
if (IsUnicode)
{
encodeBytes[0] = b;
UnicodeBuilder.Append(encodeChars, 0, encoding.GetChars(encodeBytes, 0, 1, encodeChars, 0));
}
else
BinaryBuilder.Add(b);
}
public void Append(int c, Text.Span span)
{
Append(span);
Append(c);
}
public void Append(int c)
{
Debug.Assert(c >= 0);
//if (c <= 0xff)
if (IsBinary)
BinaryBuilder.Add((byte)c);
else
UnicodeBuilder.Append((char)c);
}
#endregion
#region Misc
/// <summary>
/// Trim ending /r/n or /n characters. Assuming the string ends with /n.
/// </summary>
internal void TrimEoln()
{
if (IsUnicode)
{
if (UnicodeBuilder.Length > 0)
{
if (UnicodeBuilder.Length >= 2 && UnicodeBuilder[UnicodeBuilder.Length - 2] == '\r')
{
// trim ending \r\n:
UnicodeBuilder.Length -= 2;
}
else
{
// trim ending \n:
UnicodeBuilder.Length -= 1;
}
}
}
else
{
if (BinaryBuilder.Count > 0)
{
if (BinaryBuilder.Count >= 2 && BinaryBuilder[BinaryBuilder.Count - 2] == (byte)'\r')
{
BinaryBuilder.RemoveRange(BinaryBuilder.Count - 2, 2);
}
else
{
BinaryBuilder.RemoveAt(BinaryBuilder.Count - 1);
}
}
}
}
#endregion
}
#endregion
public partial class Lexer
{
protected bool AllowAspTags = true;
protected bool AllowShortTags = true;
/// <summary>
/// Whether tokens T_STRING, T_VARIABLE, '[', ']', '{', '}', '$', "->" are encapsulated in a string.
/// </summary>
protected bool inString;
/// <summary>
/// Whether T_STRING token should be treated as a string code token and not a plain string token.
/// </summary>
protected bool isCode;
public bool InUnicodeString { get { return inUnicodeString; } set { inUnicodeString = true; } }
private bool inUnicodeString = false;
protected string hereDocLabel = null;
protected Stack<LexicalStates> StateStack { get { return stateStack; } set { stateStack = value; } }
protected void _yymore() { yymore(); }
#region Token Buffer Interpretation
public int GetTokenByteLength(Encoding/*!*/ encoding)
{
return encoding.GetByteCount(buffer, token_start, token_end - token_start);
}
protected char[] Buffer { get { return buffer; } }
protected int BufferTokenStart { get { return token_start; } }
protected char GetTokenChar(int index)
{
return buffer[token_start + index];
}
protected string GetTokenString()
{
return new String(buffer, token_start, token_end - token_start);
}
protected string GetTokenChunkString()
{
return new String(buffer, token_chunk_start, token_end - token_chunk_start);
}
protected string GetTokenSubstring(int startIndex)
{
return new String(buffer, token_start + startIndex, token_end - token_start - startIndex);
}
protected string GetTokenSubstring(int startIndex, int length)
{
return new String(buffer, token_start + startIndex, length);
}
protected void AppendTokenTextTo(StringBuilder/*!*/ builder)
{
builder.Append(buffer, token_start, token_end - token_start);
}
/// <summary>
/// Checks whether a specified heredoc lebel exactly matches {LABEL} in ^{LABEL}(";")?{NEWLINE}.
/// </summary>
private bool IsCurrentHeredocEnd(int startIndex)
{
int i = StringUtils.FirstDifferent(buffer, token_start + startIndex, hereDocLabel, 0, false);
return i == hereDocLabel.Length && (buffer[token_start + i] == ';' ||
IsNewLineCharacter(buffer[token_start + i]));
}
protected char GetTokenAsEscapedCharacter(int startIndex)
{
Debug.Assert(GetTokenChar(startIndex) == '\\');
char c;
switch (c = GetTokenChar(startIndex + 1))
{
case 'n': return '\n';
case 't': return '\t';
case 'r': return '\r';
default: return c;
}
}
/// <summary>
/// Checks whether {LNUM} fits to integer, long or double
/// and returns appropriate value from Tokens enum.
/// </summary>
protected Tokens GetIntegerTokenType(int startIndex)
{
int i = token_start + startIndex;
while (i < token_end && buffer[i] == '0') i++;
int number_length = token_end - i;
if (i != token_start + startIndex)
{
// starts with zero - octal
// similar to GetHexIntegerTokenType code
if ((number_length < 11) || (number_length == 11 && buffer[i] == '1'))
return Tokens.T_LNUMBER;
if (number_length < 22)
return Tokens.T_L64NUMBER;
return Tokens.T_DNUMBER;
}
else
{
// decimal
if (number_length < 10)
return Tokens.T_LNUMBER;
if (number_length > 19)
return Tokens.T_DNUMBER;
if (number_length >= 11 && number_length <= 18)
return Tokens.T_L64NUMBER;
// can't easily check for numbers of different length
SemanticValueType val = default(SemanticValueType);
return GetTokenAsDecimalNumber(startIndex, 10, ref val);
}
}
/// <summary>
/// Checks whether {HNUM} fits to integer, long or double
/// and returns appropriate value from Tokens enum.
/// </summary>
protected Tokens GetHexIntegerTokenType(int startIndex)
{
// 0xffffffff no
// 0x7fffffff yes
int i = token_start + startIndex;
while (i < token_end && buffer[i] == '0') i++;
// returns T_LNUMBER when: length without zeros is less than 8
// or equals 8 and first non-zero character is less than '8'
if ((token_end - i < 8) || ((token_end - i == 8) && buffer[i] >= '0' && buffer[i] < '8'))
return Tokens.T_LNUMBER;
// similar for long
if ((token_end - i < 16) || ((token_end - i == 16) && buffer[i] >= '0' && buffer[i] < '8'))
return Tokens.T_L64NUMBER;
return Tokens.T_DNUMBER;
}
// base == 10: [0-9]*
// base == 16: [0-9A-Fa-f]*
// assuming result < max int
protected int GetTokenAsInteger(int startIndex, int @base)
{
int result = 0;
int buffer_pos = token_start + startIndex;
for (; ; )
{
int digit = Convert.AlphaNumericToDigit(buffer[buffer_pos]);
if (digit >= @base) break;
result = result * @base + digit;
buffer_pos++;
}
return result;
}
/// <summary>
/// Reads token as a number (accepts tokens with any reasonable base [0-9a-zA-Z]*).
/// Parsed value is stored in <paramref name="val"/> as integer (when value is less than MaxInt),
/// as Long (when value is less then MaxLong) or as double.
/// </summary>
/// <param name="startIndex">Starting read position of the token.</param>
/// <param name="base">The base of the number.</param>
/// <param name="val">Parsed value is stored in this union</param>
/// <returns>Returns one of T_LNUMBER (int), T_L64NUMBER (long) or T_DNUMBER (double)</returns>
protected Tokens GetTokenAsDecimalNumber(int startIndex, int @base, ref SemanticValueType val)
{
long lresult = 0;
double dresult = 0;
int digit;
int buffer_pos = token_start + startIndex;
// try to parse INT value
// most of the literals are parsed using the following loop
while (buffer_pos < buffer.Length && (digit = Convert.AlphaNumericToDigit(buffer[buffer_pos])) < @base && lresult <= Int32.MaxValue)
{
lresult = lresult * @base + digit;
buffer_pos++;
}
if (lresult > Int32.MaxValue)
{
// try to parse LONG value (check for the overflow and if it occurs converts data to double)
bool longOverflow = false;
while (buffer_pos < buffer.Length && (digit = Convert.AlphaNumericToDigit(buffer[buffer_pos])) < @base)
{
try
{
lresult = checked(lresult * @base + digit);
}
catch (OverflowException)
{
longOverflow = true; break;
}
buffer_pos++;
}
if (longOverflow)
{
// too big for LONG - use double
dresult = (double)lresult;
while (buffer_pos < buffer.Length && (digit = Convert.AlphaNumericToDigit(buffer[buffer_pos])) < @base)
{
dresult = dresult * @base + digit;
buffer_pos++;
}
val.Double = dresult;
return Tokens.T_DNUMBER;
}
else
{
val.Long = lresult;
return Tokens.T_L64NUMBER;
}
}
else
{
val.Integer = (int)lresult;
return Tokens.T_LNUMBER;
}
}
// [0-9]*[.][0-9]+
// [0-9]+[.][0-9]*
// [0-9]*[.][0-9]+[eE][+-]?[0-9]+
// [0-9]+[.][0-9]*[eE][+-]?[0-9]+
// [0-9]+[eE][+-]?[0-9]+
protected double GetTokenAsDouble(int startIndex)
{
string str = new string(buffer, token_start, token_end - token_start);
try
{
return double.Parse(
str,
NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
CultureInfo.InvariantCulture);
}
catch (OverflowException)
{
return (str.Length > 0 && str[0] == '-') ? double.NegativeInfinity : double.PositiveInfinity;
}
}
//protected void GetTokenAsQualifiedName(int startIndex, List<string>/*!*/ result)
//{
// Debug.Assert(result != null);
// int current_name = token_start + startIndex;
// int next_separator = token_start + startIndex;
// for (; ; )
// {
// while (next_separator < token_end && buffer[next_separator] != '\\')
// next_separator++;
// if (next_separator == token_end) break;
// result.Add(new String(buffer, current_name, next_separator - current_name));
// next_separator += QualifiedName.Separator.ToString().Length;
// current_name = next_separator;
// }
// // last item:
// result.Add(new String(buffer, current_name, token_end - current_name));
//}
#region GetTokenAs*QuotedString
protected object GetTokenAsDoublyQuotedString(int startIndex, Encoding/*!*/ encoding, bool forceBinaryString)
{
PhpStringBuilder result = new PhpStringBuilder(encoding, forceBinaryString, TokenLength);
int buffer_pos = token_start + startIndex + 1;
// the following loops expect the token ending by "
Debug.Assert(buffer[buffer_pos - 1] == '"' && buffer[token_end - 1] == '"');
//StringBuilder result = new StringBuilder(TokenLength);
char c;
while ((c = buffer[buffer_pos++]) != '"')
{
if (c == '\\')
{
switch (c = buffer[buffer_pos++])
{
case 'n':
result.Append('\n');
break;
case 'r':
result.Append('\r');
break;
case 't':
result.Append('\t');
break;
case '\\':
case '$':
case '"':
result.Append(c);
break;
case 'C':
if (!inUnicodeString) goto default;
result.Append(ParseCodePointName(ref buffer_pos));
break;
case 'u':
case 'U':
if (!inUnicodeString) goto default;
result.Append(ParseCodePoint(c == 'u' ? 4 : 6, ref buffer_pos));
break;
case 'x':
{
int digit;
if ((digit = Convert.AlphaNumericToDigit(buffer[buffer_pos])) < 16)
{
int hex_code = digit;
buffer_pos++;
if ((digit = Convert.AlphaNumericToDigit(buffer[buffer_pos])) < 16)
{
buffer_pos++;
hex_code = (hex_code << 4) + digit;
}
//encodeBytes[0] = (byte)hex_code;
//result.Append(encodeChars, 0, encoding.GetChars(encodeBytes, 0, 1, encodeChars, 0));
result.Append((byte)hex_code);
}
else
{
result.Append('\\');
result.Append('x');
}
break;
}
default:
{
int digit;
if ((digit = Convert.NumericToDigit(c)) < 8)
{
int octal_code = digit;
if ((digit = Convert.NumericToDigit(buffer[buffer_pos])) < 8)
{
octal_code = (octal_code << 3) + digit;
buffer_pos++;
if ((digit = Convert.NumericToDigit(buffer[buffer_pos])) < 8)
{
buffer_pos++;
octal_code = (octal_code << 3) + digit;
}
}
//encodeBytes[0] = (byte)octal_code;
//result.Append(encodeChars, 0, encoding.GetChars(encodeBytes, 0, 1, encodeChars, 0));
result.Append((byte)octal_code);
}
else
{
result.Append('\\');
result.Append(c);
}
break;
}
}
}
else
{
result.Append(c);
}
}
return result.Result;
}
protected object GetTokenAsSinglyQuotedString(int startIndex, Encoding/*!*/ encoding, bool forceBinaryString)
{
PhpStringBuilder result = new PhpStringBuilder(encoding, forceBinaryString, TokenLength);
int buffer_pos = token_start + startIndex + 1;
// the following loops expect the token ending by '
Debug.Assert(buffer[buffer_pos - 1] == '\'' && buffer[token_end - 1] == '\'');
//StringBuilder result = new StringBuilder(TokenLength);
char c;
while ((c = buffer[buffer_pos++]) != '\'')
{
if (c == '\\')
{
switch (c = buffer[buffer_pos++])
{
case '\\':
case '\'':
result.Append(c);
break;
// ??? will cause many problems ... but PHP allows this
//case 'C':
// if (!inUnicodeString) goto default;
// result.Append(ParseCodePointName(ref buffer_pos));
// break;
//case 'u':
//case 'U':
// if (!inUnicodeString) goto default;
// result.Append(ParseCodePoint( c == 'u' ? 4 : 6, ref buffer_pos));
// break;
default:
result.Append('\\');
result.Append(c);
break;
}
}
else
{
result.Append(c);
}
}
return result.Result;
}
#endregion
private string ParseCodePointName(ref int pos)
{
if (buffer[pos] == '{')
{
int start = ++pos;
while (pos < token_end && buffer[pos] != '}') pos++;
if (pos < token_end)
{
string name = new String(buffer, start, pos - start);
// TODO: name look-up
// return ...[name];
// skip '}'
pos++;
}
}
//errors.Add(Errors.InvalidCodePointName, sourceFile, );
return "?";
}
private string ParseCodePoint(int maxLength, ref int pos)
{
int digit;
int code_point = 0;
while (maxLength > 0 && (digit = Convert.NumericToDigit(buffer[pos])) < 16)
{
code_point = code_point << 4 + digit;
pos++;
maxLength--;
}
if (maxLength != 0)
{
// TODO: warning
}
try
{
if ((code_point < 0 || code_point > 0x10ffff) || (code_point >= 0xd800 && code_point <= 0xdfff))
{
// TODO: errors.Add(Errors.InvalidCodePoint, sourceFile, tokenPosition.Short, GetTokenString());
return "?";
}
else
{
return StringUtils.Utf32ToString(code_point);
}
}
catch (ArgumentOutOfRangeException)
{
// TODO: errors.Add(Errors.InvalidCodePoint, sourceFile, tokenPosition.Short, GetTokenString());
return "?";
}
}
private int GetPragmaValueStart(int directiveLength)
{
int buffer_pos = token_start + "#pragma".Length;
Debug.Assert(new String(buffer, token_start, buffer_pos - token_start) == "#pragma");
while (buffer[buffer_pos] == ' ' || buffer[buffer_pos] == '\t') buffer_pos++;
buffer_pos += directiveLength;
while (buffer[buffer_pos] == ' ' || buffer[buffer_pos] == '\t') buffer_pos++;
return buffer_pos - token_start;
}
protected string GetTokenAsFilePragma()
{
int start_offset = GetPragmaValueStart("file".Length);
int end = token_end - 1;
while (end > 0 && Char.IsWhiteSpace(buffer[end])) end--;
return GetTokenSubstring(start_offset, end - token_start - start_offset + 1);
}
protected int? GetTokenAsLinePragma()
{
int start_offset = GetPragmaValueStart("line".Length);
int sign = +1;
if (GetTokenChar(start_offset) == '-')
{
sign = -1;
start_offset++;
}
// TP_COMMENT: modified call to GetTokenAsDecimalNumber
SemanticValueType val = default(SemanticValueType);
Tokens ret = GetTokenAsDecimalNumber(start_offset, 10, ref val);
// multiplication cannot overflow as ivalue >= 0
return (ret!=Tokens.T_LNUMBER) ? null : (int?)(val.Integer * sign);
}
#endregion
private char Map(char c)
{
return (c > SByte.MaxValue) ? 'a' : c;
}
/*
* #region Unit Test
#if DEBUG
[Test]
static void Test2()
{
Debug.Assert(IsInteger("000000000000000001"));
Debug.Assert(IsInteger("0000"));
Debug.Assert(IsInteger("0"));
Debug.Assert(IsInteger("2147483647"));
Debug.Assert(!IsInteger("2147483648"));
Debug.Assert(!IsInteger("2147483648999999999999999999999999999999999999"));
Debug.Assert(IsHexInteger("0x00000000000001"));
Debug.Assert(IsHexInteger("0x00000"));
Debug.Assert(IsHexInteger("0x"));
Debug.Assert(!IsHexInteger("0x0012ABC67891"));
Debug.Assert(IsHexInteger("0xFFFFFFFF"));
Debug.Assert(!IsHexInteger("0x100000000"));
Debug.Assert(HereDocLabelsEqual("EOT", "EOT;\n"));
Debug.Assert(!HereDocLabelsEqual("EOT", "EOt\n"));
Debug.Assert(!HereDocLabelsEqual("EOT", "EOTT;\n"));
Debug.Assert(!HereDocLabelsEqual("EOT", "EOTT\n"));
Debug.Assert(!HereDocLabelsEqual("EOTX", "EOT\r"));
Debug.Assert(!HereDocLabelsEqual("EOTXYZ", "EOT\r"));
}
#endif
#endregion
*/
}
}
| |
using System;
using numl.Utils;
using numl.Model;
using System.Data;
using System.Linq;
using System.Dynamic;
using numl.Tests.Data;
using NUnit.Framework;
using System.Collections.Generic;
namespace numl.Tests.DataTests
{
[TestFixture, Category("Data")]
public class SimpleConversionTests
{
public static IEnumerable<string> ShortStrings
{
get
{
yield return "OnE!";
yield return "TWo2";
yield return "t#hrE^e";
yield return "T%hrE@e";
}
}
public static IEnumerable<string> WordStrings
{
get
{
yield return "TH@e QUi#CK bRow!N fox 12";
yield return "s@upeR B#roWN BEaR";
yield return "1829! UGlY FoX";
yield return "ThE QuICk beAr";
}
}
[Test]
public void Test_Univariate_Conversions()
{
// boolean
Assert.AreEqual(1, Ject.Convert(true));
Assert.AreEqual(-1, Ject.Convert(false));
// numeric types
Assert.AreEqual(1d, Ject.Convert((Byte)1)); // byte
Assert.AreEqual(1d, Ject.Convert((SByte)1)); // sbyte
Assert.AreEqual(0.4d, Ject.Convert((Decimal)0.4m)); // decimal
Assert.AreEqual(0.1d, Ject.Convert((Double)0.1d)); // double
Assert.AreEqual(300d, Ject.Convert((Single)300f)); // single
Assert.AreEqual(1d, Ject.Convert((Int16)1)); // int16
Assert.AreEqual(2d, Ject.Convert((UInt16)2)); // uint16
Assert.AreEqual(2323432, Ject.Convert((Int32)2323432)); // int32
Assert.AreEqual(2323432d, Ject.Convert((UInt32)2323432)); // uint32
Assert.AreEqual(1232323434345d, Ject.Convert((Int64)1232323434345)); // int64
Assert.AreEqual(1232323434345d, Ject.Convert((UInt64)1232323434345)); // uint64
Assert.AreEqual(1232323434345d, Ject.Convert((long)1232323434345)); // long
// enum
Assert.AreEqual(0d, Ject.Convert(FakeEnum.Item0));
Assert.AreEqual(1d, Ject.Convert(FakeEnum.Item1));
Assert.AreEqual(2d, Ject.Convert(FakeEnum.Item2));
Assert.AreEqual(3d, Ject.Convert(FakeEnum.Item3));
Assert.AreEqual(4d, Ject.Convert(FakeEnum.Item4));
Assert.AreEqual(5d, Ject.Convert(FakeEnum.Item5));
Assert.AreEqual(6d, Ject.Convert(FakeEnum.Item6));
Assert.AreEqual(7d, Ject.Convert(FakeEnum.Item7));
Assert.AreEqual(8d, Ject.Convert(FakeEnum.Item8));
Assert.AreEqual(9d, Ject.Convert(FakeEnum.Item9));
// char
Assert.AreEqual(65d, Ject.Convert('A'));
// timespan
Assert.AreEqual(300d, Ject.Convert(TimeSpan.FromSeconds(300)));
}
[Test]
public void Test_Univariate_Back_Conversions()
{
// boolean
Assert.AreEqual(true, Ject.Convert(1, typeof(bool)));
Assert.AreEqual(false, Ject.Convert(-1, typeof(bool)));
// numeric types
Assert.AreEqual((Byte)1, Ject.Convert(1d, typeof(Byte))); // byte
Assert.AreEqual((SByte)1, Ject.Convert(1d, typeof(SByte))); // sbyte
Assert.AreEqual((Decimal)0.4m, Ject.Convert(0.4d, typeof(Decimal))); // decimal
Assert.AreEqual((Double)0.1d, Ject.Convert(0.1d, typeof(Double))); // double
Assert.AreEqual((Single)300f, Ject.Convert(300d, typeof(Single))); // single
Assert.AreEqual((Int16)1, Ject.Convert(1d, typeof(Int16))); // int16
Assert.AreEqual((UInt16)2, Ject.Convert(2d, typeof(UInt16))); // uint16
Assert.AreEqual((Int32)2323432, Ject.Convert(2323432, typeof(Int32))); // int32
Assert.AreEqual((UInt32)2323432, Ject.Convert(2323432d, typeof(UInt32))); // uint32
Assert.AreEqual((Int64)1232323434345, Ject.Convert(1232323434345d, typeof(Int64))); // int64
Assert.AreEqual((UInt64)1232323434345, Ject.Convert(1232323434345d, typeof(UInt64))); // uint64
Assert.AreEqual((long)1232323434345, Ject.Convert(1232323434345d, typeof(long))); // long
// enum
Assert.AreEqual(FakeEnum.Item0, Ject.Convert(0d, typeof(FakeEnum)));
Assert.AreEqual(FakeEnum.Item1, Ject.Convert(1d, typeof(FakeEnum)));
Assert.AreEqual(FakeEnum.Item2, Ject.Convert(2d, typeof(FakeEnum)));
Assert.AreEqual(FakeEnum.Item3, Ject.Convert(3d, typeof(FakeEnum)));
Assert.AreEqual(FakeEnum.Item4, Ject.Convert(4d, typeof(FakeEnum)));
Assert.AreEqual(FakeEnum.Item5, Ject.Convert(5d, typeof(FakeEnum)));
Assert.AreEqual(FakeEnum.Item6, Ject.Convert(6d, typeof(FakeEnum)));
Assert.AreEqual(FakeEnum.Item7, Ject.Convert(7d, typeof(FakeEnum)));
Assert.AreEqual(FakeEnum.Item8, Ject.Convert(8d, typeof(FakeEnum)));
Assert.AreEqual(FakeEnum.Item9, Ject.Convert(9d, typeof(FakeEnum)));
// char
Assert.AreEqual('A', Ject.Convert(65d, typeof(char)));
// timespan
Assert.AreEqual(TimeSpan.FromSeconds(300), Ject.Convert(300d, typeof(TimeSpan)));
}
[Test]
public void Test_Char_Dictionary_Gen()
{
var d = StringHelpers.BuildCharDictionary(ShortStrings);
// should have the following:
// O(2), N(1), E(5), #SYM#(5), T(3), W(1), #NUM#(1), H(2), R(2)
var dict = new Dictionary<string, double>
{
{ "O", 2 },
{ "N", 1 },
{ "E", 5 },
{ "#SYM#", 5 },
{ "T", 3 },
{ "W", 1 },
{ "#NUM#", 1 },
{ "H", 2 },
{ "R", 2 },
};
Assert.AreEqual(dict, d);
}
[Test]
public void Test_Enum_Dictionary_Gen()
{
var d = StringHelpers.BuildEnumDictionary(ShortStrings);
// should have the following:
// ONE(1), TWO2(1), THREE(2)
var dict = new Dictionary<string, double>
{
{ "ONE", 1 },
{ "TWO2", 1 },
{ "THREE", 2 },
};
Assert.AreEqual(dict, d);
}
[Test]
public void Test_Word_Dictionary_Gen()
{
var d = StringHelpers.BuildWordDictionary(WordStrings);
// should have the following:
var dict = new Dictionary<string, double>
{
{ "THE", 2 },
{ "QUICK", 2 },
{ "BROWN", 2 },
{ "FOX", 2 },
{ "#NUM#", 2 },
{ "SUPER", 1 },
{ "BEAR", 2 },
{ "UGLY", 1 },
};
Assert.AreEqual(dict, d);
}
[Test]
public void Test_Fast_Reflection_Get_Standard()
{
var o = new Student
{
Age = 23,
Friends = 12,
GPA = 3.2,
Grade = Grade.A,
Name = "Jordan Spears",
Tall = true,
Nice = false
};
var age = Ject.Get(o, "Age");
Assert.AreEqual(23, (int)age);
var friends = Ject.Get(o, "Friends");
Assert.AreEqual(12, (int)friends);
var gpa = Ject.Get(o, "GPA");
Assert.AreEqual(3.2, (double)gpa);
var grade = Ject.Get(o, "Grade");
Assert.AreEqual(Grade.A, (Grade)grade);
var name = Ject.Get(o, "Name");
Assert.AreEqual("Jordan Spears", (string)name);
var tall = Ject.Get(o, "Tall");
Assert.AreEqual(true, (bool)tall);
var nice = Ject.Get(o, "Nice");
Assert.AreEqual(false, (bool)nice);
}
[Test]
public void Test_Fast_Reflection_Set_Standard()
{
var o = new Student
{
Age = 23,
Friends = 12,
GPA = 3.2,
Grade = Grade.A,
Name = "Jordan Spears",
Tall = true,
Nice = false
};
Ject.Set(o, "Age", 25);
Assert.AreEqual(25, o.Age);
Ject.Set(o, "Friends", 1);
Assert.AreEqual(1, o.Friends);
Ject.Set(o, "GPA", 1.2);
Assert.AreEqual(1.2, o.GPA);
Ject.Set(o, "Grade", Grade.C);
Assert.AreEqual(Grade.C, o.Grade);
Ject.Set(o, "Name", "Seth Juarez");
Assert.AreEqual("Seth Juarez", o.Name);
Ject.Set(o, "Tall", false);
Assert.AreEqual(false, o.Tall);
Ject.Set(o, "Nice", true);
Assert.AreEqual(true, o.Nice);
}
[Test]
public void Test_Fast_Reflection_Get_Dictionary()
{
var o = new Dictionary<string, object>();
o["Age"] = 23;
o["Friends"] = 12;
o["GPA"] = 3.2;
o["Grade"] = Grade.A;
o["Name"] = "Jordan Spears";
o["Tall"] = true;
o["Nice"] = false;
var age = Ject.Get(o, "Age");
Assert.AreEqual(23, (int)age);
var friends = Ject.Get(o, "Friends");
Assert.AreEqual(12, (int)friends);
var gpa = Ject.Get(o, "GPA");
Assert.AreEqual(3.2, (double)gpa);
var grade = Ject.Get(o, "Grade");
Assert.AreEqual(Grade.A, (Grade)grade);
var name = Ject.Get(o, "Name");
Assert.AreEqual("Jordan Spears", (string)name);
var tall = Ject.Get(o, "Tall");
Assert.AreEqual(true, (bool)tall);
var nice = Ject.Get(o, "Nice");
Assert.AreEqual(false, (bool)nice);
}
[Test]
public void Test_Fast_Reflection_Set_Dictionary()
{
var o = new Dictionary<string, object>();
o["Age"] = 23;
o["Friends"] = 12;
o["GPA"] = 3.2;
o["Grade"] = Grade.A;
o["Name"] = "Jordan Spears";
o["Tall"] = true;
o["Nice"] = false;
Ject.Set(o, "Age", 25);
Assert.AreEqual(25, o["Age"]);
Ject.Set(o, "Friends", 1);
Assert.AreEqual(1, o["Friends"]);
Ject.Set(o, "GPA", 1.2);
Assert.AreEqual(1.2, o["GPA"]);
Ject.Set(o, "Grade", Grade.C);
Assert.AreEqual(Grade.C, o["Grade"]);
Ject.Set(o, "Name", "Seth Juarez");
Assert.AreEqual("Seth Juarez", o["Name"]);
Ject.Set(o, "Tall", false);
Assert.AreEqual(false, o["Tall"]);
Ject.Set(o, "Nice", true);
Assert.AreEqual(true, o["Nice"]);
}
[Test]
public void Test_Vector_Conversion_Simple_Numbers()
{
Descriptor d = new Descriptor();
d.Features = new Property[]
{
new Property { Name = "Age", Type = typeof(int) },
new Property { Name = "Height", Type=typeof(double) },
new Property { Name = "Weight", Type = typeof(decimal) },
new Property { Name = "Good", Type=typeof(bool) },
};
var o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false };
var truths = new double[] { 23, 6.21, 220, -1 };
var actual = d.Convert(o);
Assert.AreEqual(truths, actual);
}
[Test]
public void Test_Vector_DataRow_Conversion_Simple_Numbers()
{
Descriptor d = new Descriptor();
d.Features = new Property[]
{
new Property { Name = "Age", },
new Property { Name = "Height", },
new Property { Name = "Weight", },
new Property { Name = "Good", },
};
DataTable table = new DataTable("student");
var age = table.Columns.Add("Age", typeof(int));
var height = table.Columns.Add("Height", typeof(double));
var weight = table.Columns.Add("Weight", typeof(decimal));
var good = table.Columns.Add("Good", typeof(bool));
DataRow row = table.NewRow();
row[age] = 23;
row[height] = 6.21;
row[weight] = 220m;
row[good] = false;
var truths = new double[] { 23, 6.21, 220, -1 };
var actual = d.Convert(row);
Assert.AreEqual(truths, actual);
}
[Test]
public void Test_Vector_Dictionary_Conversion_Simple_Numbers()
{
Descriptor d = new Descriptor();
d.Features = new Property[]
{
new Property { Name = "Age", },
new Property { Name = "Height", },
new Property { Name = "Weight", },
new Property { Name = "Good", },
};
Dictionary<string, object> item = new Dictionary<string, object>();
item["Age"] = 23;
item["Height"] = 6.21;
item["Weight"] = 220m;
item["Good"] = false;
var truths = new double[] { 23, 6.21, 220, -1 };
var actual = d.Convert(item);
Assert.AreEqual(truths, actual);
}
[Test]
public void Test_Vector_Expando_Conversion_Simple_Numbers()
{
Descriptor d = new Descriptor();
d.Features = new Property[]
{
new Property { Name = "Age", },
new Property { Name = "Height", },
new Property { Name = "Weight", },
new Property { Name = "Good", },
};
dynamic item = new ExpandoObject();
item.Age = 23;
item.Height = 6.21;
item.Weight = 220m;
item.Good = false;
var truths = new double[] { 23, 6.21, 220, -1 };
var actual = d.Convert(item);
Assert.AreEqual(truths, actual);
}
[Test]
public void Test_Vector_Conversion_Simple_Numbers_And_Strings()
{
Descriptor d = new Descriptor();
var dictionary = StringHelpers.BuildWordDictionary(WordStrings)
.Select(k => k.Key)
.ToArray();
d.Features = new Property[]
{
new Property { Name = "Age" },
new Property { Name = "Height" },
new StringProperty { Name = "Words", Dictionary = dictionary },
new Property { Name = "Weight" },
new Property { Name = "Good" },
};
// [THE, QUICK, BROWN, FOX, #NUM#, SUPER, BEAR, UGLY]
// [ 1, 0, 1, 0, 1, 0, 0, 0]
var o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Words = "the brown 432" };
// array generated by descriptor ordering
var truths = new double[] { 23, 6.21,
/* BEGIN TEXT */
1, 0, 1, 0, 1, 0, 0, 0,
/* END TEXT */
220, -1 };
var actual = d.Convert(o);
Assert.AreEqual(truths, actual);
// offset test
Assert.AreEqual(10, d.Features[3].Start);
Assert.AreEqual(11, d.Features[4].Start);
}
[Test]
public void Test_Vector_Conversion_Simple_Numbers_And_Strings_As_Enum()
{
Descriptor d = new Descriptor();
var dictionary = StringHelpers.BuildWordDictionary(WordStrings)
.Select(k => k.Key)
.ToArray();
d.Features = new Property[]
{
new Property { Name = "Age" },
new Property { Name = "Height" },
new StringProperty { Name = "Words", Dictionary = dictionary, AsEnum = true },
new Property { Name = "Weight" },
new Property { Name = "Good" },
};
// [THE, QUICK, BROWN, FOX, #NUM#, SUPER, BEAR, UGLY]
// [ 0, 1, 2, 3, 4, 5, 6, 7]
var o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Words = "QUICK" };
// array generated by descriptor ordering
var truths = new double[] { 23, 6.21,
/* BEGIN TEXT */
1,
/* END TEXT */
220, -1 };
var actual = d.Convert(o);
Assert.AreEqual(truths, actual);
o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Words = "sUpEr" };
// array generated by descriptor ordering
truths = new double[] { 23, 6.21,
/* BEGIN TEXT */
5,
/* END TEXT */
220, -1 };
actual = d.Convert(o);
Assert.AreEqual(truths, actual);
}
[Test]
public void Test_Vector_Conversion_Simple_Numbers_And_Chars()
{
Descriptor d = new Descriptor();
var dictionary = StringHelpers.BuildCharDictionary(ShortStrings)
.Select(k => k.Key)
.ToArray();
d.Features = new Property[]
{
new Property { Name = "Age" },
new Property { Name = "Height" },
new StringProperty {
Name = "Chars",
Dictionary = dictionary,
SplitType = StringSplitType.Character
},
new Property { Name = "Weight" },
new Property { Name = "Good" },
};
// ["O", "N", "E", "#SYM#", "T", "W", "#NUM#", "H", "R"]
// [ 2, 1, 0, 1, 0, 0, 1, 0, 3]
var o = new { Age = 23, Height = 6.21d, Chars = "oon!3RrR", Weight = 220m, Good = false, };
// array generated by descriptor ordering
var truths = new double[] { 23, 6.21,
/* BEGIN CHARS */
2, 1, 0, 1, 0, 0, 1, 0, 3,
/* END CHARS */
220, -1 };
var actual = d.Convert(o);
Assert.AreEqual(truths, actual);
}
[Test]
public void Test_Vector_Conversion_Simple_Numbers_And_Chars_As_Enum()
{
Descriptor d = new Descriptor();
var dictionary = StringHelpers.BuildCharDictionary(ShortStrings)
.Select(k => k.Key)
.ToArray();
d.Features = new Property[]
{
new Property { Name = "Age" },
new Property { Name = "Height" },
new StringProperty {
Name = "Chars",
Dictionary = dictionary,
SplitType = StringSplitType.Character,
AsEnum = true
},
new Property { Name = "Weight" },
new Property { Name = "Good" },
};
// ["O", "N", "E", "#SYM#", "T", "W", "#NUM#", "H", "R"]
// [ 2, 1, 0, 1, 0, 0, 1, 0, 3]
var o = new { Age = 23, Height = 6.21d, Chars = "N", Weight = 220m, Good = false, };
// array generated by descriptor ordering
var truths = new double[] { 23, 6.21,
/* BEGIN CHARS */
1,
/* END CHARS */
220, -1 };
var actual = d.Convert(o);
Assert.AreEqual(truths, actual);
o = new { Age = 23, Height = 6.21d, Chars = "!", Weight = 220m, Good = false, };
// array generated by descriptor ordering
truths = new double[] { 23, 6.21,
/* BEGIN CHARS */
3,
/* END CHARS */
220, -1 };
actual = d.Convert(o);
Assert.AreEqual(truths, actual);
}
[Test]
public void Test_Matrix_Conversion_Simple()
{
Descriptor d = new Descriptor();
d.Features = new Property[]
{
new Property { Name = "Age" },
new Property { Name = "Height" },
new Property { Name = "Weight" },
new Property { Name = "Good" },
};
var o = new[] {
new { Age = 23, Height = 6.21d, Weight = 220m, Good = false },
new { Age = 12, Height = 4.2d, Weight = 120m, Good = true },
new { Age = 9, Height = 6.0d, Weight = 340m, Good = true },
new { Age = 87, Height = 3.7d, Weight = 79m, Good = false }
};
// array generated by descriptor ordering
// (returns IEnumerable, but should pass)
var truths = new double[][] {
new double[] { 23, 6.21, 220, -1 },
new double[] { 12, 4.2, 120, 1 },
new double[] { 9, 6.0, 340, 1 },
new double[] { 87, 3.7, 79, -1 }
};
var actual = d.Convert(o);
Assert.AreEqual(truths, actual);
}
[Test]
public void Test_Matrix_Conversion_With_Label()
{
Descriptor d = new Descriptor();
d.Features = new Property[]
{
new Property { Name = "Age" },
new Property { Name = "Height" },
new Property { Name = "Weight" },
new Property { Name = "Good" },
};
d.Label = new Property { Name = "Nice" };
var o = new[] {
new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Nice = true },
new { Age = 12, Height = 4.2d, Weight = 120m, Good = true, Nice = false },
new { Age = 9, Height = 6.0d, Weight = 340m, Good = true, Nice = true },
new { Age = 87, Height = 3.7d, Weight = 79m, Good = false, Nice = false }
};
// array generated by descriptor ordering
// (returns IEnumerable, but should pass)
var truths = new double[][] {
new double[] { 23, 6.21, 220, -1, 1 },
new double[] { 12, 4.2, 120, 1, -1 },
new double[] { 9, 6.0, 340, 1, 1 },
new double[] { 87, 3.7, 79, -1, -1 }
};
var actual = d.Convert(o);
Assert.AreEqual(truths, actual);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Cors;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Matching;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Routing
{
// These tests are intentionally in Mvc.Test so we can also test the CORS action constraint.
public class ActionConstraintMatcherPolicyTest
{
[Fact]
public async Task Apply_CanBeAmbiguous()
{
// Arrange
var actions = new ActionDescriptor[]
{
new ActionDescriptor() { DisplayName = "A1" },
new ActionDescriptor() { DisplayName = "A2" },
};
var candidateSet = CreateCandidateSet(actions);
var selector = CreateSelector(actions);
// Act
await selector.ApplyAsync(new DefaultHttpContext(), candidateSet);
// Assert
Assert.True(candidateSet.IsValidCandidate(0));
Assert.True(candidateSet.IsValidCandidate(1));
}
[Fact]
public async Task Apply_PrefersActionWithConstraints()
{
// Arrange
var actionWithConstraints = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = true, },
},
Parameters = new List<ParameterDescriptor>(),
};
var actionWithoutConstraints = new ActionDescriptor()
{
Parameters = new List<ParameterDescriptor>(),
};
var actions = new ActionDescriptor[] { actionWithConstraints, actionWithoutConstraints };
var candidateSet = CreateCandidateSet(actions);
var selector = CreateSelector(actions);
var httpContext = CreateHttpContext("POST");
// Act
await selector.ApplyAsync(httpContext, candidateSet);
// Assert
Assert.True(candidateSet.IsValidCandidate(0));
Assert.False(candidateSet.IsValidCandidate(1));
}
[Fact]
public async Task Apply_ConstraintsRejectAll()
{
// Arrange
var action1 = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = false, },
},
};
var action2 = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = false, },
},
};
var actions = new ActionDescriptor[] { action1, action2 };
var candidateSet = CreateCandidateSet(actions);
var selector = CreateSelector(actions);
var httpContext = CreateHttpContext("POST");
// Act
await selector.ApplyAsync(httpContext, candidateSet);
// Assert
Assert.False(candidateSet.IsValidCandidate(0));
Assert.False(candidateSet.IsValidCandidate(1));
}
[Fact]
public async Task Apply_ConstraintsRejectAll_DifferentStages()
{
// Arrange
var action1 = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = false, Order = 0 },
new BooleanConstraint() { Pass = true, Order = 1 },
},
};
var action2 = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = true, Order = 0 },
new BooleanConstraint() { Pass = false, Order = 1 },
},
};
var actions = new ActionDescriptor[] { action1, action2 };
var candidateSet = CreateCandidateSet(actions);
var selector = CreateSelector(actions);
var httpContext = CreateHttpContext("POST");
// Act
await selector.ApplyAsync(httpContext, candidateSet);
// Assert
Assert.False(candidateSet.IsValidCandidate(0));
Assert.False(candidateSet.IsValidCandidate(1));
}
// Due to ordering of stages, the first action will be better.
[Fact]
public async Task Apply_ConstraintsInOrder()
{
// Arrange
var best = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = true, Order = 0, },
},
};
var worst = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = true, Order = 1, },
},
};
var actions = new ActionDescriptor[] { best, worst };
var candidateSet = CreateCandidateSet(actions);
var selector = CreateSelector(actions);
var httpContext = CreateHttpContext("POST");
// Act
await selector.ApplyAsync(httpContext, candidateSet);
// Assert
Assert.True(candidateSet.IsValidCandidate(0));
Assert.False(candidateSet.IsValidCandidate(1));
}
[Fact]
public async Task Apply_SkipsOverInvalidEndpoints()
{
// Arrange
var best = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = true, Order = 0, },
},
};
var another = new ActionDescriptor();
var worst = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = true, Order = 1, },
},
};
var actions = new ActionDescriptor[] { best, another, worst };
var candidateSet = CreateCandidateSet(actions);
candidateSet.SetValidity(0, false);
candidateSet.SetValidity(1, false);
var selector = CreateSelector(actions);
var httpContext = CreateHttpContext("POST");
// Act
await selector.ApplyAsync(httpContext, candidateSet);
// Assert
Assert.False(candidateSet.IsValidCandidate(0));
Assert.False(candidateSet.IsValidCandidate(1));
Assert.True(candidateSet.IsValidCandidate(2));
}
[Fact]
public async Task Apply_IncludesNonMvcEndpoints()
{
// Arrange
var action1 = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = false, Order = 0, },
},
};
var action2 = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = false, Order = 1, },
},
};
var actions = new ActionDescriptor[] { action1, null, action2 };
var candidateSet = CreateCandidateSet(actions);
var selector = CreateSelector(actions);
var httpContext = CreateHttpContext("POST");
// Act
await selector.ApplyAsync(httpContext, candidateSet);
// Assert
Assert.False(candidateSet.IsValidCandidate(0));
Assert.True(candidateSet.IsValidCandidate(1));
Assert.False(candidateSet.IsValidCandidate(2));
}
// Due to ordering of stages, the first action will be better.
[Fact]
public async Task Apply_ConstraintsInOrder_MultipleStages()
{
// Arrange
var best = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = true, Order = 0, },
new BooleanConstraint() { Pass = true, Order = 1, },
new BooleanConstraint() { Pass = true, Order = 2, },
},
};
var worst = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = true, Order = 0, },
new BooleanConstraint() { Pass = true, Order = 1, },
new BooleanConstraint() { Pass = true, Order = 3, },
},
};
var actions = new ActionDescriptor[] { best, worst };
var candidateSet = CreateCandidateSet(actions);
var selector = CreateSelector(actions);
var httpContext = CreateHttpContext("POST");
// Act
await selector.ApplyAsync(httpContext, candidateSet);
// Assert
Assert.True(candidateSet.IsValidCandidate(0));
Assert.False(candidateSet.IsValidCandidate(1));
}
[Fact]
public async Task Apply_Fallback_ToActionWithoutConstraints()
{
// Arrange
var nomatch1 = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = true, Order = 0, },
new BooleanConstraint() { Pass = true, Order = 1, },
new BooleanConstraint() { Pass = false, Order = 2, },
},
};
var nomatch2 = new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint() { Pass = true, Order = 0, },
new BooleanConstraint() { Pass = true, Order = 1, },
new BooleanConstraint() { Pass = false, Order = 3, },
},
};
var best = new ActionDescriptor();
var actions = new ActionDescriptor[] { best, nomatch1, nomatch2 };
var candidateSet = CreateCandidateSet(actions);
var selector = CreateSelector(actions);
var httpContext = CreateHttpContext("POST");
// Act
await selector.ApplyAsync(httpContext, candidateSet);
// Assert
Assert.True(candidateSet.IsValidCandidate(0));
Assert.False(candidateSet.IsValidCandidate(1));
Assert.False(candidateSet.IsValidCandidate(2));
}
[Fact]
public async Task DataTokens_RoundTrip()
{
// Arrange
var actions = new ActionDescriptor[]
{
new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new ConstraintWithTokens(),
},
EndpointMetadata = new List<object>()
{
new DataTokensMetadata(new Dictionary<string, object>
{
["DataTokens"] = true
})
}
},
};
var endpoints = actions.Select(CreateEndpoint).ToArray();
var selector = CreateSelector(actions);
var httpContext = CreateHttpContext("POST");
// Act
var candidateSet = CreateCandidateSet(actions);
await selector.ApplyAsync(httpContext, candidateSet);
// Assert
Assert.True(candidateSet.IsValidCandidate(0));
}
[Fact]
public void AppliesToEndpoints_IgnoresIgnorableConstraints()
{
// Arrange
var actions = new ActionDescriptor[]
{
new ActionDescriptor()
{
},
new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new HttpMethodActionConstraint(new[]{ "GET", }),
},
},
new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new ConsumesAttribute("text/json"),
},
},
};
var endpoints = actions.Select(CreateEndpoint).ToArray();
var selector = CreateSelector(actions);
// Act
var result = selector.AppliesToEndpoints(endpoints);
// Assert
Assert.False(result);
}
[Fact]
public void ShouldRunActionConstraints_RunsForArbitraryActionConstraint()
{
// Arrange
var actions = new ActionDescriptor[]
{
new ActionDescriptor()
{
},
new ActionDescriptor()
{
ActionConstraints = new List<IActionConstraintMetadata>()
{
new BooleanConstraint(),
},
},
};
var endpoints = actions.Select(CreateEndpoint).ToArray();
var selector = CreateSelector(actions);
// Act
var result = selector.AppliesToEndpoints(endpoints);
// Assert
Assert.True(result);
}
private ActionConstraintMatcherPolicy CreateSelector(ActionDescriptor[] actions)
{
// We need to actually provide some actions with some action constraints metadata
// or else the policy will No-op.
var actionDescriptorProvider = new Mock<IActionDescriptorProvider>();
actionDescriptorProvider
.Setup(a => a.OnProvidersExecuted(It.IsAny<ActionDescriptorProviderContext>()))
.Callback<ActionDescriptorProviderContext>(c =>
{
for (var i = 0; i < actions.Length; i++)
{
c.Results.Add(actions[i]);
}
});
var actionDescriptorCollectionProvider = new DefaultActionDescriptorCollectionProvider(
new IActionDescriptorProvider[] { actionDescriptorProvider.Object, },
Enumerable.Empty<IActionDescriptorChangeProvider>());
var cache = new ActionConstraintCache(actionDescriptorCollectionProvider, new[]
{
new DefaultActionConstraintProvider(),
});
return new ActionConstraintMatcherPolicy(cache);
}
private static HttpContext CreateHttpContext(string httpMethod)
{
var httpContext = new DefaultHttpContext();
httpContext.Request.Method = httpMethod;
return httpContext;
}
private static Endpoint CreateEndpoint(ActionDescriptor action)
{
var metadata = new List<object>() { action, };
if (action?.EndpointMetadata != null)
{
metadata.AddRange(action.EndpointMetadata);
}
return new Endpoint(
(context) => Task.CompletedTask,
new EndpointMetadataCollection(metadata),
$"test: {action?.DisplayName}");
}
private static CandidateSet CreateCandidateSet(ActionDescriptor[] actions)
{
var values = new RouteValueDictionary[actions.Length];
for (var i = 0; i < actions.Length; i++)
{
values[i] = new RouteValueDictionary();
}
var candidateSet = new CandidateSet(
actions.Select(CreateEndpoint).ToArray(),
values,
new int[actions.Length]);
return candidateSet;
}
private class ConstraintWithTokens : IActionConstraint
{
public int Order => 1;
public bool Accept(ActionConstraintContext context)
{
return context.RouteContext.RouteData.DataTokens.ContainsKey("DataTokens");
}
}
private class BooleanConstraint : IActionConstraint
{
public bool Pass { get; set; }
public int Order { get; set; }
public bool Accept(ActionConstraintContext context)
{
return Pass;
}
}
}
}
| |
using System ;
using System.IO ;
using System.Collections ;
using System.Collections.Generic ;
using System.Threading ;
using System.Xml ;
using System.Xml.Xsl ;
using System.Xml.XPath ;
using System.Configuration ;
using System.Diagnostics ;
using System.Reflection ;
using System.Text ;
using System.Security.Cryptography ;
namespace alby.core.crypto
{
public class RsaEncryption
{
//
//
//
protected const int DEFAULT_KEY_SIZE = 1024 ; // 2048
//
//
//
protected RSACryptoServiceProvider _rsa ;
//
//
//
public string PublicKey
{
get
{
return this._rsa.ToXmlString( false ) ;
}
set
{
this._rsa.FromXmlString( value ) ;
}
}
//
//
//
public string PrivatePublicKey
{
get
{
return this._rsa.ToXmlString( true ) ;
}
set
{
this._rsa.FromXmlString( value ) ;
}
}
//
//
//
public RsaEncryption() : this( DEFAULT_KEY_SIZE, "" )
{
}
//
//
//
public RsaEncryption( int keySize ) : this( keySize, "" )
{
}
//
//
//
public RsaEncryption( string publicKey ) : this( DEFAULT_KEY_SIZE, publicKey )
{
}
//
//
//
public RsaEncryption( int keySize, string publicKey )
{
this._rsa = new RSACryptoServiceProvider( keySize ) ;
if ( publicKey != null && publicKey.Length > 0 )
this._rsa.FromXmlString( publicKey ) ;
}
//
//
//
public RsaEncryption GetEncryptor( string receiverPublicKey )
{
return new RsaEncryption( this._rsa.KeySize, receiverPublicKey ) ;
}
//
// encrpty with the message receiver's public key - only he can decrypt it
//
public byte[] Encrypt( byte[] bytes )
{
if ( bytes == null ) bytes = new byte[0] ;
try
{
return this._rsa.Encrypt( bytes, false ) ;
}
catch( Exception ex )
{
throw new CryptographicException( "RSA encryption error", ex ) ;
}
}
//
// decrypt with my own public / private key pair
//
public byte[] Decrypt( byte[] bytes )
{
if ( bytes == null ) bytes = new byte[0] ;
try
{
byte[] result = this._rsa.Decrypt( bytes, false ) ;
if ( result == null ) throw new Exception() ;
return result ;
}
catch ( Exception ex )
{
throw new CryptographicException( "RSA decryption error", ex ) ;
}
}
//
//
//
public byte[] Encrypt( string str )
{
if ( str == null ) str = "" ;
return this.Encrypt( System.Text.Encoding.Unicode.GetBytes( str ) ) ;
}
public byte[] Encrypt( string str, string receiverPublicKey )
{
if ( str == null ) str = "" ;
RsaEncryption rsa = new RsaEncryption(this._rsa.KeySize, receiverPublicKey);
return rsa.Encrypt( System.Text.Encoding.Unicode.GetBytes( str ) ) ;
}
public byte[] Encrypt( byte[] bytes, string receiverPublicKey )
{
if (bytes == null) bytes = new byte[0];
RsaEncryption rsa = new RsaEncryption(this._rsa.KeySize, receiverPublicKey);
return rsa.Encrypt( bytes );
}
//
//
//
public override string ToString()
{
string xml = this._rsa.ToXmlString( true ) ;
string str = "keysize: " + this._rsa.KeySize +
"\nkey: " + xml ;
return str ;
}
////
//// unit testing follows
////
//public static void Main( string[] args )
//{
// //Test( "" ) ;
// Test( "<hello yogi>" ) ;
// //Test( "the fat cat sat on the mat on the hat fancy that silly cat" ) ; // about 58 chars max for RSA = 58*2*8 = 928 bits
//}
////
////
////
//protected static void Test( string str )
//{
// Base64String base64 = new Base64String() ;
// RsaEncryption alice = new RsaEncryption() ;
// RsaEncryption bob = new RsaEncryption() ;
// RsaEncryption charlie = new RsaEncryption() ;
// Console.WriteLine( "\nalice public key:\n" + alice.PublicKey ) ;
// Console.WriteLine( "\nalice whole key:\n" + alice.ToString() + "\n" ) ;
// byte[] bytesEnc ;
// byte[] bytesDec ;
// string stringOut ;
// string strReply = str + ", Good thanks." ;
// Console.WriteLine( "---------------------------------- pass 1 ---------------------------------------------" ) ;
// // alice sends a message to bob
// Console.WriteLine( "1 alice @@@" + str + "@@@ (" + str.Length + " chars)" ) ;
// RsaEncryption encryptorAlice = alice.GetEncryptor( bob.PublicKey ) ;
// bytesEnc = encryptorAlice.Encrypt( str ) ; //, bob.PublicKey ) ;
// Console.WriteLine( "1 alice encoded bytes: " + base64.BytesToString( bytesEnc ) + " (" + bytesEnc.Length + " bytes)" ) ;
// // bob has to decrypt it
// bytesDec = bob.Decrypt( bytesEnc ) ;
// Console.WriteLine( "1 bob decryped bytes: " + base64.BytesToString( bytesDec ) ) ;
// stringOut = System.Text.Encoding.Unicode.GetString( bytesDec ) ;
// Console.WriteLine( "1 bob @@@" + stringOut + "@@@" ) ;
// // charlie tries to decrypt it - should be error
// try
// {
// bytesDec = charlie.Decrypt( bytesEnc ) ;
// Console.WriteLine( "1 charlie decryped bytes: " + base64.BytesToString( bytesDec ) ) ;
// stringOut = System.Text.Encoding.Unicode.GetString( bytesDec ) ;
// Console.WriteLine( "1 charlie @@@" + stringOut + "@@@" ) ;
// }
// catch( Exception ex )
// {
// Console.WriteLine( "1 charlie: " + ex.ToString() ) ;
// }
// // bob sends reply to alice
// Console.WriteLine( "1 bob @@@" + strReply + "@@@ (" + strReply.Length + " chars)" ) ;
// RsaEncryption encryptorBob = bob.GetEncryptor( alice.PublicKey ) ;
// bytesEnc = encryptorBob.Encrypt( strReply ) ;//, alice.PublicKey ) ;
// Console.WriteLine( "1 bob encoded bytes: " + base64.BytesToString( bytesEnc ) + " (" + bytesEnc.Length + " bytes)" ) ;
// // alice has to decrypt it
// bytesDec = alice.Decrypt( bytesEnc ) ;
// Console.WriteLine( "1 alice decryped bytes: " + base64.BytesToString( bytesDec ) ) ;
// stringOut = System.Text.Encoding.Unicode.GetString( bytesDec ) ;
// Console.WriteLine( "1 alice @@@" + stringOut + "@@@" ) ;
// Console.WriteLine( "---------------------------------- pass 2 ---------------------------------------------" ) ;
// RsaEncryption alice2 = new RsaEncryption( alice.PrivatePublicKey ) ;
// RsaEncryption bob2 = new RsaEncryption( bob.PrivatePublicKey ) ;
// // alice sends a message to bob
// Console.WriteLine( "2 alice @@@" + str + "@@@" ) ;
// RsaEncryption encryptorAlice2 = alice2.GetEncryptor( bob.PublicKey ) ;
// bytesEnc = encryptorAlice2.Encrypt( str ) ;//, bob.PublicKey ) ;
// Console.WriteLine( "2 alice encoded bytes: " + base64.BytesToString( bytesEnc ) ) ;
// // bob has to decrypt it
// bytesDec = bob2.Decrypt( bytesEnc ) ;
// Console.WriteLine( "2 bob decryped bytes: " + base64.BytesToString( bytesDec ) ) ;
// stringOut = System.Text.Encoding.Unicode.GetString( bytesDec ) ;
// Console.WriteLine( "2 bob @@@" + stringOut + "@@@" ) ;
// // charlie tries to decrypt it - should be error
// try
// {
// bytesDec = charlie.Decrypt( bytesEnc ) ;
// Console.WriteLine( "2 charlie decryped bytes: " + base64.BytesToString( bytesDec ) ) ;
// stringOut = System.Text.Encoding.Unicode.GetString( bytesDec ) ;
// Console.WriteLine( "2 charlie @@@" + stringOut + "@@@" ) ;
// }
// catch( Exception ex )
// {
// Console.WriteLine( "2 charlie: " + ex.ToString() ) ;
// }
// // bob sends reply to alice
// Console.WriteLine( "2 bob @@@" + strReply + "@@@ (" + strReply.Length + " chars)" ) ;
// RsaEncryption encryptorBob2 = bob2.GetEncryptor( alice.PublicKey ) ;
// bytesEnc = encryptorBob2.Encrypt( strReply ) ;//, alice.PublicKey ) ;
// Console.WriteLine( "2 bob encoded bytes: " + base64.BytesToString( bytesEnc ) + " (" + bytesEnc.Length + " bytes)" ) ;
// // alice has to decrypt it
// bytesDec = alice2.Decrypt( bytesEnc ) ;
// Console.WriteLine( "2 alice decryped bytes: " + base64.BytesToString( bytesDec ) ) ;
// stringOut = System.Text.Encoding.Unicode.GetString( bytesDec ) ;
// Console.WriteLine( "2 alice @@@" + stringOut + "@@@" ) ;
//}
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Collections.Generic;
using MetroFramework.Drawing.Html.Adapters;
using MetroFramework.Drawing.Html.Adapters.Entities;
using MetroFramework.Drawing.Html.Core.Utils;
namespace MetroFramework.Drawing.Html.Core.Dom
{
/// <summary>
/// Helps on CSS Layout.
/// </summary>
internal static class CssLayoutEngine
{
/// <summary>
/// Measure image box size by the width\height set on the box and the actual rendered image size.<br/>
/// If no image exists for the box error icon will be set.
/// </summary>
/// <param name="imageWord">the image word to measure</param>
public static void MeasureImageSize(CssRectImage imageWord)
{
ArgChecker.AssertArgNotNull(imageWord, "imageWord");
ArgChecker.AssertArgNotNull(imageWord.OwnerBox, "imageWord.OwnerBox");
var width = new CssLength(imageWord.OwnerBox.Width);
var height = new CssLength(imageWord.OwnerBox.Height);
bool hasImageTagWidth = width.Number > 0 && width.Unit == CssUnit.Pixels;
bool hasImageTagHeight = height.Number > 0 && height.Unit == CssUnit.Pixels;
bool scaleImageHeight = false;
if (hasImageTagWidth)
{
imageWord.Width = width.Number;
}
else if (width.Number > 0 && width.IsPercentage)
{
imageWord.Width = width.Number * imageWord.OwnerBox.ContainingBlock.Size.Width;
scaleImageHeight = true;
}
else if (imageWord.Image != null)
{
imageWord.Width = imageWord.ImageRectangle == RRect.Empty ? imageWord.Image.Width : imageWord.ImageRectangle.Width;
}
else
{
imageWord.Width = hasImageTagHeight ? height.Number / 1.14f : 20;
}
var maxWidth = new CssLength(imageWord.OwnerBox.MaxWidth);
if (maxWidth.Number > 0)
{
double maxWidthVal = -1;
if (maxWidth.Unit == CssUnit.Pixels)
{
maxWidthVal = maxWidth.Number;
}
else if (maxWidth.IsPercentage)
{
maxWidthVal = maxWidth.Number * imageWord.OwnerBox.ContainingBlock.Size.Width;
}
if (maxWidthVal > -1 && imageWord.Width > maxWidthVal)
{
imageWord.Width = maxWidthVal;
scaleImageHeight = !hasImageTagHeight;
}
}
if (hasImageTagHeight)
{
imageWord.Height = height.Number;
}
else if (imageWord.Image != null)
{
imageWord.Height = imageWord.ImageRectangle == RRect.Empty ? imageWord.Image.Height : imageWord.ImageRectangle.Height;
}
else
{
imageWord.Height = imageWord.Width > 0 ? imageWord.Width * 1.14f : 22.8f;
}
if (imageWord.Image != null)
{
// If only the width was set in the html tag, ratio the height.
if ((hasImageTagWidth && !hasImageTagHeight) || scaleImageHeight)
{
// Divide the given tag width with the actual image width, to get the ratio.
double ratio = imageWord.Width / imageWord.Image.Width;
imageWord.Height = imageWord.Image.Height * ratio;
}
// If only the height was set in the html tag, ratio the width.
else if (hasImageTagHeight && !hasImageTagWidth)
{
// Divide the given tag height with the actual image height, to get the ratio.
double ratio = imageWord.Height / imageWord.Image.Height;
imageWord.Width = imageWord.Image.Width * ratio;
}
}
imageWord.Height += imageWord.OwnerBox.ActualBorderBottomWidth + imageWord.OwnerBox.ActualBorderTopWidth + imageWord.OwnerBox.ActualPaddingTop + imageWord.OwnerBox.ActualPaddingBottom;
}
/// <summary>
/// Creates line boxes for the specified blockbox
/// </summary>
/// <param name="g"></param>
/// <param name="blockBox"></param>
public static void CreateLineBoxes(RGraphics g, CssBox blockBox)
{
ArgChecker.AssertArgNotNull(g, "g");
ArgChecker.AssertArgNotNull(blockBox, "blockBox");
blockBox.LineBoxes.Clear();
double limitRight = blockBox.ActualRight - blockBox.ActualPaddingRight - blockBox.ActualBorderRightWidth;
//Get the start x and y of the blockBox
double startx = blockBox.Location.X + blockBox.ActualPaddingLeft - 0 + blockBox.ActualBorderLeftWidth;
double starty = blockBox.Location.Y + blockBox.ActualPaddingTop - 0 + blockBox.ActualBorderTopWidth;
double curx = startx + blockBox.ActualTextIndent;
double cury = starty;
//Reminds the maximum bottom reached
double maxRight = startx;
double maxBottom = starty;
//First line box
CssLineBox line = new CssLineBox(blockBox);
//Flow words and boxes
FlowBox(g, blockBox, blockBox, limitRight, 0, startx, ref line, ref curx, ref cury, ref maxRight, ref maxBottom);
// if width is not restricted we need to lower it to the actual width
if (blockBox.ActualRight >= 90999)
{
blockBox.ActualRight = maxRight + blockBox.ActualPaddingRight + blockBox.ActualBorderRightWidth;
}
//Gets the rectangles for each line-box
foreach (var linebox in blockBox.LineBoxes)
{
ApplyHorizontalAlignment(g, linebox);
ApplyRightToLeft(blockBox, linebox);
BubbleRectangles(blockBox, linebox);
ApplyVerticalAlignment(g, linebox);
linebox.AssignRectanglesToBoxes();
}
blockBox.ActualBottom = maxBottom + blockBox.ActualPaddingBottom + blockBox.ActualBorderBottomWidth;
// handle limiting block height when overflow is hidden
if (blockBox.Height != null && blockBox.Height != CssConstants.Auto && blockBox.Overflow == CssConstants.Hidden && blockBox.ActualBottom - blockBox.Location.Y > blockBox.ActualHeight)
{
blockBox.ActualBottom = blockBox.Location.Y + blockBox.ActualHeight;
}
}
/// <summary>
/// Applies special vertical alignment for table-cells
/// </summary>
/// <param name="g"></param>
/// <param name="cell"></param>
public static void ApplyCellVerticalAlignment(RGraphics g, CssBox cell)
{
ArgChecker.AssertArgNotNull(g, "g");
ArgChecker.AssertArgNotNull(cell, "cell");
if (cell.VerticalAlign == CssConstants.Top || cell.VerticalAlign == CssConstants.Baseline)
return;
double cellbot = cell.ClientBottom;
double bottom = cell.GetMaximumBottom(cell, 0f);
double dist = 0f;
if (cell.VerticalAlign == CssConstants.Bottom)
{
dist = cellbot - bottom;
}
else if (cell.VerticalAlign == CssConstants.Middle)
{
dist = (cellbot - bottom) / 2;
}
foreach (CssBox b in cell.Boxes)
{
b.OffsetTop(dist);
}
//float top = cell.ClientTop;
//float bottom = cell.ClientBottom;
//bool middle = cell.VerticalAlign == CssConstants.Middle;
//foreach (LineBox line in cell.LineBoxes)
//{
// for (int i = 0; i < line.RelatedBoxes.Count; i++)
// {
// double diff = bottom - line.RelatedBoxes[i].Rectangles[line].Bottom;
// if (middle) diff /= 2f;
// RectangleF r = line.RelatedBoxes[i].Rectangles[line];
// line.RelatedBoxes[i].Rectangles[line] = new RectangleF(r.X, r.Y + diff, r.Width, r.Height);
// }
// foreach (BoxWord word in line.Words)
// {
// double gap = word.Top - top;
// word.Top = bottom - gap - word.Height;
// }
//}
}
#region Private methods
/// <summary>
/// Recursively flows the content of the box using the inline model
/// </summary>
/// <param name="g">Device Info</param>
/// <param name="blockbox">Blockbox that contains the text flow</param>
/// <param name="box">Current box to flow its content</param>
/// <param name="limitRight">Maximum reached right</param>
/// <param name="linespacing">Space to use between rows of text</param>
/// <param name="startx">x starting coordinate for when breaking lines of text</param>
/// <param name="line">Current linebox being used</param>
/// <param name="curx">Current x coordinate that will be the left of the next word</param>
/// <param name="cury">Current y coordinate that will be the top of the next word</param>
/// <param name="maxRight">Maximum right reached so far</param>
/// <param name="maxbottom">Maximum bottom reached so far</param>
private static void FlowBox(RGraphics g, CssBox blockbox, CssBox box, double limitRight, double linespacing, double startx, ref CssLineBox line, ref double curx, ref double cury, ref double maxRight, ref double maxbottom)
{
var startX = curx;
var startY = cury;
box.FirstHostingLineBox = line;
var localCurx = curx;
var localMaxRight = maxRight;
var localmaxbottom = maxbottom;
foreach (CssBox b in box.Boxes)
{
double leftspacing = b.Position != CssConstants.Absolute ? b.ActualMarginLeft + b.ActualBorderLeftWidth + b.ActualPaddingLeft : 0;
double rightspacing = b.Position != CssConstants.Absolute ? b.ActualMarginRight + b.ActualBorderRightWidth + b.ActualPaddingRight : 0;
b.RectanglesReset();
b.MeasureWordsSize(g);
curx += leftspacing;
if (b.Words.Count > 0)
{
bool wrapNoWrapBox = false;
if (b.WhiteSpace == CssConstants.NoWrap && curx > startx)
{
var boxRight = curx;
foreach (var word in b.Words)
boxRight += word.FullWidth;
if (boxRight > limitRight)
wrapNoWrapBox = true;
}
if (DomUtils.IsBoxHasWhitespace(b))
curx += box.ActualWordSpacing;
foreach (var word in b.Words)
{
if (maxbottom - cury < box.ActualLineHeight)
maxbottom += box.ActualLineHeight - (maxbottom - cury);
if ((b.WhiteSpace != CssConstants.NoWrap && b.WhiteSpace != CssConstants.Pre && curx + word.Width + rightspacing > limitRight
&& (b.WhiteSpace != CssConstants.PreWrap || !word.IsSpaces))
|| word.IsLineBreak || wrapNoWrapBox)
{
wrapNoWrapBox = false;
curx = startx;
// handle if line is wrapped for the first text element where parent has left margin\padding
if (b == box.Boxes[0] && !word.IsLineBreak && (word == b.Words[0] || (box.ParentBox != null && box.ParentBox.IsBlock)))
curx += box.ActualMarginLeft + box.ActualBorderLeftWidth + box.ActualPaddingLeft;
cury = maxbottom + linespacing;
line = new CssLineBox(blockbox);
if (word.IsImage || word.Equals(b.FirstWord))
{
curx += leftspacing;
}
}
line.ReportExistanceOf(word);
word.Left = curx;
word.Top = cury;
curx = word.Left + word.FullWidth;
maxRight = Math.Max(maxRight, word.Right);
maxbottom = Math.Max(maxbottom, word.Bottom);
if (b.Position == CssConstants.Absolute)
{
word.Left += box.ActualMarginLeft;
word.Top += box.ActualMarginTop;
}
}
}
else
{
FlowBox(g, blockbox, b, limitRight, linespacing, startx, ref line, ref curx, ref cury, ref maxRight, ref maxbottom);
}
curx += rightspacing;
}
// handle height setting
if (maxbottom - startY < box.ActualHeight)
{
maxbottom += box.ActualHeight - (maxbottom - startY);
}
// handle width setting
if (box.IsInline && 0 <= curx - startX && curx - startX < box.ActualWidth)
{
// hack for actual width handling
curx += box.ActualWidth - (curx - startX);
line.Rectangles.Add(box, new RRect(startX, startY, box.ActualWidth, box.ActualHeight));
}
// handle box that is only a whitespace
if (box.Text != null && box.Text.IsWhitespace() && !box.IsImage && box.IsInline && box.Boxes.Count == 0 && box.Words.Count == 0)
{
curx += box.ActualWordSpacing;
}
// hack to support specific absolute position elements
if (box.Position == CssConstants.Absolute)
{
curx = localCurx;
maxRight = localMaxRight;
maxbottom = localmaxbottom;
AdjustAbsolutePosition(box, 0, 0);
}
box.LastHostingLineBox = line;
}
/// <summary>
/// Adjust the position of absolute elements by letf and top margins.
/// </summary>
private static void AdjustAbsolutePosition(CssBox box, double left, double top)
{
left += box.ActualMarginLeft;
top += box.ActualMarginTop;
if (box.Words.Count > 0)
{
foreach (var word in box.Words)
{
word.Left += left;
word.Top += top;
}
}
else
{
foreach (var b in box.Boxes)
AdjustAbsolutePosition(b, left, top);
}
}
/// <summary>
/// Recursively creates the rectangles of the blockBox, by bubbling from deep to outside of the boxes
/// in the rectangle structure
/// </summary>
private static void BubbleRectangles(CssBox box, CssLineBox line)
{
if (box.Words.Count > 0)
{
double x = Single.MaxValue, y = Single.MaxValue, r = Single.MinValue, b = Single.MinValue;
List<CssRect> words = line.WordsOf(box);
if (words.Count > 0)
{
foreach (CssRect word in words)
{
// handle if line is wrapped for the first text element where parent has left margin\padding
var left = word.Left;
if (box == box.ParentBox.Boxes[0] && word == box.Words[0] && word == line.Words[0] && line != line.OwnerBox.LineBoxes[0] && !word.IsLineBreak)
left -= box.ParentBox.ActualMarginLeft + box.ParentBox.ActualBorderLeftWidth + box.ParentBox.ActualPaddingLeft;
x = Math.Min(x, left);
r = Math.Max(r, word.Right);
y = Math.Min(y, word.Top);
b = Math.Max(b, word.Bottom);
}
line.UpdateRectangle(box, x, y, r, b);
}
}
else
{
foreach (CssBox b in box.Boxes)
{
BubbleRectangles(b, line);
}
}
}
/// <summary>
/// Applies vertical and horizontal alignment to words in lineboxes
/// </summary>
/// <param name="g"></param>
/// <param name="lineBox"></param>
private static void ApplyHorizontalAlignment(RGraphics g, CssLineBox lineBox)
{
switch (lineBox.OwnerBox.TextAlign)
{
case CssConstants.Right:
ApplyRightAlignment(g, lineBox);
break;
case CssConstants.Center:
ApplyCenterAlignment(g, lineBox);
break;
case CssConstants.Justify:
ApplyJustifyAlignment(g, lineBox);
break;
default:
ApplyLeftAlignment(g, lineBox);
break;
}
}
/// <summary>
/// Applies right to left direction to words
/// </summary>
/// <param name="blockBox"></param>
/// <param name="lineBox"></param>
private static void ApplyRightToLeft(CssBox blockBox, CssLineBox lineBox)
{
if (blockBox.Direction == CssConstants.Rtl)
{
ApplyRightToLeftOnLine(lineBox);
}
else
{
foreach (var box in lineBox.RelatedBoxes)
{
if (box.Direction == CssConstants.Rtl)
{
ApplyRightToLeftOnSingleBox(lineBox, box);
}
}
}
}
/// <summary>
/// Applies RTL direction to all the words on the line.
/// </summary>
/// <param name="line">the line to apply RTL to</param>
private static void ApplyRightToLeftOnLine(CssLineBox line)
{
if (line.Words.Count > 0)
{
double left = line.Words[0].Left;
double right = line.Words[line.Words.Count - 1].Right;
foreach (CssRect word in line.Words)
{
double diff = word.Left - left;
double wright = right - diff;
word.Left = wright - word.Width;
}
}
}
/// <summary>
/// Applies RTL direction to specific box words on the line.
/// </summary>
/// <param name="lineBox"></param>
/// <param name="box"></param>
private static void ApplyRightToLeftOnSingleBox(CssLineBox lineBox, CssBox box)
{
int leftWordIdx = -1;
int rightWordIdx = -1;
for (int i = 0; i < lineBox.Words.Count; i++)
{
if (lineBox.Words[i].OwnerBox == box)
{
if (leftWordIdx < 0)
leftWordIdx = i;
rightWordIdx = i;
}
}
if (leftWordIdx > -1 && rightWordIdx > leftWordIdx)
{
double left = lineBox.Words[leftWordIdx].Left;
double right = lineBox.Words[rightWordIdx].Right;
for (int i = leftWordIdx; i <= rightWordIdx; i++)
{
double diff = lineBox.Words[i].Left - left;
double wright = right - diff;
lineBox.Words[i].Left = wright - lineBox.Words[i].Width;
}
}
}
/// <summary>
/// Applies vertical alignment to the linebox
/// </summary>
/// <param name="g"></param>
/// <param name="lineBox"></param>
private static void ApplyVerticalAlignment(RGraphics g, CssLineBox lineBox)
{
double baseline = Single.MinValue;
foreach (var box in lineBox.Rectangles.Keys)
{
baseline = Math.Max(baseline, lineBox.Rectangles[box].Top);
}
var boxes = new List<CssBox>(lineBox.Rectangles.Keys);
foreach (CssBox box in boxes)
{
//Important notes on http://www.w3.org/TR/CSS21/tables.html#height-layout
switch (box.VerticalAlign)
{
case CssConstants.Sub:
lineBox.SetBaseLine(g, box, baseline + lineBox.Rectangles[box].Height * .5f);
break;
case CssConstants.Super:
lineBox.SetBaseLine(g, box, baseline - lineBox.Rectangles[box].Height * .2f);
break;
case CssConstants.TextTop:
break;
case CssConstants.TextBottom:
break;
case CssConstants.Top:
break;
case CssConstants.Bottom:
break;
case CssConstants.Middle:
break;
default:
//case: baseline
lineBox.SetBaseLine(g, box, baseline);
break;
}
}
}
/// <summary>
/// Applies centered alignment to the text on the linebox
/// </summary>
/// <param name="g"></param>
/// <param name="lineBox"></param>
private static void ApplyJustifyAlignment(RGraphics g, CssLineBox lineBox)
{
if (lineBox.Equals(lineBox.OwnerBox.LineBoxes[lineBox.OwnerBox.LineBoxes.Count - 1]))
return;
double indent = lineBox.Equals(lineBox.OwnerBox.LineBoxes[0]) ? lineBox.OwnerBox.ActualTextIndent : 0f;
double textSum = 0f;
double words = 0f;
double availWidth = lineBox.OwnerBox.ClientRectangle.Width - indent;
// Gather text sum
foreach (CssRect w in lineBox.Words)
{
textSum += w.Width;
words += 1f;
}
if (words <= 0f)
return; //Avoid Zero division
double spacing = (availWidth - textSum) / words; //Spacing that will be used
double curx = lineBox.OwnerBox.ClientLeft + indent;
foreach (CssRect word in lineBox.Words)
{
word.Left = curx;
curx = word.Right + spacing;
if (word == lineBox.Words[lineBox.Words.Count - 1])
{
word.Left = lineBox.OwnerBox.ClientRight - word.Width;
}
}
}
/// <summary>
/// Applies centered alignment to the text on the linebox
/// </summary>
/// <param name="g"></param>
/// <param name="line"></param>
private static void ApplyCenterAlignment(RGraphics g, CssLineBox line)
{
if (line.Words.Count == 0)
return;
CssRect lastWord = line.Words[line.Words.Count - 1];
double right = line.OwnerBox.ActualRight - line.OwnerBox.ActualPaddingRight - line.OwnerBox.ActualBorderRightWidth;
double diff = right - lastWord.Right - lastWord.OwnerBox.ActualBorderRightWidth - lastWord.OwnerBox.ActualPaddingRight;
diff /= 2;
if (diff > 0)
{
foreach (CssRect word in line.Words)
{
word.Left += diff;
}
if (line.Rectangles.Count > 0)
{
foreach (CssBox b in ToList(line.Rectangles.Keys))
{
RRect r = line.Rectangles[b];
line.Rectangles[b] = new RRect(r.X + diff, r.Y, r.Width, r.Height);
}
}
}
}
/// <summary>
/// Applies right alignment to the text on the linebox
/// </summary>
/// <param name="g"></param>
/// <param name="line"></param>
private static void ApplyRightAlignment(RGraphics g, CssLineBox line)
{
if (line.Words.Count == 0)
return;
CssRect lastWord = line.Words[line.Words.Count - 1];
double right = line.OwnerBox.ActualRight - line.OwnerBox.ActualPaddingRight - line.OwnerBox.ActualBorderRightWidth;
double diff = right - lastWord.Right - lastWord.OwnerBox.ActualBorderRightWidth - lastWord.OwnerBox.ActualPaddingRight;
if (diff > 0)
{
foreach (CssRect word in line.Words)
{
word.Left += diff;
}
if (line.Rectangles.Count > 0)
{
foreach (CssBox b in ToList(line.Rectangles.Keys))
{
RRect r = line.Rectangles[b];
line.Rectangles[b] = new RRect(r.X + diff, r.Y, r.Width, r.Height);
}
}
}
}
/// <summary>
/// Simplest alignment, just arrange words.
/// </summary>
/// <param name="g"></param>
/// <param name="line"></param>
private static void ApplyLeftAlignment(RGraphics g, CssLineBox line)
{
//No alignment needed.
//foreach (LineBoxRectangle r in line.Rectangles)
//{
// double curx = r.Left + (r.Index == 0 ? r.OwnerBox.ActualPaddingLeft + r.OwnerBox.ActualBorderLeftWidth / 2 : 0);
// if (r.SpaceBefore) curx += r.OwnerBox.ActualWordSpacing;
// foreach (BoxWord word in r.Words)
// {
// word.Left = curx;
// word.Top = r.Top;// +r.OwnerBox.ActualPaddingTop + r.OwnerBox.ActualBorderTopWidth / 2;
// curx = word.Right + r.OwnerBox.ActualWordSpacing;
// }
//}
}
/// <summary>
/// todo: optimizate, not creating a list each time
/// </summary>
private static List<T> ToList<T>(IEnumerable<T> collection)
{
List<T> result = new List<T>();
foreach (T item in collection)
{
result.Add(item);
}
return result;
}
#endregion
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
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 names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.IO;
using System.Security.Permissions;
namespace MSNPSharp.Core
{
using MSNPSharp;
/// <summary>
/// A multi-user stream.
/// </summary>
public class PersistentStream : Stream
{
/// <summary>
/// </summary>
private Stream innerStream = null;
#region Stream overrides
/// <summary>
/// </summary>
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return innerStream.BeginRead(buffer, offset, count, callback, state);
}
/// <summary>
/// </summary>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return innerStream.BeginWrite(buffer, offset, count, callback, state);
}
/// <summary>
/// </summary>
public override bool CanRead
{
get
{
return innerStream.CanRead;
}
}
/// <summary>
/// </summary>
public override bool CanSeek
{
get
{
return innerStream.CanSeek;
}
}
/// <summary>
/// </summary>
public override bool CanWrite
{
get
{
return innerStream.CanWrite;
}
}
/// <summary>
/// </summary>
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
{
return innerStream.CreateObjRef(requestedType);
}
/// <summary>
/// </summary>
public override int EndRead(IAsyncResult asyncResult)
{
return innerStream.EndRead(asyncResult);
}
/// <summary>
/// </summary>
public override void EndWrite(IAsyncResult asyncResult)
{
innerStream.EndWrite(asyncResult);
}
/// <summary>
/// </summary>
public override bool Equals(object obj)
{
return innerStream.Equals(obj);
}
/// <summary>
/// </summary>
public override void Flush()
{
innerStream.Flush();
}
/// <summary>
/// </summary>
public override int GetHashCode()
{
return innerStream.GetHashCode();
}
/// <summary>
/// </summary>
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return innerStream.InitializeLifetimeService();
}
/// <summary>
/// </summary>
public override long Length
{
get
{
return innerStream.Length;
}
}
/// <summary>
/// </summary>
public override long Position
{
get
{
return innerStream.Position;
}
set
{
innerStream.Position = value;
}
}
/// <summary>
/// </summary>
public override int Read(byte[] buffer, int offset, int count)
{
return innerStream.Read(buffer, offset, count);
}
/// <summary>
/// </summary>
public override int ReadByte()
{
return innerStream.ReadByte();
}
/// <summary>
/// </summary>
public override long Seek(long offset, SeekOrigin origin)
{
return innerStream.Seek(offset, origin);
}
/// <summary>
/// </summary>
public override void SetLength(long value)
{
innerStream.SetLength(value);
}
/// <summary>
/// </summary>
public override string ToString()
{
return innerStream.ToString();
}
/// <summary>
/// </summary>
public override void Write(byte[] buffer, int offset, int count)
{
innerStream.Write(buffer, offset, count);
}
/// <summary>
/// </summary>
public override void WriteByte(byte value)
{
innerStream.WriteByte(value);
}
#endregion
/// <summary>
/// Keeps track of the number of users using the stream.
/// </summary>
private int users;
/// <summary>
/// The number of users using the stream.
/// </summary>
public int Users
{
get
{
return users;
}
}
/// <summary>
/// Increases the number of users using this stream with 1.
/// </summary>
public void Open()
{
users++;
}
/// <summary>
/// Decreases the number of users using this stream with 1. If the number of users is below 0 the stream will really be closed.
/// </summary>
public override void Close()
{
users--;
if (users <= 0)
innerStream.Close();
}
/// <summary>
/// </summary>
public PersistentStream(Stream stream)
{
innerStream = stream;
Open();
}
}
};
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#if false
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.ComponentModel.Composition;
using RoslynToCCICodeModel;
using System.Diagnostics;
using ClousotExtension;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Formatting;
using System.Windows.Media;
using Microsoft.CodeAnalysis.CodeRefactorings;
using System.Threading.Tasks;
namespace ClousotExtension {
[ExportCodeRefactoringProvider("ClousotExtractMethod", LanguageNames.CSharp)]
class ClousotExtractMethod : ICodeRefactoringProvider {
private ClousotOptions options;
[ImportingConstructor]
public ClousotExtractMethod(ClousotOptions options) {
this.options = options;
}
public async System.Threading.Tasks.Task<IEnumerable<CodeAction>> GetRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
if (textSpan.IsEmpty)
{
return null;
}
if (String.IsNullOrWhiteSpace(document.GetText().GetSubText(textSpan).ToString())) { return null; }
var tree = (SyntaxTree)document.GetSyntaxTree(cancellationToken);
var diagnostics = tree.GetDiagnostics(cancellationToken);
if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError)) return null;
var linespan = tree.GetLocation(textSpan).GetLineSpan(false);
if (linespan.EndLinePosition.Line <= linespan.StartLinePosition.Line) return null; // single line
var semanticModel = (SemanticModel)document.GetSemanticModel(cancellationToken);
var sdiag = semanticModel.GetDiagnostics(cancellationToken);
if (sdiag == null) return null;
if (sdiag.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError)) return null;
var methodExtractor = new MethodExtractor(semanticModel, document, textSpan, this.options);
var newDocument = methodExtractor.GetRefactoredDocument(cancellationToken);
if (newDocument == null) return null;
var action = new ClousotExtractMethodAction(newDocument);
return new List<CodeAction>{ action };
}
}
class ClousotExtractMethodAction : CodeAction
{
private Document d;
public ClousotExtractMethodAction(Document d)
{
this.d = d;
}
public override string Description { get { return "Extract method with Contracts"; } }
protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
{
return this.d;
}
}
class MethodExtractor {
private readonly SemanticModel semanticModel;
private readonly Microsoft.CodeAnalysis.Document document;
private readonly TextSpan textSpan;
private ClousotOptions options;
public MethodExtractor(SemanticModel semanticModel, Document document, TextSpan textSpan, ClousotOptions options) {
this.semanticModel = semanticModel;
this.document = document;
this.textSpan = textSpan;
this.options = options;
}
public Document GetRefactoredDocument_new(CancellationToken cancellationToken) {
if (this.textSpan.IsEmpty)
{
return null;
}
lock (this) {
var start = DateTime.Now;
Utils.Trace(string.Format("Trying to extract method, span: {0}", this.textSpan));
var localDocument = this.document;
var extracted = ExtractMethodService.ExtractMethodAsync(localDocument, this.textSpan, new ExtractMethodOptions(true), cancellationToken).Result;
Utils.TraceTime("Roslyn extract method", DateTime.Now - start);
if (!extracted.Succeeded) {
Utils.Trace("Method Extraction failed!");
return null;
}
Utils.Trace("Extract method: ok");
var clock = DateTime.Now;
var root = extracted.Document.GetSyntaxRoot(cancellationToken);
var closestEnclosingStatement = extracted.InvocationNameToken.Parent.FirstAncestorOrSelf<StatementSyntax>();
if (closestEnclosingStatement == null) return null;
var newMethod = extracted.MethodDeclarationNode as MethodDeclarationSyntax;
if (newMethod == null) return null;
var body = newMethod.Body;
Utils.Trace("Generating the Precondition marker");
var actualParameters = "";
var formalParameters = "";
var ps = newMethod.ParameterList.Parameters;
for (int i = 0, j = 0, n = ps.Count; i < n; i++) {
var p = ps[i];
{
var modifiers = "";
foreach (var modifier in p.Modifiers) {
modifiers = modifiers + modifier.ValueText + " ";
}
// Avoid the refs when emitting the condition
if (!String.IsNullOrEmpty(modifiers)) {
if (0 < j) {
actualParameters += ",";
formalParameters += ",";
}
var name = p.Identifier.ValueText;
actualParameters += name;
formalParameters += p.Type + " " + name;
j++;
}
}
}
// todo: just use invocation, but replace the method name with __PreconditionMarker!
var preconditionMarkerString = "__PreconditionMarker(" + actualParameters + ");";
var preconditionMarker = Formatter.Annotation.AddAnnotationTo(SyntaxFactory.ParseStatement(preconditionMarkerString));
var postconditionMarker = Formatter.Annotation.AddAnnotationTo(SyntaxFactory.ParseStatement("Console.WriteLine(5);\n"));
var b = SyntaxFactory.Block(preconditionMarker, closestEnclosingStatement, postconditionMarker);
//var finalRoot = ((SyntaxNode)root).ReplaceNode(
// closestEnclosingStatement,
// b.WithAdditionalAnnotations(CodeActionAnnotations.CreateRenameAnnotation())
// );
Utils.Trace("Adding dummy methods");
var preconditionMarkerDefString = "[Pure]\npublic static void __PreconditionMarker(" + formalParameters + "){}\n";
var preconditionMarkerDef = SyntaxFactory.MethodDeclaration(null, new SyntaxTokenList(), SyntaxFactory.ParseTypeName("void"), null, SyntaxFactory.ParseToken("__PreconditionMarker"), null, SyntaxFactory.ParseParameterList("(" + formalParameters + ")"), null, SyntaxFactory.Block());
var r1 = (SyntaxNode)root;
var classDef = closestEnclosingStatement.FirstAncestorOrSelf<TypeDeclarationSyntax>();
var r2 = new AddMarkerMethods(classDef, preconditionMarkerDef).Visit(r1);
var r3 = r2.ReplaceNode(
closestEnclosingStatement,
b.WithAdditionalAnnotations(CodeActionAnnotations.CreateRenameAnnotation())
);
return this.document.WithSyntaxRoot(r3);
#if false
var resultingTree = (SyntaxNode)extracted.MethodDeclarationNode;
var newMethodIdentified = (SyntaxToken)extracted.InvocationNameToken;
var oldTree = localDocument.GetSyntaxTree(cancellationToken);
if (oldTree == null) return null;
Utils.Trace("Got the original syntax tree");
var oldRoot = oldTree.GetRoot(cancellationToken) as SyntaxNode;
#endif
}
}
public Document GetRefactoredDocument(CancellationToken cancellationToken) {
lock (this) {
var start = DateTime.Now;
Utils.Trace(string.Format("Trying to extract method, span: {0}", this.textSpan));
var localDocument = document;
var extracted = ExtractMethodService.ExtractMethodAsync(localDocument, this.textSpan, new ExtractMethodOptions(true), cancellationToken).Result;
Utils.TraceTime("Roslyn extract method", DateTime.Now - start);
if (!extracted.Succeeded) {
Utils.Trace("Method Extraction failed!");
return null;
}
Utils.Trace("Extract method: ok");
var clock = DateTime.Now;
var resultingTree = localDocument.GetSyntaxTree(cancellationToken).GetRoot(cancellationToken);
var newMethodSyntax = extracted.MethodDeclarationNode as MethodDeclarationSyntax;
if (newMethodSyntax == null) return null;
var body = newMethodSyntax.Body;
var compilationUnitDeclaration = resultingTree as CompilationUnitSyntax;
if (compilationUnitDeclaration == null) return null;
var oldTree = localDocument.GetSyntaxTree(cancellationToken);
if (oldTree == null)
return null;
Utils.Trace("Got the original syntax tree");
var oldRoot = oldTree.GetRoot() as SyntaxNode;
// find the smallest containing statement (and the
Utils.Trace("Searching for the statement containing the new call");
StatementSyntax containingStatement = extracted.InvocationNameToken.Parent.FirstAncestorOrSelf<StatementSyntax>();
if (containingStatement == null) {
Utils.Trace("No containing statement found. Aborting");
return null;
}
Utils.Trace("Containing statement found");
Utils.Trace("Searching for the right spots where to place the placeholder calls");
var oldText = oldTree.GetText().ToString();
var beforeRefactoringText = oldText.Substring(0, containingStatement.Span.Start - 1);
var afterRefactoringText = oldText.Substring(containingStatement.Span.Start + containingStatement.Span.Length);
//var sub = oldText.Substring(containingStatement.Span.Start, containingStatement.Span.Length);
var sub = oldText.Substring(this.textSpan.Start, this.textSpan.Length);
Utils.Trace("Generating the Precondition marker");
var actualParameters = "";
var formalParameters = "";
var ps = newMethodSyntax.ParameterList.Parameters;
for (int i = 0, j = 0, n = ps.Count; i < n; i++) {
var p = ps[i];
{
var modifiers = "";
foreach (var modifier in p.Modifiers) {
modifiers = modifiers + modifier.ValueText + " ";
}
// Avoid the refs when emitting the condition
if (!String.IsNullOrEmpty(modifiers)) {
if (0 < j) {
actualParameters += ",";
formalParameters += ",";
}
var name = p.Identifier.ValueText;
actualParameters += name;
formalParameters += p.Type + " " + name;
j++;
}
}
}
// todo: just use invocation, but replace the method name with __PreconditionMarker!
var preconditionMarker = "__PreconditionMarker(" + actualParameters + ");";
Utils.Trace("Generating the Postcondition marker");
var postconditionMarker = "__PostconditionMarker(" + (actualParameters.Length > 0 ? actualParameters : "");
BinaryExpressionSyntax assignment = null;
var invocationExpression = extracted.InvocationNameToken.Parent.Parent as InvocationExpressionSyntax;
if (invocationExpression != null) {
var expression = invocationExpression.Parent.FirstAncestorOrSelf<ExpressionSyntax>();
if (expression != null && expression.Kind == SyntaxKind.AssignExpression) {
// TODO: what about += or local declarations? should they be included?
assignment = (BinaryExpressionSyntax)expression;
}
}
if (assignment == null) { // then the extraction was at the statement level
postconditionMarker += (actualParameters.Length > 0 ? "," : "") + "false";
} else {
postconditionMarker += (actualParameters.Length > 0 ? "," : "") + assignment.Left.GetText() + ", true";
}
postconditionMarker += ");";
Utils.Trace("Searching for the enclosing method");
// now need to climb up to enclosing method so definitions of the markers can be inserted
MethodDeclarationSyntax containingMethod = containingStatement.FirstAncestorOrSelf<MethodDeclarationSyntax>();
if (containingMethod == null) {
Utils.Trace("No enclosing method found: Aborting");
return null;
}
Utils.Trace("Enclosing method found");
Utils.Trace("Computing string positions for dummy methods");
cancellationToken.ThrowIfCancellationRequested();
var beforeMethodText = oldText.Substring(0, containingMethod.Span.Start - 1);
var inMethodBeforeRefactoringText = oldText.Substring(containingMethod.Span.Start, this.textSpan.Start - containingMethod.Span.Start);
var remaining = oldText.Substring(this.textSpan.End);
Utils.Trace("Adding dummy methods");
var preconditionMarkerDef = "[Pure]\npublic static void __PreconditionMarker(" + formalParameters + "){}\n";
// It is generic only if there is a parameter representing the return value
var postconditionMarkerDef = assignment != null ?
"[Pure]\npublic static void __PostconditionMarker<T>(" + formalParameters + (formalParameters.Length > 0 ? "," : "") + "T x,bool returnValue){}\n"
:
"[Pure]\npublic static void __PostconditionMarker(" + formalParameters + (formalParameters.Length > 0 ? "," : "") + " bool returnValue = false){}\n"
;
var newProg = String.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}",
beforeMethodText, preconditionMarkerDef, postconditionMarkerDef,
inMethodBeforeRefactoringText, preconditionMarker, sub, postconditionMarker,
remaining);
var newSolution = localDocument.Project.Solution.WithDocumentText(document.Id, SourceText.From(newProg));
//var newSolution = localDocument.Project.Solution.UpdateDocument(document.Id, SourceText.From(newProg));
localDocument = newSolution.GetDocument(document.Id);
var newTree = localDocument.GetSyntaxTree();
cancellationToken.ThrowIfCancellationRequested();
Utils.Trace("Dumping annotated tree");
Utils.DumpCSFile(@"AnnotatedTree.cs", newTree.GetText().ToString(), @"Program with marker explicits");
var newRoot = (CompilationUnitSyntax)newTree.GetRoot();
if (newRoot.ContainsDiagnostics) return null;
Utils.Trace("Searching the extracted method");
MethodDeclarationSyntax newExtractedMethod, originalMethod;
newExtractedMethod = extracted.MethodDeclarationNode as MethodDeclarationSyntax;
if (newExtractedMethod == null) {
Utils.Trace("Extracted method not found: aborting");
return null;
}
Utils.Trace("Extracted method found");
originalMethod = newExtractedMethod;
// Getting the name of the method
MethodDeclarationSyntax methodToAnalyze = containingStatement.FirstAncestorOrSelf<MethodDeclarationSyntax>();
if (methodToAnalyze == null) {
Utils.Trace("Extractee method not found: aborting");
return null;
}
Utils.Trace("Extractee method found.");
Utils.TraceTime("Generating annotated tree", DateTime.Now - clock);
clock = DateTime.Now; // reset the clock
// now let Clousot see the rewritten unit
cancellationToken.ThrowIfCancellationRequested();
Utils.Trace("Running Clousot to extract <Ps, Qs>");
newExtractedMethod = ExtractAndAddPsQs(ref cancellationToken, localDocument, newRoot, newExtractedMethod);
Utils.TraceTime("Running Clousot to extract <Ps, Qs>", DateTime.Now - clock);
clock = DateTime.Now;
if (newExtractedMethod == null) {
Utils.Trace("Aborting: failed to infer <Ps, Qs>");
return null;
}
Utils.Trace("Checking we have new contracts");
#if DEBUG || TRACE
// If we added some contract
if (newExtractedMethod == originalMethod) {
Utils.Trace("no new contract, but we continue to get the <Pm, Qm>");
//return null;
}
#endif
Utils.Trace("Creating a new tree");
var refactoredTree = (SyntaxNode) extracted.Document.GetSyntaxRoot().ReplaceNode(originalMethod, Formatter.Annotation.AddAnnotationTo(newExtractedMethod));
//(SyntaxNode)resultingTree.ReplaceNode(originalMethod, Formatter.Annotation.AddAnnotationTo(newExtractedMethod));
cancellationToken.ThrowIfCancellationRequested();
Utils.DumpCSFile(@"RefactoredProgram.cs", refactoredTree.ToFullString(), "Program with extracted contracts (Ps, Qs)");
//Utils.DumpCSFile(@"RefactoredProgram.cs", refactoredTree.GetFullText(), "Program with extracted contracts (Ps, Qs)");
var annotatedMethod = ExtractAndAddPmQm(ref cancellationToken, localDocument, refactoredTree, newExtractedMethod);
if (annotatedMethod == null) {
Utils.Trace("Aborting: failed to annotate the method");
return null;
}
Utils.TraceTime("Running Clousot to extract <Pm, Qm>", DateTime.Now - clock);
if (annotatedMethod != newExtractedMethod) {
Utils.Trace("Found new contracts, updating the method");
Utils.TraceTime("Done!", DateTime.Now - start);
refactoredTree = (SyntaxNode)extracted.Document.GetSyntaxRoot().ReplaceNode(originalMethod, Formatter.Annotation.AddAnnotationTo(annotatedMethod));
}
Utils.TraceTime("Done!", DateTime.Now - start);
return localDocument.WithSyntaxRoot(refactoredTree);
//return this.editFactory.CreateTreeTransformEdit(localDocument.Project.Solution, localDocument.GetSyntaxTree(), refactoredTree);
}
}
private MethodDeclarationSyntax ExtractAndAddPsQs(ref CancellationToken cancellationToken, Microsoft.CodeAnalysis.Document localDocument, CompilationUnitSyntax newRoot, MethodDeclarationSyntax newExtractedMethod)
{
// Let Clousot see the rewritten unit
var connectionToClousot = new RoslynToCCICodeModel.ClousotGlue();
var results = connectionToClousot.AnalyzeMeAUnit(localDocument, newRoot, cancellationToken, this.options,
new string[] { "-extractmethodmode", "-arrays:arraypurity", "-suggest:requires" /*"-memberNameSelect",*/ });
if (results == null) return null;
foreach (var result in results)
{
cancellationToken.ThrowIfCancellationRequested();
Utils.Trace("Getting Clousot Result");
String condition;
ContractKind kind;
if (result.IsExtractMethodSuggestion && result.Message.TryParseSuggestion(out kind, out condition))
{
Utils.Trace("Inserting Clousot result. New Condition: " + condition);
// Parse the condition
var newContract = SyntaxFactory.ParseStatement(condition + Environment.NewLine);
newExtractedMethod = newExtractedMethod.InsertStatements(newContract, kind);
}
else
{
Utils.Trace("Skipped Clousot output : " + result.Message);
}
}
return newExtractedMethod;
}
private MethodDeclarationSyntax ExtractAndAddPmQm(ref CancellationToken cancellationToken,
Microsoft.CodeAnalysis.Document localDocument, SyntaxNode oldRoot, MethodDeclarationSyntax newExtractedMethod) {
var newText = oldRoot.ToFullString();
cancellationToken.ThrowIfCancellationRequested();
Utils.DumpCSFile("BeforePmQm.cs", newText);
var newSolution = localDocument.Project.Solution.WithDocumentText(localDocument.Id, SourceText.From(newText));
//var newSolution = localDocument.Project.Solution.UpdateDocument(localDocument.Id, SourceText.From(newText));
var newLocalDocument = newSolution.GetDocument(localDocument.Id);
localDocument = null; // to be sure we do not use it
var newTree = newLocalDocument.GetSyntaxTree();
Utils.Trace("Running Clousot to infer <Pm, Qm> and <Pr, Qr>");
var newRoot = (CompilationUnitSyntax)newTree.GetRoot();
if (newRoot.ContainsDiagnostics) {
Utils.Trace("Aborting: the new tree has syntax errors");
return null;
}
// Let Clousot see the rewritten unit
var connectionToClousot = new RoslynToCCICodeModel.ClousotGlue();
var results = connectionToClousot.AnalyzeMeAUnit(newLocalDocument, newRoot, cancellationToken, this.options,
new string[] { "-extractmethodmoderefine", newExtractedMethod.Identifier.ValueText, "-premode", "combined", "-suggest", "methodensures", "-suggest:requires" });
if (results == null) return null;
foreach (var result in results)
{
cancellationToken.ThrowIfCancellationRequested();
Utils.Trace("Getting Clousot Result");
String condition;
ContractKind kind;
if (result.Message.TryParseSuggestion(out kind, out condition)) {
Utils.Trace("Inserting Clousot result. New Condition: " + condition);
// Parse the condition
var newContract = SyntaxFactory.ParseStatement(condition + Environment.NewLine);
if (!newContract.ContainsDiagnostics) {
newExtractedMethod = newExtractedMethod.InsertStatements(newContract, kind);
} else {
Utils.Trace("\tskipped, as it contains syntax errors");
}
}
}
return newExtractedMethod;
}
}
public class AddMarkerMethods : CSharpSyntaxRewriter {
private MethodDeclarationSyntax pre;
// private MethodDeclarationSyntax post;
private TypeDeclarationSyntax type;
public AddMarkerMethods(TypeDeclarationSyntax type, MethodDeclarationSyntax pre/*, MethodDeclarationSyntax post*/)
{
this.type = type;
this.pre = pre;
//this.post = post;
}
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) {
if (node == this.type) {
return node.WithMembers(node.Members.Add(this.pre));
}
return base.VisitClassDeclaration(node);
}
}
}
#endif
| |
using System;
using System.IO;
using System.Diagnostics;
using System.Text;
using System.Threading;
using ToolBelt;
namespace ToolBelt
{
/// <summary>
/// Class for running shell commands and scripts
/// </summary>
public class Command
{
#region Fields
/// <summary>
/// Get or set debug execution mode. In debug mode, just print the command that is supposed to be
/// executed and return 0.
/// </summary>
public bool DebugMode { get; set; }
public string Script { get; private set; }
public TextWriter OutputWriter { get; private set; }
public TextWriter ErrorWriter { get; private set; }
#endregion
#region Construction
public Command(string script, TextWriter outputWriter, TextWriter errorWriter, bool debugMode)
{
this.Script = script;
this.OutputWriter = outputWriter;
this.ErrorWriter = errorWriter;
this.DebugMode = debugMode;
}
#endregion
#region Private Methods
private string CreateScriptFile(string script)
{
#if WINDOWS
string scriptContents = String.Format("@echo off\r\n{0}\r\n", programAndArgs);
ParsedPath scriptFileName = new ParsedPath(Path.GetTempFileName(), PathType.File).WithExtension(".bat");
#elif MACOS
string scriptContents = String.Format("{0}\nexit $?", script);
ParsedPath scriptFileName = new ParsedPath(Path.GetTempFileName(), PathType.File).WithExtension(".sh");
#else
#error Unsupported OS
#endif
File.WriteAllText(scriptFileName, scriptContents);
if (this.DebugMode)
{
Console.WriteLine(scriptFileName + ":");
Console.WriteLine(scriptContents);
}
return scriptFileName;
}
#endregion
#region Public Methods
/// <summary>
/// Run the specified command through the shell specified in the COMSPEC
/// environment variable. Output is sent to the default console output and error streams.
/// </summary>
/// <param name="programAndArgs">The command to pass to the shell.</param>
/// <returns>The exit code of the process.</returns>
public static int Run(string programAndArgs)
{
return Run(programAndArgs, Console.Out, Console.Error, false); // Please DO NOT change this behavior!
}
/// <summary>
/// Run the specified command through the shell specified in the COMSPEC
/// environment variable.
/// </summary>
/// <param name="programAndArgs">The command to pass to the shell.</param>
/// <param name="output">Interleaved results from standard output and standard error streams.</param>
/// <returns>The exit code of the process.</returns>
public static int Run(string programAndArgs, out string output)
{
return Run(programAndArgs, out output, false);
}
public static int Run(string programAndArgs, out string output, bool debugMode)
{
StringBuilder outputString = new StringBuilder();
StringWriter outputWriter = new StringWriter(outputString);
int exitCode = Run(programAndArgs, outputWriter, outputWriter, debugMode);
outputWriter.Close();
output = outputString.ToString();
return exitCode;
}
/// <summary>
/// Run the specified command through the shell specified in the COMSPEC
/// environment variable.
/// </summary>
/// <param name="programAndArgs">The command to pass to the shell.</param>
/// <param name="output">Results from standard output stream.</param>
/// <param name="error">Results from standard error stream.</param>
/// <returns>The exit code of the process.</returns>
public static int Run(string programAndArgs, out string output, out string error)
{
StringBuilder outputString = new StringBuilder();
StringWriter outputWriter = new StringWriter(outputString);
StringBuilder errorString = new StringBuilder();
StringWriter errorWriter = new StringWriter(errorString);
int exitCode = Run(programAndArgs, outputWriter, errorWriter, false);
outputWriter.Close();
errorWriter.Close();
output = outputString.ToString();
error = errorString.ToString();
return exitCode;
}
/// <summary>
/// Run the specified command through the shell specified in the COMSPEC or SHELL environment variable.
/// </summary>
/// <param name="programAndArgs">The command to pass to the shell.</param>
/// <param name="outputWriter">The stream to which the standard output stream will be redirected.</param>
/// <param name="errorWriter">The stream to which the standard error stream will be redirected.</param>
/// <param name="debugMode">Debug mode</param>
/// <returns>The exit code of the process.</returns>
public static int Run(string programAndArgs, TextWriter outputWriter, TextWriter errorWriter, bool debugMode)
{
return new Command(programAndArgs, outputWriter, errorWriter, debugMode).Run();
}
public int Run()
{
int exitCode = -1;
string scriptFileName = null;
try
{
scriptFileName = CreateScriptFile(this.Script);
if (this.DebugMode)
{
this.OutputWriter.WriteLine(this.Script);
return 0;
}
#if WINDOWS
var shellVar = "COMSPEC";
#elif MACOS || UNIX
var shellVar = "SHELL";
#else
throw new NotImplementedException();
#endif
string shell = System.Environment.GetEnvironmentVariable(shellVar);
if (String.IsNullOrEmpty(shell))
throw new InvalidOperationException("{0} environment variable is not set".InvariantFormat(shellVar));
string argString = "\"" + scriptFileName + "\"";
Process p = new Process();
p.StartInfo = new ProcessStartInfo(shell, argString);
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
if (this.OutputWriter != null && this.ErrorWriter != null)
{
p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs arg)
{
if (arg.Data != null)
{
this.OutputWriter.WriteLine(arg.Data);
}
};
p.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs arg)
{
if (arg.Data != null)
{
this.ErrorWriter.WriteLine(arg.Data);
}
};
}
p.Start();
if (this.OutputWriter != null && this.ErrorWriter != null)
{
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}
p.WaitForExit();
exitCode = p.ExitCode;
p.Close();
}
finally
{
if (scriptFileName != null)
File.Delete(scriptFileName);
}
return exitCode;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="MSMQ.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Communication
{
using System;
using System.Globalization;
using System.Messaging;
using Microsoft.Build.Framework;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>Create</i> (<b>Required: </b> Path <b>Optional: Label, Transactional, Authenticated, MaximumQueueSize, MaximumJournalSize, UseJournalQueue, Force, Privacy</b> )</para>
/// <para><i>CheckExists</i> (<b>Required: </b> Path <b>Output: Exists</b> )</para>
/// <para><i>Delete</i> (<b>Required: </b> Path <b>Optional: </b> )</para>
/// <para><i>Send</i> (<b>Required: </b> Path <b>Optional: Message, Label</b> )</para>
/// <para><i>SetPermissions</i> (<b>Required: </b> Path <b>Optional: Allow, Deny, Revoke, Set</b> )</para>
/// <para><b>Remote Execution Support:</b> No</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <ItemGroup>
/// <Allow Include="TFS">
/// <Permissions>DeleteMessage,ReceiveMessage</Permissions>
/// </Allow>
/// <Deny Include="TFS">
/// <Permissions>GetQueueProperties</Permissions>
/// </Deny>
/// </ItemGroup>
/// <!-- Create queue -->
/// <MSBuild.ExtensionPack.Communication.MSMQ TaskAction="Create" Path=".\private$\3" Label="Test Queue" Force="true"/>
/// <!-- Check if the queue exists -->
/// <MSBuild.ExtensionPack.Communication.MSMQ TaskAction="CheckExists" Path=".\private$\3">
/// <Output TaskParameter="Exists" PropertyName="DoesExist"/>
/// </MSBuild.ExtensionPack.Communication.MSMQ>
/// <Message Text="Exists: $(DoesExist)"/>
/// <!-- Delete the queue -->
/// <MSBuild.ExtensionPack.Communication.MSMQ TaskAction="Delete" Path=".\private$\3"/>
/// <!-- Check if the queue exists -->
/// <MSBuild.ExtensionPack.Communication.MSMQ TaskAction="CheckExists" Path=".\private$\3">
/// <Output TaskParameter="Exists" PropertyName="DoesExist"/>
/// </MSBuild.ExtensionPack.Communication.MSMQ>
/// <Message Text="Exists: $(DoesExist)"/>
/// <!-- Delete the queue again to see that no error is thrown -->
/// <MSBuild.ExtensionPack.Communication.MSMQ TaskAction="Delete" Path=".\private$\3"/>
/// <!-- Create queue -->
/// <MSBuild.ExtensionPack.Communication.MSMQ TaskAction="Create" Path=".\private$\3" Label="Test Queue" Force="true" Transactional="false" Authenticated="" MaximumQueueSize="220"/>
/// <!-- Send Message -->
/// <MSBuild.ExtensionPack.Communication.MSMQ TaskAction="Send" Path=".\private$\3" Message="Mike" Label="Hi2"/>
/// <!-- Send Message -->
/// <MSBuild.ExtensionPack.Communication.MSMQ TaskAction="Send" Path=".\private$\3" Message="" Label=""/>
/// <!-- Set permissions -->
/// <MSBuild.ExtensionPack.Communication.MSMQ TaskAction="SetPermissions" Path=".\private$\3" Allow="@(Allow)" Deny="@(Deny)"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class MSMQ : BaseTask
{
private const string CreateTaskAction = "Create";
private const string DeleteTaskAction = "Delete";
private const string CheckExistsTaskAction = "CheckExists";
private const string SendTaskAction = "Send";
private const string SetPermissionsTaskAction = "SetPermissions";
private System.Messaging.EncryptionRequired privacy = System.Messaging.EncryptionRequired.Optional;
/// <summary>
/// Sets the path of the queue. Required.
/// </summary>
[Required]
public string Path { get; set; }
/// <summary>
/// Sets the Label of the queue
/// </summary>
public string Label { get; set; }
/// <summary>
/// Sets the Message to send to the queue
/// </summary>
public string Message { get; set; }
/// <summary>
/// An access-allowed entry that causes the new rights to be added to any existing rights the trustee has. Permission metadata supports: DeleteMessage, PeekMessage, WriteMessage, DeleteJournalMessage, SetQueueProperties, GetQueueProperties, DeleteQueue, GetQueuePermissions, ChangeQueuePermissions, TakeQueueOwnership, ReceiveMessage, ReceiveJournalMessage, GenericRead, GenericWrite, FullControl
/// </summary>
public ITaskItem[] Allow { get; set; }
/// <summary>
/// An access-denied entry that denies the specified rights in addition to any currently denied rights of the trustee. Permission metadata supports: DeleteMessage, PeekMessage, WriteMessage, DeleteJournalMessage, SetQueueProperties, GetQueueProperties, DeleteQueue, GetQueuePermissions, ChangeQueuePermissions, TakeQueueOwnership, ReceiveMessage, ReceiveJournalMessage, GenericRead, GenericWrite, FullControl
/// </summary>
public ITaskItem[] Deny { get; set; }
/// <summary>
/// An entry that removes all existing allowed or denied rights for the specified trustee. Permission metadata supports: DeleteMessage, PeekMessage, WriteMessage, DeleteJournalMessage, SetQueueProperties, GetQueueProperties, DeleteQueue, GetQueuePermissions, ChangeQueuePermissions, TakeQueueOwnership, ReceiveMessage, ReceiveJournalMessage, GenericRead, GenericWrite, FullControl
/// </summary>
public ITaskItem[] Revoke { get; set; }
/// <summary>
/// An access-allowed entry that is similar to Allow, except that the new entry allows only the specified rights. Using it discards any existing rights, including all existing access-denied entries for the trustee. Permission metadata supports: DeleteMessage, PeekMessage, WriteMessage, DeleteJournalMessage, SetQueueProperties, GetQueueProperties, DeleteQueue, GetQueuePermissions, ChangeQueuePermissions, TakeQueueOwnership, ReceiveMessage, ReceiveJournalMessage, GenericRead, GenericWrite, FullControl
/// </summary>
public ITaskItem[] Set { get; set; }
/// <summary>
/// Set true to create a transactional queue; false to create a non-transactional queue. Default is false;
/// </summary>
public bool Transactional { get; set; }
/// <summary>
/// Set to try to create an Authenticated queueu. Default is false
/// </summary>
public bool Authenticated { get; set; }
/// <summary>
/// Set to true to recreate a queue if it already exists
/// </summary>
public bool Force { get; set; }
/// <summary>
/// Sets the maximum queue size in kb.
/// </summary>
public int MaximumQueueSize { get; set; }
/// <summary>
/// Sets the maximum journal size in kb.
/// </summary>
public int MaximumJournalSize { get; set; }
/// <summary>
/// Set to true to use the journal queue
/// </summary>
public bool UseJournalQueue { get; set; }
/// <summary>
/// You can specify whether the queue accepts private (encrypted) messages, non-private (non-encrypted) messages, or both. Supports Optional (default), None, Both.
/// </summary>
public string Privacy
{
get { return this.privacy.ToString(); }
set { this.privacy = (System.Messaging.EncryptionRequired)Enum.Parse(typeof(System.Messaging.EncryptionRequired), value); }
}
/// <summary>
/// Gets whether the queue exists
/// </summary>
[Output]
public bool Exists { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
switch (this.TaskAction)
{
case CreateTaskAction:
this.Create();
break;
case CheckExistsTaskAction:
this.CheckExists();
break;
case DeleteTaskAction:
this.Delete();
break;
case SendTaskAction:
this.Send();
break;
case SetPermissionsTaskAction:
this.SetPermissions();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private void SetPermissions()
{
if (System.Messaging.MessageQueue.Exists(this.Path))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting permissions on queue: {0}", this.Path));
using (System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(this.Path))
{
if (this.Allow != null)
{
foreach (ITaskItem i in this.Allow)
{
MessageQueueAccessRights permission = (MessageQueueAccessRights)Enum.Parse(typeof(MessageQueueAccessRights), i.GetMetadata("Permissions"), true);
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Allow permission for user {0} - {1}", i.ItemSpec, i.GetMetadata("Permissions")));
queue.SetPermissions(i.ItemSpec, permission, AccessControlEntryType.Allow);
}
}
if (this.Deny != null)
{
foreach (ITaskItem i in this.Deny)
{
MessageQueueAccessRights permission = (MessageQueueAccessRights)Enum.Parse(typeof(MessageQueueAccessRights), i.GetMetadata("Permissions"), true);
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Deny permission for user {0} - {1}", i.ItemSpec, i.GetMetadata("Permissions")));
queue.SetPermissions(i.ItemSpec, permission, AccessControlEntryType.Deny);
}
}
if (this.Set != null)
{
foreach (ITaskItem i in this.Set)
{
MessageQueueAccessRights permission = (MessageQueueAccessRights)Enum.Parse(typeof(MessageQueueAccessRights), i.GetMetadata("Permissions"), true);
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Set permission for user {0} - {1}", i.ItemSpec, i.GetMetadata("Permissions")));
queue.SetPermissions(i.ItemSpec, permission, AccessControlEntryType.Set);
}
}
if (this.Revoke != null)
{
foreach (ITaskItem i in this.Revoke)
{
MessageQueueAccessRights permission = (MessageQueueAccessRights)Enum.Parse(typeof(MessageQueueAccessRights), i.GetMetadata("Permissions"), true);
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Revoke permission for user {0} - {1}", i.ItemSpec, i.GetMetadata("Permissions")));
queue.SetPermissions(i.ItemSpec, permission, AccessControlEntryType.Revoke);
}
}
}
}
else
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Queue not found: {0}", this.Path));
}
}
private void Create()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating queue: {0}", this.Path));
if (System.Messaging.MessageQueue.Exists(this.Path))
{
if (this.Force)
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting existing queue: {0}", this.Path));
System.Messaging.MessageQueue.Delete(this.Path);
}
else
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Queue already exists. Use Force=\"true\" to delete the existing queue: {0}", this.Path));
return;
}
}
using (System.Messaging.MessageQueue q = System.Messaging.MessageQueue.Create(this.Path, this.Transactional))
{
if (!string.IsNullOrEmpty(this.Label))
{
q.Label = this.Label;
}
if (this.Authenticated)
{
q.Authenticate = true;
}
if (this.MaximumQueueSize > 0)
{
q.MaximumQueueSize = this.MaximumQueueSize;
}
if (this.UseJournalQueue)
{
q.UseJournalQueue = true;
if (this.MaximumJournalSize > 0)
{
q.MaximumJournalSize = this.MaximumJournalSize;
}
}
q.EncryptionRequired = this.privacy;
}
}
private void CheckExists()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking whether queue exists: {0}", this.Path));
this.Exists = System.Messaging.MessageQueue.Exists(this.Path);
}
private void Send()
{
if (System.Messaging.MessageQueue.Exists(this.Path))
{
if (string.IsNullOrEmpty(this.Label))
{
this.Label = string.Empty;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Sending message to queue: [{0}] - {1}", this.Path, this.Message));
// Connect to a queue on the local computer.
using (System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(this.Path))
{
// Send a message to the queue.
if (this.Transactional)
{
// Create a transaction.
using (MessageQueueTransaction myTransaction = new MessageQueueTransaction())
{
// Begin the transaction.
myTransaction.Begin();
// Send the message.
queue.Send(this.Message, this.Label, myTransaction);
// Commit the transaction.
myTransaction.Commit();
}
}
else
{
queue.Send(this.Message, this.Label);
}
}
}
else
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Queue not found: {0}", this.Path));
}
}
private void Delete()
{
if (System.Messaging.MessageQueue.Exists(this.Path))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting queue: {0}", this.Path));
System.Messaging.MessageQueue.Delete(this.Path);
}
}
}
}
| |
using UnityEditor;
namespace BuildReportTool
{
public static class Options
{
// constants
public const string BUILD_REPORT_PACKAGE_MOVED_MSG = "BuildReport package seems to have been moved. Finding...";
public const string BUILD_REPORT_PACKAGE_MISSING_MSG = "Unable to find BuildReport package folder! Cannot find suitable GUI Skin.\nTry editing the source code and change the value\nof `BUILD_REPORT_TOOL_DEFAULT_PATH` to what path the Build Report Tool is in.\nMake sure the folder is named \"BuildReport\".";
public const string BUILD_REPORT_TOOL_DEFAULT_PATH = "Assets/BuildReport";
public const string BUILD_REPORT_TOOL_DEFAULT_FOLDER_NAME = "BuildReport";
public const string BUILD_REPORTS_DEFAULT_FOLDER_NAME = "UnityBuildReports";
// user options
public static string EditorLogOverridePath
{
get
{
return EditorPrefs.GetString("BRT_EditorLogOverridePath", "");
}
set
{
EditorPrefs.SetString("BRT_EditorLogOverridePath", value);
}
}
public static bool IncludeSvnInUnused
{
get
{
return EditorPrefs.GetBool("BRT_IncludeSvnInUnused", true);
}
set
{
EditorPrefs.SetBool("BRT_IncludeSvnInUnused", value);
}
}
public static bool IncludeGitInUnused
{
get
{
return EditorPrefs.GetBool("BRT_IncludeGitInUnused", true);
}
set
{
EditorPrefs.SetBool("BRT_IncludeGitInUnused", value);
}
}
public static FileFilterDisplay GetOptionFileFilterDisplay()
{
return FileFilterDisplay.DropDown;
}
public static bool AllowDeletingOfUsedAssets
{
get
{
return EditorPrefs.GetBool("BRT_AllowDeletingOfUsedAssets", false);
}
set
{
EditorPrefs.SetBool("BRT_AllowDeletingOfUsedAssets", value);
}
}
public static bool CollectBuildInfo
{
get
{
return EditorPrefs.GetBool("BRT_CollectBuildInfo", true);
}
set
{
EditorPrefs.SetBool("BRT_CollectBuildInfo", value);
}
}
/*public static int GetOptionEditorLogMegaByteSizeReadLimit()
{
return EditorPrefs.GetInt("BRT_EditorLogMegaByteSizeReadLimit", 100);
}
public static void SetOptionEditorLogMegaByteSizeReadLimit(int val)
{
EditorPrefs.SetInt("BRT_EditorLogMegaByteSizeReadLimit", val);
}*/
public static string BuildReportFolderName
{
get
{
return EditorPrefs.GetString("BRT_BuildReportFolderName", BUILD_REPORTS_DEFAULT_FOLDER_NAME);
}
set
{
EditorPrefs.SetString("BRT_BuildReportFolderName", value);
}
}
public static string BuildReportSavePath
{
get
{
return EditorPrefs.GetString("BRT_SavePath", BuildReportTool.Util.GetUserHomeFolder() + "/" + BuildReportFolderName);
}
set
{
EditorPrefs.SetString("BRT_SavePath", value + "/" + BuildReportFolderName);
}
}
public static int SaveType
{
get
{
return EditorPrefs.GetInt("BRT_SaveType", SAVE_TYPE_PERSONAL);
}
set
{
EditorPrefs.SetInt("BRT_SaveType", value);
}
}
public enum FileFilterDisplay
{
DropDown = 0,
Buttons = 1
}
public const int SAVE_TYPE_PERSONAL = 0;
public const int SAVE_TYPE_PROJECT = 1;
public enum FilterToUseType
{
UseConfiguredFile,
UseEmbedded
}
public static FilterToUseType GetOptionFilterToUse()
{
switch (FilterToUseInt)
{
case 0:
return FilterToUseType.UseConfiguredFile;
case 1:
return FilterToUseType.UseEmbedded;
}
return FilterToUseType.UseConfiguredFile;
}
public static bool ShouldUseConfiguredFileFilters()
{
//Debug.Log("GetOptionFilterToUse() " + GetOptionFilterToUse());
return GetOptionFilterToUse() == FilterToUseType.UseConfiguredFile;
}
public static bool ShouldUseEmbeddedFileFilters()
{
return GetOptionFilterToUse() == FilterToUseType.UseEmbedded;
}
public static int FilterToUseInt
{
get
{
return EditorPrefs.GetInt("BRT_FilterToUse", 0);
}
set
{
EditorPrefs.SetInt("BRT_FilterToUse", value);
}
}
public static int AssetListPaginationLength
{
get
{
return EditorPrefs.GetInt("BRT_AssetPaginationLength", 300);
}
set
{
EditorPrefs.SetInt("BRT_AssetPaginationLength", value);
}
}
public static int UnusedAssetsEntriesPerBatch
{
get
{
return EditorPrefs.GetInt("BRT_UnusedAssetsEntriesPerBatch", 1000);
}
set
{
EditorPrefs.SetInt("BRT_UnusedAssetsEntriesPerBatch", value);
}
}
// Build Report Calculation
// Full report
// No prefabs in unused assets calculation
// No unused assets calculation, but still has used assets list (won't collect prefabs in scene)
// No used assets and unused assets calculation (overview only)
public static bool IncludeUsedAssetsInReportCreation
{
get
{
return EditorPrefs.GetBool("BRT_IncludeUsedAssetsInReportCreation", true);
}
set
{
EditorPrefs.SetBool("BRT_IncludeUsedAssetsInReportCreation", value);
}
}
public static bool IncludeUnusedAssetsInReportCreation
{
get
{
return EditorPrefs.GetBool("BRT_IncludeUnusedAssetsInReportCreation", true);
}
set
{
EditorPrefs.SetBool("BRT_IncludeUnusedAssetsInReportCreation", value);
}
}
public static bool IncludeUnusedPrefabsInReportCreation
{
get
{
return EditorPrefs.GetBool("BRT_IncludeUnusedPrefabsInReportCreation", true);
}
set
{
EditorPrefs.SetBool("BRT_IncludeUnusedPrefabsInReportCreation", value);
}
}
public static bool IncludeBuildSizeInReportCreation
{
get
{
return EditorPrefs.GetBool("BRT_IncludeBuildSizeInReportCreation", true);
}
set
{
EditorPrefs.SetBool("BRT_IncludeBuildSizeInReportCreation", value);
}
}
public static bool GetImportedSizesForUsedAssets
{
get
{
return EditorPrefs.GetBool("BRT_GetImportedSizesForUsedAssets", true);
}
set
{
EditorPrefs.SetBool("BRT_GetImportedSizesForUsedAssets", value);
}
}
public static bool GetImportedSizesForUnusedAssets
{
get
{
return EditorPrefs.GetBool("BRT_GetImportedSizesForUnusedAssets", true);
}
set
{
EditorPrefs.SetBool("BRT_GetImportedSizesForUnusedAssets", value);
}
}
public static bool GetProjectSettings
{
get
{
return EditorPrefs.GetBool("BRT_GetProjectSettings", true);
}
set
{
EditorPrefs.SetBool("BRT_GetProjectSettings", value);
}
}
public static bool IsCalculationLevelAtFull(bool includeUsedAssets, bool includeUnusedAssets, bool includeUnusedPrefabs)
{
return includeUsedAssets && includeUnusedAssets && includeUnusedPrefabs;
}
public static bool IsCalculationLevelAtNoUnusedPrefabs(bool includeUsedAssets, bool includeUnusedAssets, bool includeUnusedPrefabs)
{
return includeUsedAssets && includeUnusedAssets && !includeUnusedPrefabs;
}
public static bool IsCalculationLevelAtNoUnusedAssets(bool includeUsedAssets, bool includeUnusedAssets, bool includeUnusedPrefabs)
{
// unused prefabs are not checked. if unused assets are not calculated, it is understood that unused prefabs are not included
return includeUsedAssets && !includeUnusedAssets;
}
public static bool IsCalculationLevelAtOverviewOnly(bool includeUsedAssets, bool includeUnusedAssets, bool includeUnusedPrefabs)
{
// if used assets not included, it is understood that unused assets are not included too.
// if used assets are not included, there is no way to determing if an asset is unused.
return !includeUsedAssets;
}
public static bool IsCurrentCalculationLevelAtFull
{
get
{
return IsCalculationLevelAtFull(IncludeUsedAssetsInReportCreation, IncludeUnusedAssetsInReportCreation, IncludeUnusedPrefabsInReportCreation);
}
}
public static bool IsCurrentCalculationLevelAtNoUnusedPrefabs
{
get
{
return IsCalculationLevelAtNoUnusedPrefabs(IncludeUsedAssetsInReportCreation, IncludeUnusedAssetsInReportCreation, IncludeUnusedPrefabsInReportCreation);
}
}
public static bool IsCurrentCalculationLevelAtNoUnusedAssets
{
get
{
return IsCalculationLevelAtNoUnusedAssets(IncludeUsedAssetsInReportCreation, IncludeUnusedAssetsInReportCreation, IncludeUnusedPrefabsInReportCreation);
}
}
public static bool IsCurrentCalculationLevelAtOverviewOnly
{
get
{
return IsCalculationLevelAtOverviewOnly(IncludeUsedAssetsInReportCreation, IncludeUnusedAssetsInReportCreation, IncludeUnusedPrefabsInReportCreation);
}
}
public static void SetCalculationLevelToFull()
{
IncludeUsedAssetsInReportCreation = true;
IncludeUnusedAssetsInReportCreation = true;
IncludeUnusedPrefabsInReportCreation = true;
}
public static void SetCalculationLevelToNoUnusedPrefabs()
{
IncludeUsedAssetsInReportCreation = true;
IncludeUnusedAssetsInReportCreation = true;
IncludeUnusedPrefabsInReportCreation = false;
}
public static void SetCalculationLevelToNoUnusedAssets()
{
IncludeUsedAssetsInReportCreation = true;
IncludeUnusedAssetsInReportCreation = false;
IncludeUnusedPrefabsInReportCreation = false;
}
public static void SetCalculationLevelToOverviewOnly()
{
IncludeUsedAssetsInReportCreation = false;
IncludeUnusedAssetsInReportCreation = false;
IncludeUnusedPrefabsInReportCreation = false;
}
public static bool AutoShowWindowAfterNormalBuild
{
get
{
return EditorPrefs.GetBool("BRT_AutoShowWindowAfterNormalBuild", true);
}
set
{
EditorPrefs.SetBool("BRT_AutoShowWindowAfterNormalBuild", value);
}
}
public static bool AutoShowWindowAfterBatchModeBuild
{
get
{
return EditorPrefs.GetBool("BRT_AutoShowWindowAfterBatchModeBuild", false);
}
set
{
EditorPrefs.SetBool("BRT_AutoShowWindowAfterBatchModeBuild", value);
}
}
public static void SetAutoShowWindowTypeToNever()
{
AutoShowWindowAfterNormalBuild = false;
AutoShowWindowAfterBatchModeBuild = false;
}
public static void SetAutoShowWindowTypeToAlways()
{
AutoShowWindowAfterNormalBuild = true;
AutoShowWindowAfterBatchModeBuild = true;
}
public static void SetAutoShowWindowTypeToNotInBatchMode()
{
AutoShowWindowAfterNormalBuild = true;
AutoShowWindowAfterBatchModeBuild = false;
}
public static bool IsAutoShowWindowTypeSetToNever
{
get
{
return
!AutoShowWindowAfterNormalBuild &&
!AutoShowWindowAfterBatchModeBuild;
}
}
public static bool IsAutoShowWindowTypeSetToAlways
{
get
{
return
AutoShowWindowAfterNormalBuild &&
AutoShowWindowAfterBatchModeBuild;
}
}
public static bool IsAutoShowWindowTypeSetToNotInBatchMode
{
get
{
return
AutoShowWindowAfterNormalBuild &&
!AutoShowWindowAfterBatchModeBuild;
}
}
public static bool ShouldShowWindowAfterBuild
{
get
{
return
(IsInBatchMode && AutoShowWindowAfterBatchModeBuild) ||
(!IsInBatchMode && AutoShowWindowAfterNormalBuild);
}
}
public static bool IsInBatchMode
{
get
{
return UnityEditorInternal.InternalEditorUtility.inBatchMode;
#if OTHER_BATCH_MODE_DETECTION_CODE
// different ways to find out actually.
// included here in case a new version of Unity
// removes our current way of figuring out batchmode.
// check the isHumanControllingUs bool
return UnityEditorInternal.InternalEditorUtility.isHumanControllingUs;
// check the command line args for "-batchmode"
string[] arguments = Environment.GetCommandLineArgs();
for (int n = 0, len = arguments.Length; n < len; ++n)
{
if (arguments[n] == "-batchmode")
{
return true;
}
}
return false;
#endif
}
}
}
}
| |
/**
Copyright 2014-2021 Robert McNeel and Associates
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 Eto.Forms;
using Rhino.UI;
using static RhinoCyclesCore.RenderEngine;
namespace RhinoCyclesCore.Settings
{
///<summary>
/// The UI implementation for advanced settings section in Rendering panel
///</summary>
public class AdvancedSettingsSection : Section
{
private readonly LocalizeStringPair m_caption;
private NumericStepper StepperSeed;
private NumericStepper StepperMaxBounces;
private NumericStepper StepperMaxDiffuseBounces;
private NumericStepper StepperMaxGlossyBounces;
private NumericStepper StepperMaxVolumeBounces;
private NumericStepper StepperMaxTransmissionBounces;
private NumericStepper StepperMaxTransparencyBounces;
private NumericStepper StepperSamples;
private CheckBox CheckboxUseSamples;
private DropDown ListboxTextureBakeQuality;
public override LocalizeStringPair Caption => m_caption;
///<summary>
/// The Heigth of the section
///</summary>
public override int SectionHeight
{
get
{
float dpi = ParentWindow != null ? ParentWindow.LogicalPixelSize : 1.0f;
// Content.Height, use 450 for now
int height = (int)(450 * dpi);
return height;
}
}
Guid m_pluginId;
public override Guid PlugInId => m_pluginId;
public Label LblSeed { get; set; }
public Label LblSamples { get; set; }
public Label LblUseDocumentSamples { get; set; }
public Label LblMaxBounces { get; set; }
public Label LblMaxDiffuseBounces { get; set; }
public Label LblMaxGlossyBounces { get; set; }
public Label LblMaxVolumeBounces { get; set; }
public Label LblMaxTransmissionBounces { get; set; }
public Label LblMaxTransparencyBounces { get; set; }
public Label LblTextureBakeQuality { get; set; }
public StackLayout MainLayout { get; set; }
/// <summary>
/// Local copy of Settings.Samples. Needed since we need it on
/// the Unload event. At this point Settings is invalid, so
/// that can't be used.
/// </summary>
private int Samples { get; set; } = 0;
///<summary>
/// Constructor for IntegratorSection
///</summary>
public AdvancedSettingsSection(Guid pluginId)
{
m_pluginId = pluginId;
m_caption = Localization.LocalizeCommandOptionValue("Rhino Render Advanced Settings", 38);
InitializeComponents();
InitializeLayout();
RegisterControlEvents();
ViewModelActivated += IntegratorSection_ViewModelActivated;
DataChanged += AdvancedSettingsSection_DataChanged;
}
private void AdvancedSettingsSection_DataChanged(object sender, Rhino.UI.Controls.DataSource.EventArgs e)
{
if(e.DataType == Rhino.UI.Controls.DataSource.ProviderIds.RhinoSettings)
DisplayData();
}
private void SettingsForProperties_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
DisplayData();
}
private void IntegratorSection_ViewModelActivated(object sender, EventArgs e)
{
DataContext = ViewModel;
DisplayData();
}
public override void DisplayData()
{
try
{
IntegratorSection_ViewportSettingsReceived(this, new EngineSettingsReceivedArgs(Settings));
}
catch (Exception)
{
}
}
private void IntegratorSection_ViewportSettingsReceived(object sender, EngineSettingsReceivedArgs e)
{
if (e.AllSettings != null)
{
UnregisterControlEvents();
StepperSeed.Value = e.AllSettings.Seed;
CheckboxUseSamples.Checked = e.AllSettings.UseDocumentSamples;
StepperSamples.Value = e.AllSettings.Samples;
StepperMaxBounces.Value = e.AllSettings.MaxBounce;
StepperMaxDiffuseBounces.Value = e.AllSettings.MaxDiffuseBounce;
StepperMaxGlossyBounces.Value = e.AllSettings.MaxGlossyBounce;
StepperMaxVolumeBounces.Value = e.AllSettings.MaxVolumeBounce;
StepperMaxTransmissionBounces.Value = e.AllSettings.MaxTransmissionBounce;
StepperMaxTransparencyBounces.Value = e.AllSettings.TransparentMaxBounce;
ListboxTextureBakeQuality.SelectedIndex = e.AllSettings.TextureBakeQuality;
RegisterControlEvents();
}
}
private void InitializeComponents()
{
LblSeed = new Label()
{
Text = Localization.LocalizeString("Seed", 4),
VerticalAlignment = VerticalAlignment.Center,
};
StepperSeed = new NumericStepper()
{
Value = 0,
MaxValue = int.MaxValue,
MinValue = 0,
MaximumDecimalPlaces = 0,
Width = 75,
Tag = AdvancedSettings.Seed,
};
LblSamples = new Label()
{
Text = Localization.LocalizeString("Samples", 6),
VerticalAlignment = VerticalAlignment.Center,
};
StepperSamples = new NumericStepper()
{
Value = 0,
MaximumDecimalPlaces = 0,
MaxValue = int.MaxValue,
MinValue = 0,
Width = 75,
Tag = AdvancedSettings.Samples,
};
LblUseDocumentSamples = new Label()
{
Text = Localization.LocalizeString("Override Production Render Quality", 1),
VerticalAlignment = VerticalAlignment.Center,
};
CheckboxUseSamples = new CheckBox()
{
Checked = false,
ToolTip = Localization.LocalizeString("Check to override render quality setting. If unchecked affects only viewport sample count", 2),
};
LblMaxBounces = new Label()
{
Text = Localization.LocalizeString("Maximum bounces", 22),
VerticalAlignment = VerticalAlignment.Center,
};
StepperMaxBounces = new NumericStepper()
{
Value = 0,
MaxValue = int.MaxValue,
MinValue = 0,
MaximumDecimalPlaces = 0,
Width = 75,
Tag = AdvancedSettings.MaxBounce,
};
LblMaxDiffuseBounces = new Label()
{
Text = Localization.LocalizeString("Diffuse", 31),
ToolTip = Localization.LocalizeString("Maximum Diffuse Bounces", 15),
VerticalAlignment = VerticalAlignment.Center,
};
StepperMaxDiffuseBounces = new NumericStepper()
{
Value = 0,
ToolTip = Localization.LocalizeString("Maximum Diffuse Bounces", 15),
MaxValue = int.MaxValue,
MinValue = 0,
MaximumDecimalPlaces = 0,
Width = 75,
Tag = AdvancedSettings.MaxDiffuseBounce,
};
LblMaxGlossyBounces = new Label()
{
Text = Localization.LocalizeString("Glossy", 32),
ToolTip = Localization.LocalizeString("Maximum Glossy Bounces", 16),
VerticalAlignment = VerticalAlignment.Center,
};
StepperMaxGlossyBounces = new NumericStepper()
{
Value = 0,
ToolTip = Localization.LocalizeString("Maximum Glossy Bounces", 16),
MaxValue = int.MaxValue,
MinValue = 0,
MaximumDecimalPlaces = 0,
Width = 75,
Tag = AdvancedSettings.MaxGlossyBounce,
};
LblMaxVolumeBounces = new Label()
{
Text = Localization.LocalizeString("Volume", 33),
ToolTip = Localization.LocalizeString("Maximum Volume Bounces", 17),
VerticalAlignment = VerticalAlignment.Center,
};
StepperMaxVolumeBounces = new NumericStepper()
{
Value = 0,
ToolTip = Localization.LocalizeString("Maximum Volume Bounces", 17),
MaxValue = int.MaxValue,
MinValue = 0,
MaximumDecimalPlaces = 0,
Width = 75,
Tag = AdvancedSettings.MaxVolumeBounce,
};
LblMaxTransmissionBounces = new Label()
{
Text = Localization.LocalizeString("Transmission", 23),
ToolTip = Localization.LocalizeString("Maximum Transmission Bounces", 18),
VerticalAlignment = VerticalAlignment.Center,
};
StepperMaxTransmissionBounces = new NumericStepper()
{
Value = 0,
ToolTip = Localization.LocalizeString("Maximum Transmission Bounces", 18),
MaxValue = int.MaxValue,
MinValue = 0,
MaximumDecimalPlaces = 0,
Width = 75,
Tag = AdvancedSettings.MaxTransmissionBounce,
};
LblMaxTransparencyBounces = new Label()
{
Text = Localization.LocalizeString("Transparency", 29),
ToolTip = Localization.LocalizeString("Maximum Transparency Bounces", 30),
VerticalAlignment = VerticalAlignment.Center,
};
StepperMaxTransparencyBounces = new NumericStepper()
{
Value = 0,
ToolTip = Localization.LocalizeString("Maximum Transparency Bounces", 37),
MinValue = 0,
MaximumDecimalPlaces = 0,
Width = 75,
Tag = AdvancedSettings.TransparentMaxBounce,
};
LblTextureBakeQuality = new Label()
{
Text = Localization.LocalizeString("Texture Bake Quality", 3),
VerticalAlignment = VerticalAlignment.Center,
};
ListboxTextureBakeQuality = new DropDown()
{
Items = {
Localization.LocalizeString("Low", 8),
Localization.LocalizeString("Standard", 9),
Localization.LocalizeString("High", 10),
Localization.LocalizeString("Ultra", 11)
}
};
}
private void InitializeLayout()
{
var bounceTable = new TableLayout()
{
Spacing = new Eto.Drawing.Size(1, 5),
Rows =
{
new TableRow(LblMaxBounces, StepperMaxBounces),
new TableRow(LblMaxDiffuseBounces, StepperMaxDiffuseBounces),
new TableRow(LblMaxGlossyBounces, StepperMaxGlossyBounces),
new TableRow(LblMaxTransmissionBounces, StepperMaxTransmissionBounces),
new TableRow(LblMaxVolumeBounces, StepperMaxVolumeBounces),
new TableRow(LblMaxTransparencyBounces, StepperMaxTransparencyBounces),
}
};
var sampleTable = new TableLayout()
{
Spacing = new Eto.Drawing.Size(1, 5),
Rows =
{
new TableRow(LblSamples, StepperSamples),
new TableRow(LblUseDocumentSamples, CheckboxUseSamples),
}
};
var textureTable = new TableLayout()
{
Spacing = new Eto.Drawing.Size(1, 5),
Rows =
{
new TableRow(LblTextureBakeQuality, ListboxTextureBakeQuality),
}
};
MainLayout = new StackLayout()
{
// Padding around the table
Padding = new Eto.Drawing.Padding(3, 5, 3, 0),
// Spacing between table cells
HorizontalContentAlignment = HorizontalAlignment.Stretch,
MinimumSize = new Eto.Drawing.Size(200, 400),
Items =
{
TableLayout.Horizontal(10,
new GroupBox() {
Padding = new Eto.Drawing.Padding(10, 5, 5, 10),
Text = Localization.LocalizeString("Seed", 4),
ToolTip = Localization.LocalizeString("Set the seed for the random number generator.", 34),
Content = new TableLayout
{
Rows = { new TableRow(new TableCell(StepperSeed, true)) }
}
}),
TableLayout.Horizontal(10,
new GroupBox()
{
Padding = new Eto.Drawing.Padding(10, 5, 5, 10),
Text = Localization.LocalizeString("Session", 12),
ToolTip = Localization.LocalizeString("Settings for controlling Cycles in a session", 20),
Content = sampleTable,
}
),
TableLayout.Horizontal(10,
new GroupBox()
{
Padding = new Eto.Drawing.Padding(10, 5, 5, 10),
Text = Localization.LocalizeString("Ray Bounces", 35),
ToolTip = Localization.LocalizeString("Settings controlling the bounce limits\nfor different types of rays.", 36),
Content = bounceTable,
}
),
TableLayout.Horizontal(10,
new GroupBox()
{
Padding = new Eto.Drawing.Padding(10, 5, 5, 10),
Text = Localization.LocalizeString("Texture Baking", 21),
ToolTip = Localization.LocalizeString("Setting for controlling texture bake resolution", 28),
Content = textureTable,
}
),
}
};
Content = MainLayout;
}
private void RegisterControlEvents()
{
CheckboxUseSamples.CheckedChanged += CheckboxUseSamples_CheckedChanged;
ListboxTextureBakeQuality.SelectedIndexChanged += ListboxTextureBakeQuality_SelectedIndexChanged;
StepperSamples.ValueChanged += IntegratorSettingValueChangedHandler;
StepperSeed.ValueChanged += IntegratorSettingValueChangedHandler;
StepperMaxBounces.ValueChanged += IntegratorSettingValueChangedHandler;
StepperMaxDiffuseBounces.ValueChanged += IntegratorSettingValueChangedHandler;
StepperMaxGlossyBounces.ValueChanged += IntegratorSettingValueChangedHandler;
StepperMaxVolumeBounces.ValueChanged += IntegratorSettingValueChangedHandler;
StepperMaxTransmissionBounces.ValueChanged += IntegratorSettingValueChangedHandler;
StepperMaxTransparencyBounces.ValueChanged += IntegratorSettingValueChangedHandler;
}
private void ListboxTextureBakeQuality_SelectedIndexChanged(object sender, EventArgs e)
{
var vud = Settings;
if (vud == null) return;
vud.TextureBakeQuality = ListboxTextureBakeQuality.SelectedIndex;
}
private void CheckboxUseSamples_CheckedChanged(object sender, EventArgs e)
{
var vud = Settings;
if (vud == null) return;
vud.UseDocumentSamples = CheckboxUseSamples.Checked.GetValueOrDefault(false);
}
private void UnregisterControlEvents()
{
CheckboxUseSamples.CheckedChanged -= CheckboxUseSamples_CheckedChanged;
StepperSamples.ValueChanged -= IntegratorSettingValueChangedHandler;
ListboxTextureBakeQuality.SelectedIndexChanged -= ListboxTextureBakeQuality_SelectedIndexChanged;
StepperSeed.ValueChanged -= IntegratorSettingValueChangedHandler;
StepperMaxBounces.ValueChanged -= IntegratorSettingValueChangedHandler;
StepperMaxDiffuseBounces.ValueChanged -= IntegratorSettingValueChangedHandler;
StepperMaxGlossyBounces.ValueChanged -= IntegratorSettingValueChangedHandler;
StepperMaxVolumeBounces.ValueChanged -= IntegratorSettingValueChangedHandler;
StepperMaxTransmissionBounces.ValueChanged -= IntegratorSettingValueChangedHandler;
StepperMaxTransparencyBounces.ValueChanged -= IntegratorSettingValueChangedHandler;
}
private void IntegratorSettingValueChangedHandler(object sender, EventArgs e)
{
var vud = Settings;
if (vud == null) return;
if (!(sender is NumericStepper ns)) return;
var setting = (AdvancedSettings)ns.Tag;
switch (setting)
{
case AdvancedSettings.Seed:
vud.Seed = (int)ns.Value;
break;
case AdvancedSettings.Samples:
vud.Samples = (int)ns.Value;
Samples = (int)ns.Value;
break;
case AdvancedSettings.MaxBounce:
vud.MaxBounce = (int)ns.Value;
break;
case AdvancedSettings.MaxDiffuseBounce:
vud.MaxDiffuseBounce = (int)ns.Value;
break;
case AdvancedSettings.MaxGlossyBounce:
vud.MaxGlossyBounce = (int)ns.Value;
break;
case AdvancedSettings.MaxTransmissionBounce:
vud.MaxTransmissionBounce = (int)ns.Value;
break;
case AdvancedSettings.MaxVolumeBounce:
vud.MaxVolumeBounce = (int)ns.Value;
break;
case AdvancedSettings.TransparentMaxBounce:
vud.TransparentMaxBounce = (int)ns.Value;
break;
default:
throw new ArgumentException("Unknown IntegratorSetting encountered");
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Fusion.Core.IniParser.Model
{
/// <summary>
/// Information associated to a section in a INI File
/// Includes both the value and the comments associated to the key.
/// </summary>
public class SectionData : ICloneable
{
IEqualityComparer<string> _searchComparer;
#region Initialization
public SectionData(string sectionName)
:this(sectionName, EqualityComparer<string>.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SectionData"/> class.
/// </summary>
public SectionData(string sectionName, IEqualityComparer<string> searchComparer)
{
_searchComparer = searchComparer;
if (string.IsNullOrEmpty(sectionName))
throw new ArgumentException("section name can not be empty");
_leadingComments = new List<string>();
_keyDataCollection = new KeyDataCollection(_searchComparer);
SectionName = sectionName;
}
/// <summary>
/// Initializes a new instance of the <see cref="SectionData"/> class
/// from a previous instance of <see cref="SectionData"/>.
/// </summary>
/// <remarks>
/// Data is deeply copied
/// </remarks>
/// <param name="ori">
/// The instance of the <see cref="SectionData"/> class
/// used to create the new instance.
/// </param>
/// <param name="searchComparer">
/// Search comparer.
/// </param>
public SectionData(SectionData ori, IEqualityComparer<string> searchComparer = null)
{
SectionName = ori.SectionName;
_searchComparer = searchComparer;
_leadingComments = new List<string>(ori._leadingComments);
_keyDataCollection = new KeyDataCollection(ori._keyDataCollection, searchComparer ?? ori._searchComparer);
}
#endregion
#region Operations
/// <summary>
/// Deletes all comments in this section and key/value pairs
/// </summary>
public void ClearComments()
{
LeadingComments.Clear();
TrailingComments.Clear();
Keys.ClearComments();
}
/// <summary>
/// Deletes all the key-value pairs in this section.
/// </summary>
public void ClearKeyData()
{
Keys.RemoveAllKeys();
}
/// <summary>
/// Merges otherSection into this, adding new keys if they don't exists
/// or overwriting values if the key already exists.
/// Comments get appended.
/// </summary>
/// <remarks>
/// Comments are also merged but they are always added, not overwritten.
/// </remarks>
/// <param name="toMergeSection"></param>
public void Merge(SectionData toMergeSection)
{
foreach (var comment in toMergeSection.LeadingComments)
LeadingComments.Add(comment);
Keys.Merge(toMergeSection.Keys);
foreach(var comment in toMergeSection.TrailingComments)
TrailingComments.Add(comment);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the name of the section.
/// </summary>
/// <value>
/// The name of the section
/// </value>
public string SectionName
{
get
{
return _sectionName;
}
set
{
if (!string.IsNullOrEmpty(value))
_sectionName = value;
}
}
/// <summary>
/// Gets or sets the comment list associated to this section.
/// </summary>
/// <value>
/// A list of strings.
/// </value>
public List<string> LeadingComments
{
get
{
return _leadingComments;
}
internal set
{
_leadingComments = new List<string>(value);
}
}
/// <summary>
/// Gets or sets the comment list associated to this section.
/// </summary>
/// <value>
/// A list of strings.
/// </value>
public List<string> Comments
{
get
{
var list = new List<string>(_leadingComments);
list.AddRange(_trailingComments);
return list;
}
}
/// <summary>
/// Gets or sets the comment list associated to this section.
/// </summary>
/// <value>
/// A list of strings.
/// </value>
public List<string> TrailingComments
{
get
{
return _trailingComments;
}
internal set
{
_trailingComments = new List<string>(value);
}
}
/// <summary>
/// Gets or sets the keys associated to this section.
/// </summary>
/// <value>
/// A collection of KeyData objects.
/// </value>
public KeyDataCollection Keys
{
get
{
return _keyDataCollection;
}
set
{
_keyDataCollection = value;
}
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public object Clone()
{
return new SectionData(this);
}
#endregion
#region Non-public members
// Comments associated to this section
private List<string> _leadingComments;
private List<string> _trailingComments = new List<string>();
// Keys associated to this section
private KeyDataCollection _keyDataCollection;
private string _sectionName;
#endregion
}
}
| |
namespace Microsoft.Azure.Management.StorSimple8000Series
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for BackupPoliciesOperations.
/// </summary>
public static partial class BackupPoliciesOperationsExtensions
{
/// <summary>
/// Gets all the backup policies in a device.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
public static IEnumerable<BackupPolicy> ListByDevice(this IBackupPoliciesOperations operations, string deviceName, string resourceGroupName, string managerName)
{
return operations.ListByDeviceAsync(deviceName, resourceGroupName, managerName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the backup policies in a device.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<BackupPolicy>> ListByDeviceAsync(this IBackupPoliciesOperations operations, string deviceName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByDeviceWithHttpMessagesAsync(deviceName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the properties of the specified backup policy name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The name of backup policy to be fetched.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
public static BackupPolicy Get(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, string resourceGroupName, string managerName)
{
return operations.GetAsync(deviceName, backupPolicyName, resourceGroupName, managerName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the properties of the specified backup policy name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The name of backup policy to be fetched.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BackupPolicy> GetAsync(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(deviceName, backupPolicyName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates the backup policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The name of the backup policy to be created/updated.
/// </param>
/// <param name='parameters'>
/// The backup policy.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
public static BackupPolicy CreateOrUpdate(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, BackupPolicy parameters, string resourceGroupName, string managerName)
{
return operations.CreateOrUpdateAsync(deviceName, backupPolicyName, parameters, resourceGroupName, managerName).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates the backup policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The name of the backup policy to be created/updated.
/// </param>
/// <param name='parameters'>
/// The backup policy.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BackupPolicy> CreateOrUpdateAsync(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, BackupPolicy parameters, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(deviceName, backupPolicyName, parameters, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the backup policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The name of the backup policy.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
public static void Delete(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, string resourceGroupName, string managerName)
{
operations.DeleteAsync(deviceName, backupPolicyName, resourceGroupName, managerName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the backup policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The name of the backup policy.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(deviceName, backupPolicyName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Backup the backup policy now.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The backup policy name.
/// </param>
/// <param name='backupType'>
/// The backup Type. This can be cloudSnapshot or localSnapshot.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
public static void BackupNow(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, string backupType, string resourceGroupName, string managerName)
{
operations.BackupNowAsync(deviceName, backupPolicyName, backupType, resourceGroupName, managerName).GetAwaiter().GetResult();
}
/// <summary>
/// Backup the backup policy now.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The backup policy name.
/// </param>
/// <param name='backupType'>
/// The backup Type. This can be cloudSnapshot or localSnapshot.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BackupNowAsync(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, string backupType, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BackupNowWithHttpMessagesAsync(deviceName, backupPolicyName, backupType, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates or updates the backup policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The name of the backup policy to be created/updated.
/// </param>
/// <param name='parameters'>
/// The backup policy.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
public static BackupPolicy BeginCreateOrUpdate(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, BackupPolicy parameters, string resourceGroupName, string managerName)
{
return operations.BeginCreateOrUpdateAsync(deviceName, backupPolicyName, parameters, resourceGroupName, managerName).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates the backup policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The name of the backup policy to be created/updated.
/// </param>
/// <param name='parameters'>
/// The backup policy.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BackupPolicy> BeginCreateOrUpdateAsync(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, BackupPolicy parameters, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(deviceName, backupPolicyName, parameters, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the backup policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The name of the backup policy.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
public static void BeginDelete(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, string resourceGroupName, string managerName)
{
operations.BeginDeleteAsync(deviceName, backupPolicyName, resourceGroupName, managerName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the backup policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The name of the backup policy.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(deviceName, backupPolicyName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Backup the backup policy now.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The backup policy name.
/// </param>
/// <param name='backupType'>
/// The backup Type. This can be cloudSnapshot or localSnapshot.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
public static void BeginBackupNow(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, string backupType, string resourceGroupName, string managerName)
{
operations.BeginBackupNowAsync(deviceName, backupPolicyName, backupType, resourceGroupName, managerName).GetAwaiter().GetResult();
}
/// <summary>
/// Backup the backup policy now.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='backupPolicyName'>
/// The backup policy name.
/// </param>
/// <param name='backupType'>
/// The backup Type. This can be cloudSnapshot or localSnapshot.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginBackupNowAsync(this IBackupPoliciesOperations operations, string deviceName, string backupPolicyName, string backupType, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginBackupNowWithHttpMessagesAsync(deviceName, backupPolicyName, backupType, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar
{
/// <summary>
/// The controller for navigation bars.
/// </summary>
/// <remarks>
/// The threading model for this class is simple: all non-static members are affinitized to the
/// UI thread.
/// </remarks>
internal partial class NavigationBarController : ForegroundThreadAffinitizedObject, INavigationBarController
{
private readonly INavigationBarPresenter _presenter;
private readonly ITextBuffer _subjectBuffer;
private readonly IWaitIndicator _waitIndicator;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly WorkspaceRegistration _workspaceRegistration;
/// <summary>
/// If we have pushed a full list to the presenter in response to a focus event, this
/// contains the version stamp of the list that was pushed. It is null if the last thing
/// pushed to the list was due to a caret move or file change.
/// </summary>
private VersionStamp? _versionStampOfFullListPushedToPresenter = null;
private bool _disconnected = false;
private Workspace _workspace;
public NavigationBarController(
INavigationBarPresenter presenter,
ITextBuffer subjectBuffer,
IWaitIndicator waitIndicator,
IAsynchronousOperationListener asyncListener)
{
_presenter = presenter;
_subjectBuffer = subjectBuffer;
_waitIndicator = waitIndicator;
_asyncListener = asyncListener;
_workspaceRegistration = Workspace.GetWorkspaceRegistration(subjectBuffer.AsTextContainer());
_workspaceRegistration.WorkspaceChanged += OnWorkspaceRegistrationChanged;
presenter.CaretMoved += OnCaretMoved;
presenter.ViewFocused += OnViewFocused;
presenter.DropDownFocused += OnDropDownFocused;
presenter.ItemSelected += OnItemSelected;
subjectBuffer.PostChanged += OnSubjectBufferPostChanged;
// Initialize the tasks to be an empty model so we never have to deal with a null case.
_modelTask = Task.FromResult(
new NavigationBarModel(
SpecializedCollections.EmptyList<NavigationBarItem>(),
default(VersionStamp),
null));
_selectedItemInfoTask = Task.FromResult(new NavigationBarSelectedTypeAndMember(null, null));
if (_workspaceRegistration.Workspace != null)
{
ConnectToWorkspace(_workspaceRegistration.Workspace);
}
}
private void OnWorkspaceRegistrationChanged(object sender, EventArgs e)
{
DisconnectFromWorkspace();
var newWorkspace = _workspaceRegistration.Workspace;
if (newWorkspace != null)
{
ConnectToWorkspace(newWorkspace);
}
}
private void ConnectToWorkspace(Workspace workspace)
{
AssertIsForeground();
// If we disconnected before the workspace ever connected, just disregard
if (_disconnected)
{
return;
}
_workspace = workspace;
_workspace.WorkspaceChanged += this.OnWorkspaceChanged;
// For the first time you open the file, we'll start immediately
StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: true);
}
private void DisconnectFromWorkspace()
{
if (_workspace != null)
{
_workspace.WorkspaceChanged -= this.OnWorkspaceChanged;
_workspace = null;
}
}
public void Disconnect()
{
AssertIsForeground();
DisconnectFromWorkspace();
_subjectBuffer.PostChanged -= OnSubjectBufferPostChanged;
_presenter.CaretMoved -= OnCaretMoved;
_presenter.ViewFocused -= OnViewFocused;
_presenter.DropDownFocused -= OnDropDownFocused;
_presenter.ItemSelected -= OnItemSelected;
_presenter.Disconnect();
_workspaceRegistration.WorkspaceChanged -= OnWorkspaceRegistrationChanged;
_disconnected = true;
// Cancel off any remaining background work
_modelTaskCancellationSource.Cancel();
_selectedItemInfoTaskCancellationSource.Cancel();
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args)
{
// We're getting an event for a workspace we already disconnected from
if (args.NewSolution.Workspace != _workspace)
{
return;
}
// If the displayed project is being renamed, retrigger the update
if (args.Kind == WorkspaceChangeKind.ProjectChanged && args.ProjectId != null)
{
var oldProject = args.OldSolution.GetProject(args.ProjectId);
var newProject = args.NewSolution.GetProject(args.ProjectId);
if (oldProject.Name != newProject.Name)
{
var currentContextDocumentId = _workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer());
if (currentContextDocumentId != null && currentContextDocumentId.ProjectId == args.ProjectId)
{
StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: true);
}
}
}
if (args.Kind == WorkspaceChangeKind.DocumentChanged &&
args.OldSolution == args.NewSolution)
{
var currentContextDocumentId = _workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer());
if (currentContextDocumentId != null && currentContextDocumentId == args.DocumentId)
{
// The context has changed, so update everything.
StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: true);
}
}
}
private void OnSubjectBufferPostChanged(object sender, EventArgs e)
{
AssertIsForeground();
StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: TaggerConstants.MediumDelay, selectedItemUpdateDelay: 0, updateUIWhenDone: true);
}
private void OnCaretMoved(object sender, EventArgs e)
{
AssertIsForeground();
StartSelectedItemUpdateTask(delay: TaggerConstants.NearImmediateDelay, updateUIWhenDone: true);
}
private void OnViewFocused(object sender, EventArgs e)
{
AssertIsForeground();
StartSelectedItemUpdateTask(delay: TaggerConstants.ShortDelay, updateUIWhenDone: true);
}
private void OnDropDownFocused(object sender, EventArgs e)
{
AssertIsForeground();
// Refresh the drop downs to their full information
_waitIndicator.Wait(
EditorFeaturesResources.NavigationBars,
EditorFeaturesResources.RefreshingNavigationBars,
allowCancel: true,
action: context => UpdateDropDownsSynchronously(context.CancellationToken));
}
private void UpdateDropDownsSynchronously(CancellationToken cancellationToken)
{
AssertIsForeground();
// If the presenter already has the full list and the model is already complete, then we
// don't have to do any further computation nor push anything to the presenter
if (PresenterAlreadyHaveUpToDateFullList(cancellationToken))
{
return;
}
// We need to ensure that all the state computation is up to date, so cancel any
// previous work and ensure the model is up to date
StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: false);
// Wait for the work to be complete. We'll wait with our cancellationToken, so if the
// user hits cancel we won't block them, but the computation can still continue
using (Logger.LogBlock(FunctionId.NavigationBar_UpdateDropDownsSynchronously_WaitForModel, cancellationToken))
{
_modelTask.Wait(cancellationToken);
}
using (Logger.LogBlock(FunctionId.NavigationBar_UpdateDropDownsSynchronously_WaitForSelectedItemInfo, cancellationToken))
{
_selectedItemInfoTask.Wait(cancellationToken);
}
IList<NavigationBarProjectItem> projectItems;
NavigationBarProjectItem selectedProjectItem;
GetProjectItems(out projectItems, out selectedProjectItem);
_presenter.PresentItems(
projectItems,
selectedProjectItem,
_modelTask.Result.Types,
_selectedItemInfoTask.Result.TypeItem,
_selectedItemInfoTask.Result.MemberItem);
_versionStampOfFullListPushedToPresenter = _modelTask.Result.SemanticVersionStamp;
}
private void GetProjectItems(out IList<NavigationBarProjectItem> projectItems, out NavigationBarProjectItem selectedProjectItem)
{
var documents = _subjectBuffer.CurrentSnapshot.GetRelatedDocumentsWithChanges();
if (!documents.Any())
{
projectItems = SpecializedCollections.EmptyList<NavigationBarProjectItem>();
selectedProjectItem = null;
return;
}
projectItems = documents.Select(d =>
new NavigationBarProjectItem(
d.Project.Name,
GetProjectGlyph(d.Project),
workspace: d.Project.Solution.Workspace,
documentId: d.Id,
language: d.Project.Language)).OrderBy(projectItem => projectItem.Text).ToList();
projectItems.Do(i => i.InitializeTrackingSpans(_subjectBuffer.CurrentSnapshot));
var document = _subjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
selectedProjectItem = document != null
? projectItems.FirstOrDefault(p => p.Text == document.Project.Name) ?? projectItems.First()
: projectItems.First();
}
private Glyph GetProjectGlyph(Project project)
{
// TODO: Get the glyph from the hierarchy
return project.Language == LanguageNames.CSharp ? Glyph.CSharpProject : Glyph.BasicProject;
}
/// <summary>
/// Check if the presenter has already been pushed the full model that corresponds to the
/// current buffer's project version stamp.
/// </summary>
private bool PresenterAlreadyHaveUpToDateFullList(CancellationToken cancellationToken)
{
AssertIsForeground();
// If it doesn't have a full list pushed, then of course not
if (_versionStampOfFullListPushedToPresenter == null)
{
return false;
}
var document = _subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return false;
}
return document.Project.GetDependentSemanticVersionAsync(cancellationToken).WaitAndGetResult(cancellationToken) == _versionStampOfFullListPushedToPresenter;
}
private void PushSelectedItemsToPresenter(NavigationBarSelectedTypeAndMember selectedItems)
{
AssertIsForeground();
var oldLeft = selectedItems.TypeItem;
var oldRight = selectedItems.MemberItem;
NavigationBarItem newLeft = null;
NavigationBarItem newRight = null;
var listOfLeft = new List<NavigationBarItem>();
var listOfRight = new List<NavigationBarItem>();
if (oldRight != null)
{
newRight = new NavigationBarPresentedItem(oldRight.Text, oldRight.Glyph, oldRight.Spans, oldRight.ChildItems, oldRight.Bolded, oldRight.Grayed || selectedItems.ShowMemberItemGrayed);
newRight.TrackingSpans = oldRight.TrackingSpans;
listOfRight.Add(newRight);
}
if (oldLeft != null)
{
newLeft = new NavigationBarPresentedItem(oldLeft.Text, oldLeft.Glyph, oldLeft.Spans, listOfRight, oldLeft.Bolded, oldLeft.Grayed || selectedItems.ShowTypeItemGrayed);
newLeft.TrackingSpans = oldLeft.TrackingSpans;
listOfLeft.Add(newLeft);
}
IList<NavigationBarProjectItem> projectItems;
NavigationBarProjectItem selectedProjectItem;
GetProjectItems(out projectItems, out selectedProjectItem);
_presenter.PresentItems(
projectItems,
selectedProjectItem,
listOfLeft,
newLeft,
newRight);
_versionStampOfFullListPushedToPresenter = null;
}
private void OnItemSelected(object sender, NavigationBarItemSelectedEventArgs e)
{
AssertIsForeground();
_waitIndicator.Wait(
EditorFeaturesResources.NavigationBars,
EditorFeaturesResources.RefreshingNavigationBars,
allowCancel: true,
action: context => ProcessItemSelectionSynchronously(e.Item, context.CancellationToken));
}
/// <summary>
/// Process the selection of an item synchronously inside a wait context.
/// </summary>
/// <param name="item">The selected item.</param>
/// <param name="cancellationToken">A cancellation token from the wait context.</param>
private void ProcessItemSelectionSynchronously(NavigationBarItem item, CancellationToken cancellationToken)
{
AssertIsForeground();
var presentedItem = item as NavigationBarPresentedItem;
if (presentedItem != null)
{
// Presented items are not navigable, but they may be selected due to a race
// documented in Bug #1174848. Protect all INavigationBarItemService implementers
// from this by ignoring these selections here.
return;
}
var projectItem = item as NavigationBarProjectItem;
if (projectItem != null)
{
projectItem.SwitchToContext();
// TODO: navigate to document / focus text view
}
else
{
var document = _subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var languageService = document.Project.LanguageServices.GetService<INavigationBarItemService>();
NavigateToItem(item, document, _subjectBuffer.CurrentSnapshot, languageService, cancellationToken);
}
}
// Now that the edit has been done, refresh to make sure everything is up-to-date. At
// this point, we now use CancellationToken.None to ensure we're properly refreshed.
UpdateDropDownsSynchronously(CancellationToken.None);
}
private void NavigateToItem(NavigationBarItem item, Document document, ITextSnapshot snapshot, INavigationBarItemService languageService, CancellationToken cancellationToken)
{
item.Spans = item.TrackingSpans.Select(ts => ts.GetSpan(snapshot).Span.ToTextSpan()).ToList();
languageService.NavigateToItem(document, item, _presenter.TryGetCurrentView(), cancellationToken);
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon 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.Collections.Generic;
using System.Linq;
using System.Text;
using OpenMetaverse;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.FrameworkTests
{
internal class SceneUtil
{
private readonly static Random rand = new Random();
public static Vector3 RandomVector()
{
return new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble());
}
public static Quaternion RandomQuat()
{
return new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble());
}
internal static byte RandomByte()
{
return (byte)rand.Next(byte.MaxValue);
}
public static SceneObjectPart RandomSOP(string name, uint localId)
{
OpenSim.Framework.PrimitiveBaseShape shape = MockPrmitiveBaseShape();
SceneObjectPart part = new SceneObjectPart(UUID.Zero, shape, new Vector3(1, 2, 3), new Quaternion(4, 5, 6, 7), Vector3.Zero, false);
part.Name = name;
part.Description = "Desc";
part.AngularVelocity = SceneUtil.RandomVector();
part.BaseMask = 0x0876;
part.Category = 10;
part.ClickAction = 5;
part.CollisionSound = UUID.Random();
part.CollisionSoundVolume = 1.1f;
part.CreationDate = OpenSim.Framework.Util.UnixTimeSinceEpoch();
part.CreatorID = UUID.Random();
part.EveryoneMask = 0x0543;
part.Flags = PrimFlags.CameraSource | PrimFlags.DieAtEdge;
part.GroupID = UUID.Random();
part.GroupMask = 0x0210;
part.LastOwnerID = UUID.Random();
part.LinkNum = 4;
part.LocalId = localId;
part.Material = 0x1;
part.MediaUrl = "http://bam";
part.NextOwnerMask = 0x0234;
part.CreatorID = UUID.Random();
part.ObjectFlags = 10101;
part.OwnerID = UUID.Random();
part.OwnerMask = 0x0567;
part.OwnershipCost = 5;
part.ParentID = 0202;
part.ParticleSystem = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, };
part.PassTouches = true;
part.PhysicalAngularVelocity = SceneUtil.RandomVector();
part.RegionHandle = 1234567;
part.RegionID = UUID.Random();
part.RotationOffset = SceneUtil.RandomQuat();
part.SalePrice = 42;
part.SavedAttachmentPoint = 6;
part.SavedAttachmentPos = SceneUtil.RandomVector();
part.SavedAttachmentRot = SceneUtil.RandomQuat();
part.ScriptAccessPin = 87654;
part.SerializedPhysicsData = new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, };
part.ServerFlags = 0;
part.ServerWeight = 3.0f;
part.StreamingCost = 2.0f;
part.SitName = "Sitting";
part.Sound = UUID.Random();
part.SoundGain = 3.4f;
part.SoundOptions = 9;
part.SoundRadius = 10.3f;
part.Text = "Test";
part.TextColor = System.Drawing.Color.FromArgb(1, 2, 3, 4);
part.TextureAnimation = new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD };
part.TouchName = "DoIt";
part.UUID = UUID.Random();
part.Velocity = SceneUtil.RandomVector();
part.FromItemID = UUID.Random();
part.SetSitTarget(true, SceneUtil.RandomVector(), SceneUtil.RandomQuat(), false);
return part;
}
public static OpenSim.Framework.PrimitiveBaseShape MockPrmitiveBaseShape()
{
var shape = new OpenSim.Framework.PrimitiveBaseShape();
shape.ExtraParams = new byte[] { 0xA, 0x9, 0x8, 0x7, 0x6, 0x5 };
shape.FlexiDrag = 0.3f;
shape.FlexiEntry = true;
shape.FlexiForceX = 1.0f;
shape.FlexiForceY = 2.0f;
shape.FlexiForceZ = 3.0f;
shape.FlexiGravity = 10.0f;
shape.FlexiSoftness = 1;
shape.FlexiTension = 999.4f;
shape.FlexiWind = 9292.33f;
shape.HollowShape = OpenSim.Framework.HollowShape.Square;
shape.LightColorA = 0.3f;
shape.LightColorB = 0.22f;
shape.LightColorG = 0.44f;
shape.LightColorR = 0.77f;
shape.LightCutoff = 0.4f;
shape.LightEntry = true;
shape.LightFalloff = 7474;
shape.LightIntensity = 0.0f;
shape.LightRadius = 10.0f;
shape.Media = new OpenSim.Framework.PrimitiveBaseShape.PrimMedia();
shape.Media.New(2);
shape.Media[0] = new MediaEntry
{
AutoLoop = true,
AutoPlay = true,
AutoScale = true,
AutoZoom = true,
ControlPermissions = MediaPermission.All,
Controls = MediaControls.Standard,
CurrentURL = "bam.com",
EnableAlterntiveImage = true,
EnableWhiteList = false,
Height = 1,
HomeURL = "anotherbam.com",
InteractOnFirstClick = true,
InteractPermissions = MediaPermission.Group,
WhiteList = new string[] { "yo mamma" },
Width = 5
};
shape.Media[1] = new MediaEntry
{
AutoLoop = true,
AutoPlay = true,
AutoScale = true,
AutoZoom = true,
ControlPermissions = MediaPermission.All,
Controls = MediaControls.Standard,
CurrentURL = "kabam.com",
EnableAlterntiveImage = true,
EnableWhiteList = true,
Height = 1,
HomeURL = "anotherbam.com",
InteractOnFirstClick = true,
InteractPermissions = MediaPermission.Group,
WhiteList = new string[] { "ur mamma" },
Width = 5
};
shape.PathBegin = 3;
shape.PathCurve = 127;
shape.PathEnd = 10;
shape.PathRadiusOffset = 127;
shape.PathRevolutions = 2;
shape.PathScaleX = 50;
shape.PathScaleY = 100;
shape.PathShearX = 33;
shape.PathShearY = 44;
shape.PathSkew = 126;
shape.PathTaperX = 110;
shape.PathTaperY = 66;
shape.PathTwist = 99;
shape.PathTwistBegin = 3;
shape.PCode = 3;
shape.PreferredPhysicsShape = PhysicsShapeType.Prim;
shape.ProfileBegin = 77;
shape.ProfileCurve = 5;
shape.ProfileEnd = 7;
shape.ProfileHollow = 9;
shape.ProfileShape = OpenSim.Framework.ProfileShape.IsometricTriangle;
shape.ProjectionAmbiance = 0.1f;
shape.ProjectionEntry = true;
shape.ProjectionFocus = 3.4f;
shape.ProjectionFOV = 4.0f;
shape.ProjectionTextureUUID = UUID.Random();
shape.Scale = SceneUtil.RandomVector();
shape.SculptEntry = true;
shape.SculptTexture = UUID.Random();
shape.SculptType = 40;
shape.VertexCount = 1;
shape.HighLODBytes = 2;
shape.MidLODBytes = 3;
shape.LowLODBytes = 4;
shape.LowestLODBytes = 5;
return shape;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace AngularWebApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetAzureDataReplicationRulesSpectraS3Request : Ds3Request
{
private string _dataPolicyId;
public string DataPolicyId
{
get { return _dataPolicyId; }
set { WithDataPolicyId(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private bool? _replicateDeletes;
public bool? ReplicateDeletes
{
get { return _replicateDeletes; }
set { WithReplicateDeletes(value); }
}
private DataPlacementRuleState? _state;
public DataPlacementRuleState? State
{
get { return _state; }
set { WithState(value); }
}
private string _targetId;
public string TargetId
{
get { return _targetId; }
set { WithTargetId(value); }
}
private DataReplicationRuleType? _type;
public DataReplicationRuleType? Type
{
get { return _type; }
set { WithType(value); }
}
public GetAzureDataReplicationRulesSpectraS3Request WithDataPolicyId(Guid? dataPolicyId)
{
this._dataPolicyId = dataPolicyId.ToString();
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId.ToString());
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithDataPolicyId(string dataPolicyId)
{
this._dataPolicyId = dataPolicyId;
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId);
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithReplicateDeletes(bool? replicateDeletes)
{
this._replicateDeletes = replicateDeletes;
if (replicateDeletes != null)
{
this.QueryParams.Add("replicate_deletes", replicateDeletes.ToString());
}
else
{
this.QueryParams.Remove("replicate_deletes");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithState(DataPlacementRuleState? state)
{
this._state = state;
if (state != null)
{
this.QueryParams.Add("state", state.ToString());
}
else
{
this.QueryParams.Remove("state");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithTargetId(Guid? targetId)
{
this._targetId = targetId.ToString();
if (targetId != null)
{
this.QueryParams.Add("target_id", targetId.ToString());
}
else
{
this.QueryParams.Remove("target_id");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithTargetId(string targetId)
{
this._targetId = targetId;
if (targetId != null)
{
this.QueryParams.Add("target_id", targetId);
}
else
{
this.QueryParams.Remove("target_id");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request WithType(DataReplicationRuleType? type)
{
this._type = type;
if (type != null)
{
this.QueryParams.Add("type", type.ToString());
}
else
{
this.QueryParams.Remove("type");
}
return this;
}
public GetAzureDataReplicationRulesSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/azure_data_replication_rule";
}
}
}
}
| |
using System;
using ViewNet;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace ViewNet
{
public class IOService : IService
{
volatile bool _IsActive;
long UploadFeedID;
long DownloadFeedID;
public volatile bool SafeToOperate;
Dictionary<long, FileFeed> UploadFromRemote = new Dictionary<long, FileFeed> ();
Dictionary<long, FileFeed> UploadToRemote = new Dictionary<long, FileFeed> ();
Dictionary<long, FileFeed> DownloadFromRemote = new Dictionary<long, FileFeed> ();
Dictionary<long, FileFeed> DownloadToRemote = new Dictionary<long, FileFeed> ();
readonly ByteServiceStream managedStream;
Thread writeThread { get; set; }
public string CurrentDirectory { get; set; }
public string[] Directories { get; set; }
public string[] Files { get; set; }
string RemoteCurrentDirectory { get; set; }
Dictionary<long, FileFeedFlag> UploadIDToFlag = new Dictionary<long, FileFeedFlag> ();
Dictionary<long, FileFeedFlag> DownloadIDToFlag = new Dictionary<long, FileFeedFlag> ();
public FileFeedFlag CheckDownloadState (long id)
{
FileFeedFlag flag;
lock (DownloadIDToFlag) {
if (DownloadIDToFlag.ContainsKey (id))
flag = DownloadIDToFlag [id];
else
return FileFeedFlag.Unknown;
}
return flag;
}
public FileFeedFlag CheckUploadState (long id)
{
FileFeedFlag flag;
lock (UploadIDToFlag) {
if (UploadIDToFlag.ContainsKey (id))
flag = UploadIDToFlag [id];
else
return FileFeedFlag.Unknown;
}
return flag;
}
public IOService ()
{
managedStream = new ByteServiceStream (new [] {
typeof(FileUploadRequest),
typeof(FileUploadResponse),
typeof(FileDownloadRequest),
typeof(FileDownloadResponse),
typeof(BrowseRequest),
typeof(BrowseResponse),
typeof(UploadCancel),
typeof(DownloadCancel),
typeof(UploadHold),
typeof(DownloadHold),
typeof(DownloadComplete),
typeof(UploadComplete),
typeof(DownloadFeed),
typeof(UploadFeed)
});
}
public byte[] Write ()
{
return managedStream.Write (65536);
}
public void Read (byte[] data)
{
managedStream.Read (data);
Process ();
}
protected void Process ()
{
while (true) {
var item = managedStream.AttemptDequeueMessage ();
if (item == null)
return;
var itemType = item.GetType ();
// Handle the Upload Request
if (itemType == typeof(FileUploadRequest))
ProcessUploadRequest ((FileUploadRequest)item);
// Handle The Upload Response
if (itemType == typeof(FileUploadResponse))
ProcessUploadResponse ((FileUploadResponse)item);
// Handle the Download Request
if (itemType == typeof(FileDownloadRequest))
ProcessDownloadRequest ((FileDownloadRequest)item);
// Handle The Download Response
if (itemType == typeof(FileDownloadResponse))
ProcessDownloadResponse ((FileDownloadResponse)item);
// Handle the Browse Request
if (itemType == typeof(BrowseRequest))
ProcessBrowseRequest ((BrowseRequest)item);
// Handle the Browse Response
if (itemType == typeof(BrowseResponse))
ProcessBrowseResponse ((BrowseResponse)item);
// Handle the Download Feed
if (itemType == typeof(DownloadFeed))
ProcessDownloadFeed ((DownloadFeed)item);
// Handle the Download Feed
if (itemType == typeof(UploadFeed))
ProcessUploadFeed ((UploadFeed)item);
// Handle the Upload Complete
if (itemType == typeof(UploadComplete))
ProcessUploadComplete ((UploadComplete)item);
// Handle the Download Feed
if (itemType == typeof(DownloadComplete))
ProcessDownloadComplete ((DownloadComplete)item);
}
}
protected void ProcessUploadRequest (FileUploadRequest request)
{
Console.WriteLine ("Processing Request");
// Combine the Request Path with Current Directory
// Assign the ID given in Request to a File Feed Handler Object.
// Set the File Feed as NotApproved to await calls
// Enqueue the Message
var selectedPath = Path.Combine (RemoteCurrentDirectory, request.FileName);
// Permission check here and send a not allowed resposne if failed such check.
lock (UploadFromRemote)
UploadFromRemote.Add (request.FileUploadID, new FileFeed (request.FileSize, selectedPath, FileFeedFlag.Allowed, new FileStream (selectedPath, FileMode.Create)));
var response = new FileUploadResponse ();
response.ID = request.FileUploadID;
response.Allowed = true;
managedStream.EnqueueMessage (response);
}
protected void ProcessUploadResponse (FileUploadResponse response)
{
Console.WriteLine ("Processing Response");
if (!UploadToRemote.ContainsKey (response.ID)) {
var closeUpload = new UploadCancel ();
closeUpload.ID = response.ID;
managedStream.EnqueueMessage (closeUpload);
return;
}
if (!response.Allowed) {
if (UploadToRemote.ContainsKey (response.ID)) {
UploadToRemote [response.ID].Feed.Dispose ();
UploadToRemote.Remove (response.ID);
}
return;
}
UploadToRemote [response.ID].State = FileFeedFlag.Allowed;
lock (UploadIDToFlag)
if (UploadIDToFlag.ContainsKey (response.ID))
UploadIDToFlag [response.ID] = FileFeedFlag.Allowed;
}
protected void ProcessDownloadRequest (FileDownloadRequest request)
{
var fullPath = Path.Combine (RemoteCurrentDirectory, request.FileName);
// Permission Check
if (!File.Exists (fullPath)) {
var reply = new FileDownloadResponse ();
reply.ID = request.ID;
reply.Allowed = false;
managedStream.EnqueueMessage (reply);
return;
}
lock (DownloadToRemote) {
var info = new FileInfo (fullPath);
DownloadToRemote.Add (request.ID, new FileFeed (info.Length, info.Name, FileFeedFlag.Allowed, new FileStream (fullPath, FileMode.Open)));
var response = new FileDownloadResponse ();
response.ID = response.ID;
response.Allowed = true;
managedStream.EnqueueMessage (response);
}
}
protected void ProcessDownloadResponse (FileDownloadResponse response)
{
lock (DownloadFromRemote) {
if (!DownloadFromRemote.ContainsKey (response.ID)) {
var cancel = new DownloadCancel ();
cancel.ID = response.ID;
managedStream.EnqueueMessage (cancel);
return;
}
DownloadFromRemote [response.ID].State = FileFeedFlag.Allowed;
lock (DownloadIDToFlag)
if (DownloadIDToFlag.ContainsKey (response.ID))
DownloadIDToFlag [response.ID] = FileFeedFlag.Allowed;
}
}
protected void ProcessBrowseRequest (BrowseRequest request)
{
// Permission Check
if (!Directory.Exists (request.Path)) {
var nullresponse = new BrowseResponse ();
managedStream.EnqueueMessage (nullresponse);
return;
}
RemoteCurrentDirectory = new DirectoryInfo (request.Path).FullName;
var response = new BrowseResponse ();
var dirs = new List<string> ();
var files = new List<string> ();
var currentdir = new DirectoryInfo (request.Path);
foreach (var item in currentdir.GetDirectories ())
dirs.Add (item.Name);
response.Dirs = dirs.ToArray ();
foreach (var item in currentdir.GetFiles ())
files.Add (item.Name);
response.Files = files.ToArray ();
response.DirPath = request.Path;
managedStream.EnqueueMessage (response);
Console.WriteLine ("Processed Browse Request");
}
protected void ProcessBrowseResponse (BrowseResponse response)
{
Console.WriteLine ("Processing Browse Response");
// Doesn't really require anything to process, just simply apply
if (CurrentDirectory != null)
lock (CurrentDirectory)
CurrentDirectory = response.DirPath;
else
CurrentDirectory = response.DirPath;
if (Directories != null)
lock (Directories)
Directories = response.Dirs;
else
Directories = response.Dirs;
if (Files != null)
lock (Files)
Files = response.Files;
else
Files = response.Files;
SafeToOperate = true;
}
protected void ProcessDownloadComplete (DownloadComplete completed)
{
lock (DownloadFromRemote) {
lock (DownloadIDToFlag)
if (DownloadIDToFlag.ContainsKey (completed.ID))
DownloadIDToFlag [completed.ID] = FileFeedFlag.Completed;
if (DownloadFromRemote.ContainsKey (completed.ID)) {
DownloadFromRemote [completed.ID].Feed.Close ();
DownloadFromRemote.Remove (completed.ID);
}
}
}
protected void ProcessUploadComplete (UploadComplete completed)
{
lock (UploadFromRemote) {
lock (UploadIDToFlag)
if (UploadIDToFlag.ContainsKey (completed.ID))
UploadIDToFlag [completed.ID] = FileFeedFlag.Completed;
if (UploadFromRemote.ContainsKey (completed.ID)) {
UploadFromRemote [completed.ID].Feed.Close ();
UploadFromRemote.Remove (completed.ID);
}
}
}
protected void ProcessDownloadFeed (DownloadFeed feed)
{
lock (DownloadFromRemote) {
if (!DownloadFromRemote.ContainsKey (feed.ID)) {
return; // Error it in the future
}
DownloadFromRemote [feed.ID].Feed.Write (feed.Data, 0, feed.Data.Length);
}
}
protected void ProcessUploadFeed (UploadFeed feed)
{
lock (UploadFromRemote) {
if (!UploadFromRemote.ContainsKey (feed.ID)) {
return; // Error it in the future
}
UploadFromRemote [feed.ID].Feed.Write (feed.Data, 0, feed.Data.Length);
}
}
protected void ProcessUploadHold (UploadHold hold)
{
lock (UploadToRemote) {
if (UploadToRemote.ContainsKey (hold.ID))
UploadToRemote [hold.ID].State = FileFeedFlag.Hold;
}
lock (UploadIDToFlag) {
if (UploadIDToFlag.ContainsKey (hold.ID))
UploadIDToFlag [hold.ID] = FileFeedFlag.Hold;
}
}
protected void ProcessDownloadHold (DownloadHold hold)
{
lock (DownloadFromRemote) {
if (DownloadFromRemote.ContainsKey (hold.ID))
DownloadFromRemote [hold.ID].State = FileFeedFlag.Hold;
}
lock (DownloadIDToFlag) {
if (DownloadIDToFlag.ContainsKey (hold.ID))
DownloadIDToFlag [hold.ID] = FileFeedFlag.Hold;
}
}
protected void ProcessUploadContinue (UploadHold hold)
{
lock (UploadToRemote) {
if (UploadToRemote.ContainsKey (hold.ID))
UploadToRemote [hold.ID].State = FileFeedFlag.Allowed;
}
lock (UploadIDToFlag) {
if (UploadIDToFlag.ContainsKey (hold.ID))
UploadIDToFlag [hold.ID] = FileFeedFlag.Allowed;
}
}
protected void ProcessDownloadContinue (DownloadHold hold)
{
lock (DownloadFromRemote) {
if (DownloadFromRemote.ContainsKey (hold.ID))
DownloadFromRemote [hold.ID].State = FileFeedFlag.Allowed;
}
lock (DownloadIDToFlag) {
if (DownloadIDToFlag.ContainsKey (hold.ID))
DownloadIDToFlag [hold.ID] = FileFeedFlag.Allowed;
}
}
public bool Available ()
{
var availableOrNot = managedStream.Avaliable ();
if (!availableOrNot)
WriteProcess ();
return managedStream.Avaliable ();
}
void StartWriteThread ()
{
if (writeThread != null) {
if (writeThread.ThreadState != ThreadState.Running)
writeThread = null;
else
return;
}
writeThread = new Thread (WriteProcess);
writeThread.Start ();
}
void WriteProcess ()
{
byte[] buffer;
int TotalAppend = 0;
int OldAppend = 0;
int tick = 0;
const int maxTick = 10;
var ListOfUploads = new List<long> ();
var ListOfDownloads = new List<long> ();
while (true) {
lock (UploadToRemote) {
var enumerate = UploadToRemote.GetEnumerator ();
while (enumerate.MoveNext ()) {
if (enumerate.Current.Value.State != FileFeedFlag.Allowed ||
ListOfUploads.Contains (enumerate.Current.Key)) {
continue;
}
tick++;
if (tick >= maxTick)
break;
buffer = new byte[8192];
var reSize = enumerate.Current.Value.Feed.Read (buffer, 0, buffer.Length);
if (reSize == 0) {
ListOfUploads.Add (enumerate.Current.Key);
continue;
}
TotalAppend += reSize;
Array.Resize (ref buffer, reSize);
var feed = new UploadFeed ();
feed.ID = enumerate.Current.Key;
feed.Data = (byte[])buffer.Clone ();
managedStream.EnqueueMessage (feed);
}
}
lock (DownloadToRemote) {
var enumerate = DownloadToRemote.GetEnumerator ();
while (enumerate.MoveNext ()) {
if (enumerate.Current.Value.State != FileFeedFlag.Allowed ||
ListOfDownloads.Contains (enumerate.Current.Key)) {
continue;
}
tick++;
if (tick >= maxTick)
break;
buffer = new byte[8192];
var reSize = enumerate.Current.Value.Feed.Read (buffer, 0, buffer.Length);
if (reSize == 0) {
ListOfDownloads.Add (enumerate.Current.Key);
continue;
}
TotalAppend += reSize;
Array.Resize (ref buffer, reSize);
var feed = new DownloadFeed ();
feed.ID = enumerate.Current.Key;
feed.Data = (byte[])buffer.Clone ();
managedStream.EnqueueMessage (feed);
}
}
foreach (var id in ListOfUploads) {
lock (UploadToRemote) {
UploadToRemote.Remove (id);
var completed = new UploadComplete ();
completed.ID = id;
managedStream.EnqueueMessage (completed);
lock (UploadIDToFlag)
if (UploadIDToFlag.ContainsKey (id)) {
UploadIDToFlag [id] = FileFeedFlag.Completed;
}
}
}
foreach (var id in ListOfDownloads) {
lock (DownloadToRemote) {
DownloadToRemote.Remove (id);
var completed = new DownloadComplete ();
completed.ID = id;
managedStream.EnqueueMessage (completed);
lock (DownloadIDToFlag)
if (DownloadIDToFlag.ContainsKey (id)) {
DownloadIDToFlag [id] = FileFeedFlag.Completed;
}
}
}
if (TotalAppend > 131072 ||
TotalAppend == OldAppend) {
break;
}
OldAppend = TotalAppend;
tick = 0;
}
}
public bool IsActive {
get {
return _IsActive;
}
set {
_IsActive = value;
}
}
public long UploadFile (string filepath)
{
if (!SafeToOperate)
throw new Exception ("Need to await a Browse Response to process otherwise remote computer will outright reject your upload no matter what.");
if (!File.Exists (filepath)) {
throw new IOException ("The file you selected does not exists!");
}
var info = new FileInfo (filepath);
var request = new FileUploadRequest ();
request.FileName = info.Name;
request.FileSize = info.Length;
request.FileUploadID = UploadFeedID;
// Prep the upload
lock (UploadToRemote)
UploadToRemote.Add (UploadFeedID, new FileFeed (info.Length, info.Name, FileFeedFlag.NotApproved, new FileStream (filepath, FileMode.Open)));
lock (UploadIDToFlag)
UploadIDToFlag.Add (UploadFeedID, FileFeedFlag.NotApproved);
managedStream.EnqueueMessage (request);
Console.WriteLine ("Sent Upload Request");
UploadFeedID++;
return UploadFeedID - 1;
}
public long DownloadFile (string file, string destination)
{
var request = new FileDownloadRequest ();
request.FileName = file;
request.ID = DownloadFeedID;
lock (DownloadFromRemote)
DownloadFromRemote.Add (DownloadFeedID, new FileFeed (-1, file, FileFeedFlag.Allowed, new FileStream (destination, FileMode.Create)));
lock (DownloadIDToFlag)
DownloadIDToFlag.Add (DownloadFeedID, FileFeedFlag.NotApproved);
managedStream.EnqueueMessage (request);
DownloadFeedID++;
return DownloadFeedID - 1;
}
public void BrowsePath (string path)
{
var request = new BrowseRequest ();
request.Path = path;
managedStream.EnqueueMessage (request);
Console.WriteLine ("Sending Browse Request");
}
public void HoldDownload (long id)
{
var holdDownload = new DownloadHold ();
holdDownload.ID = id;
managedStream.EnqueueMessage (holdDownload);
}
}
public class FileUploadRequest
{
public string FileName { get; set; }
public long FileSize { get; set; }
public long FileUploadID { get; set; }
public FileUploadRequest()
{
FileName = string.Empty;
}
public FileUploadRequest (string name, long size, long id)
{
FileName = name;
FileSize = size;
FileUploadID = id;
}
}
public class FileDownloadRequest
{
public long ID { get; set; }
public string FileName { get; set; }
}
public class FileDownloadResponse
{
public long ID { get; set; }
public bool Allowed { get; set; }
}
public class FileUploadResponse
{
public long ID { get; set; }
public bool Allowed { get; set; }
}
public class UploadFeed
{
public long ID { get; set; }
public byte[] Data { get; set; }
}
public class DownloadFeed
{
public long ID { get; set; }
public byte[] Data { get; set; }
}
public class BrowseRequest
{
public string Path { get; set; }
}
public class BrowseResponse
{
public string[] Dirs { get; set; }
public string[] Files { get; set; }
public string DirPath { get; set; }
}
public class UploadCancel
{
public long ID { get; set; }
}
public class DownloadCancel
{
public long ID { get; set; }
}
public class DownloadComplete
{
public long ID { get; set; }
}
public class UploadComplete
{
public long ID { get; set; }
}
public class UploadHold
{
public long ID { get; set; }
}
public class DownloadHold
{
public long ID { get; set; }
}
public class FileFeed
{
public long Size { get; set; }
public string Name { get; set; }
public FileFeedFlag State { get; set; }
public FileStream Feed { get; set; }
public FileFeed ()
{
}
public FileFeed (long size, string name, FileFeedFlag state, FileStream stream)
{
Size = size;
Name = name;
State = state;
Feed = stream;
}
}
public enum FileFeedFlag
{
Allowed,
NotApproved,
Hold,
Completed,
Unknown
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orchard.Caching;
using Orchard.Environment.Extensions.Loaders;
using Orchard.Environment.Extensions.Models;
using Orchard.FileSystems.Dependencies;
using Orchard.FileSystems.VirtualPath;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Utility;
namespace Orchard.Environment.Extensions {
public class ExtensionLoaderCoordinator : IExtensionLoaderCoordinator {
private readonly IDependenciesFolder _dependenciesFolder;
private readonly IExtensionDependenciesManager _extensionDependenciesManager;
private readonly IExtensionManager _extensionManager;
private readonly IVirtualPathProvider _virtualPathProvider;
private readonly IEnumerable<IExtensionLoader> _loaders;
private readonly IHostEnvironment _hostEnvironment;
private readonly IParallelCacheContext _parallelCacheContext;
private readonly IBuildManager _buildManager;
public ExtensionLoaderCoordinator(
IDependenciesFolder dependenciesFolder,
IExtensionDependenciesManager extensionDependenciesManager,
IExtensionManager extensionManager,
IVirtualPathProvider virtualPathProvider,
IEnumerable<IExtensionLoader> loaders,
IHostEnvironment hostEnvironment,
IParallelCacheContext parallelCacheContext,
IBuildManager buildManager) {
_dependenciesFolder = dependenciesFolder;
_extensionDependenciesManager = extensionDependenciesManager;
_extensionManager = extensionManager;
_virtualPathProvider = virtualPathProvider;
_loaders = loaders.OrderBy(l => l.Order);
_hostEnvironment = hostEnvironment;
_parallelCacheContext = parallelCacheContext;
_buildManager = buildManager;
T = NullLocalizer.Instance;
Logger = NullLogger.Instance;
}
public Localizer T { get; set; }
public ILogger Logger { get; set; }
public void SetupExtensions() {
Logger.Information("Start loading extensions...");
var context = CreateLoadingContext();
// Notify all loaders about extensions removed from the web site
foreach (var dependency in context.DeletedDependencies) {
Logger.Information("Extension {0} has been removed from site", dependency.Name);
foreach (var loader in _loaders) {
if (dependency.LoaderName == loader.Name) {
loader.ExtensionRemoved(context, dependency);
}
}
}
// For all existing extensions in the site, ask each loader if they can
// load that extension.
foreach (var extension in context.AvailableExtensions) {
ProcessExtension(context, extension);
}
// Execute all the work need by "ctx"
ProcessContextCommands(context);
// And finally save the new entries in the dependencies folder
_dependenciesFolder.StoreDescriptors(context.NewDependencies);
_extensionDependenciesManager.StoreDependencies(context.NewDependencies, desc => GetExtensionHash(context, desc));
Logger.Information("Done loading extensions...");
// Very last step: Notify the host environment to restart the AppDomain if needed
if (context.RestartAppDomain) {
Logger.Information("AppDomain restart required.");
_hostEnvironment.RestartAppDomain();
}
}
private string GetExtensionHash(ExtensionLoadingContext context, DependencyDescriptor dependencyDescriptor) {
var hash = new Hash();
hash.AddStringInvariant(dependencyDescriptor.Name);
foreach (var virtualpathDependency in context.ProcessedExtensions[dependencyDescriptor.Name].VirtualPathDependencies) {
hash.AddDateTime(GetVirtualPathModificationTimeUtc(context.VirtualPathModficationDates, virtualpathDependency));
}
foreach (var reference in dependencyDescriptor.References) {
hash.AddStringInvariant(reference.Name);
hash.AddString(reference.LoaderName);
hash.AddDateTime(GetVirtualPathModificationTimeUtc(context.VirtualPathModficationDates, reference.VirtualPath));
}
return hash.Value;
}
private void ProcessExtension(ExtensionLoadingContext context, ExtensionDescriptor extension) {
var extensionProbes = context.AvailableExtensionsProbes.ContainsKey(extension.Id) ?
context.AvailableExtensionsProbes[extension.Id] :
Enumerable.Empty<ExtensionProbeEntry>();
// materializes the list
extensionProbes = extensionProbes.ToArray();
if (Logger.IsEnabled(LogLevel.Debug)) {
Logger.Debug("Loaders for extension \"{0}\": ", extension.Id);
foreach (var probe in extensionProbes) {
Logger.Debug(" Loader: {0}", probe.Loader.Name);
Logger.Debug(" VirtualPath: {0}", probe.VirtualPath);
Logger.Debug(" VirtualPathDependencies: {0}", string.Join(", ", probe.VirtualPathDependencies));
}
}
var moduleReferences =
context.AvailableExtensions
.Where(e =>
context.ReferencesByModule.ContainsKey(extension.Id) &&
context.ReferencesByModule[extension.Id].Any(r => StringComparer.OrdinalIgnoreCase.Equals(e.Id, r.Name)))
.ToList();
var processedModuleReferences =
moduleReferences
.Where(e => context.ProcessedExtensions.ContainsKey(e.Id))
.Select(e => context.ProcessedExtensions[e.Id])
.ToList();
var activatedExtension = extensionProbes.FirstOrDefault(
e => e.Loader.IsCompatibleWithModuleReferences(extension, processedModuleReferences)
);
var previousDependency = context.PreviousDependencies.FirstOrDefault(
d => StringComparer.OrdinalIgnoreCase.Equals(d.Name, extension.Id)
);
if (activatedExtension == null) {
Logger.Warning("No loader found for extension \"{0}\"!", extension.Id);
}
var references = ProcessExtensionReferences(context, activatedExtension);
foreach (var loader in _loaders) {
if (activatedExtension != null && activatedExtension.Loader.Name == loader.Name) {
Logger.Information("Activating extension \"{0}\" with loader \"{1}\"", activatedExtension.Descriptor.Id, loader.Name);
loader.ExtensionActivated(context, extension);
}
else if (previousDependency != null && previousDependency.LoaderName == loader.Name) {
Logger.Information("Deactivating extension \"{0}\" from loader \"{1}\"", previousDependency.Name, loader.Name);
loader.ExtensionDeactivated(context, extension);
}
}
if (activatedExtension != null) {
context.NewDependencies.Add(new DependencyDescriptor {
Name = extension.Id,
LoaderName = activatedExtension.Loader.Name,
VirtualPath = activatedExtension.VirtualPath,
References = references
});
}
// Keep track of which loader we use for every extension
// This will be needed for processing references from other dependent extensions
context.ProcessedExtensions.Add(extension.Id, activatedExtension);
}
private ExtensionLoadingContext CreateLoadingContext() {
var availableExtensions = _extensionManager
.AvailableExtensions()
.Where(d => DefaultExtensionTypes.IsModule(d.ExtensionType) || DefaultExtensionTypes.IsTheme(d.ExtensionType))
.OrderBy(d => d.Id)
.ToList();
// Check there are no duplicates
var duplicates = availableExtensions.GroupBy(ed => ed.Id).Where(g => g.Count() >= 2).ToList();
if (duplicates.Any()) {
var sb = new StringBuilder();
sb.Append(T("There are multiple extensions with the same name installed in this instance of Orchard.\r\n"));
foreach (var dup in duplicates) {
sb.Append(T("Extension '{0}' has been found from the following locations: {1}.\r\n", dup.Key, string.Join(", ", dup.Select(e => e.Location + "/" + e.Id))));
}
sb.Append(T("This issue can be usually solved by removing or renaming the conflicting extension."));
Logger.Error(sb.ToString());
throw new OrchardException(new LocalizedString(sb.ToString()));
}
var previousDependencies = _dependenciesFolder.LoadDescriptors().ToList();
var virtualPathModficationDates = new ConcurrentDictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
Logger.Information("Probing extensions");
var availableExtensionsProbes1 = _parallelCacheContext
.RunInParallel(availableExtensions, extension =>
_loaders.Select(loader => loader.Probe(extension)).Where(entry => entry != null).ToArray())
.SelectMany(entries => entries)
.GroupBy(entry => entry.Descriptor.Id);
var availableExtensionsProbes = _parallelCacheContext
.RunInParallel(availableExtensionsProbes1, g =>
new { Id = g.Key, Entries = SortExtensionProbeEntries(g, virtualPathModficationDates)})
.ToDictionary(g => g.Id, g => g.Entries, StringComparer.OrdinalIgnoreCase);
Logger.Information("Done probing extensions");
var deletedDependencies = previousDependencies
.Where(e => !availableExtensions.Any(e2 => StringComparer.OrdinalIgnoreCase.Equals(e2.Id, e.Name)))
.ToList();
// Collect references for all modules
Logger.Information("Probing extension references");
var references = _parallelCacheContext
.RunInParallel(availableExtensions, extension => _loaders.SelectMany(loader => loader.ProbeReferences(extension)).ToList())
.SelectMany(entries => entries)
.ToList();
Logger.Information("Done probing extension references");
var referencesByModule = references
.GroupBy(entry => entry.Descriptor.Id, StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key, g => g.AsEnumerable(), StringComparer.OrdinalIgnoreCase);
var referencesByName = references
.GroupBy(reference => reference.Name, StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key, g => g.AsEnumerable(), StringComparer.OrdinalIgnoreCase);
var sortedAvailableExtensions =
availableExtensions.OrderByDependenciesAndPriorities(
(item, dep) => referencesByModule.ContainsKey(item.Id) &&
referencesByModule[item.Id].Any(r => StringComparer.OrdinalIgnoreCase.Equals(dep.Id, r.Name)),
item => 0)
.ToList();
return new ExtensionLoadingContext {
AvailableExtensions = sortedAvailableExtensions,
PreviousDependencies = previousDependencies,
DeletedDependencies = deletedDependencies,
AvailableExtensionsProbes = availableExtensionsProbes,
ReferencesByName = referencesByName,
ReferencesByModule = referencesByModule,
VirtualPathModficationDates = virtualPathModficationDates,
};
}
private IEnumerable<ExtensionProbeEntry> SortExtensionProbeEntries(IEnumerable<ExtensionProbeEntry> entries, ConcurrentDictionary<string, DateTime> virtualPathModficationDates) {
// All "entries" are for the same extension ID, so we just need to filter/sort them by priority+ modification dates.
var groupByPriority = entries
.GroupBy(entry => entry.Priority)
.OrderByDescending(g => g.Key);
// Select highest priority group with at least one item
var firstNonEmptyGroup = groupByPriority.FirstOrDefault(g => g.Any()) ?? Enumerable.Empty<ExtensionProbeEntry>();
// No need for further sorting if only 1 item found
if (firstNonEmptyGroup.Count() <= 1)
return firstNonEmptyGroup;
// Sort by last modification date/loader order
return firstNonEmptyGroup
.OrderByDescending(probe => GetVirtualPathDepedenciesModificationTimeUtc(virtualPathModficationDates, probe))
.ThenBy(probe => probe.Loader.Order)
.ToList();
}
private DateTime GetVirtualPathDepedenciesModificationTimeUtc(ConcurrentDictionary<string, DateTime> virtualPathDependencies, ExtensionProbeEntry probe) {
if (!probe.VirtualPathDependencies.Any())
return DateTime.MinValue;
Logger.Information("Retrieving modification dates of dependencies of extension '{0}'", probe.Descriptor.Id);
var result = probe.VirtualPathDependencies.Max(path => GetVirtualPathModificationTimeUtc(virtualPathDependencies, path));
Logger.Information("Done retrieving modification dates of dependencies of extension '{0}'", probe.Descriptor.Id);
return result;
}
private DateTime GetVirtualPathModificationTimeUtc(ConcurrentDictionary<string, DateTime> virtualPathDependencies, string path) {
return virtualPathDependencies.GetOrAdd(path, p => _virtualPathProvider.GetFileLastWriteTimeUtc(p));
}
IEnumerable<DependencyReferenceDescriptor> ProcessExtensionReferences(ExtensionLoadingContext context, ExtensionProbeEntry activatedExtension) {
if (activatedExtension == null)
return Enumerable.Empty<DependencyReferenceDescriptor>();
var referenceNames = (context.ReferencesByModule.ContainsKey(activatedExtension.Descriptor.Id) ?
context.ReferencesByModule[activatedExtension.Descriptor.Id] :
Enumerable.Empty<ExtensionReferenceProbeEntry>())
.Select(r => r.Name)
.Distinct(StringComparer.OrdinalIgnoreCase);
var referencesDecriptors = new List<DependencyReferenceDescriptor>();
foreach (var referenceName in referenceNames) {
ProcessExtensionReference(context, activatedExtension, referenceName, referencesDecriptors);
}
return referencesDecriptors;
}
private void ProcessExtensionReference(ExtensionLoadingContext context,
ExtensionProbeEntry activatedExtension,
string referenceName,
IList<DependencyReferenceDescriptor> activatedReferences) {
// If the reference is an extension has been processed already, use the same loader as
// that extension, since a given extension should be loaded with a unique loader for the
// whole application
var bestExtensionReference = context.ProcessedExtensions.ContainsKey(referenceName) ?
context.ProcessedExtensions[referenceName] :
null;
// Activated the extension reference
if (bestExtensionReference != null) {
activatedReferences.Add(new DependencyReferenceDescriptor {
LoaderName = bestExtensionReference.Loader.Name,
Name = referenceName,
VirtualPath = bestExtensionReference.VirtualPath
});
return;
}
// Skip references from "~/bin"
if (_buildManager.HasReferencedAssembly(referenceName))
return;
// Binary references
var references = context.ReferencesByName.ContainsKey(referenceName) ?
context.ReferencesByName[referenceName] :
Enumerable.Empty<ExtensionReferenceProbeEntry>();
var bestBinaryReference = references
.Where(entry => !string.IsNullOrEmpty(entry.VirtualPath))
.Select(entry => new { Entry = entry, LastWriteTimeUtc = _virtualPathProvider.GetFileLastWriteTimeUtc(entry.VirtualPath) })
.OrderBy(e => e.LastWriteTimeUtc)
.ThenBy(e => e.Entry.Name)
.FirstOrDefault();
// Activate the binary ref
if (bestBinaryReference != null) {
if (!context.ProcessedReferences.ContainsKey(bestBinaryReference.Entry.Name)) {
context.ProcessedReferences.Add(bestBinaryReference.Entry.Name, bestBinaryReference.Entry);
bestBinaryReference.Entry.Loader.ReferenceActivated(context, bestBinaryReference.Entry);
}
activatedReferences.Add(new DependencyReferenceDescriptor {
LoaderName = bestBinaryReference.Entry.Loader.Name,
Name = bestBinaryReference.Entry.Name,
VirtualPath = bestBinaryReference.Entry.VirtualPath
});
return;
}
}
private void ProcessContextCommands(ExtensionLoadingContext ctx) {
Logger.Information("Executing list of operations needed for loading extensions...");
foreach (var action in ctx.DeleteActions) {
action();
}
foreach (var action in ctx.CopyActions) {
action();
}
}
}
}
| |
/*
* 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 firehose-2015-08-04.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.KinesisFirehose.Model;
namespace Amazon.KinesisFirehose
{
/// <summary>
/// Interface for accessing KinesisFirehose
///
/// Amazon Kinesis Firehose API Reference
/// <para>
/// Amazon Kinesis Firehose is a fully-managed service that delivers real-time streaming
/// data to destinations such as Amazon S3 and Amazon Redshift.
/// </para>
/// </summary>
public partial interface IAmazonKinesisFirehose : IDisposable
{
#region CreateDeliveryStream
/// <summary>
/// Creates a delivery stream.
///
///
/// <para>
/// <a>CreateDeliveryStream</a> is an asynchronous operation that immediately returns.
/// The initial status of the delivery stream is <code>CREATING</code>. After the delivery
/// stream is created, its status is <code>ACTIVE</code> and it now accepts data. Attempts
/// to send data to a delivery stream that is not in the <code>ACTIVE</code> state cause
/// an exception. To check the state of a delivery stream, use <a>DescribeDeliveryStream</a>.
/// </para>
///
/// <para>
/// The name of a delivery stream identifies it. You can't have two delivery streams with
/// the same name in the same region. Two delivery streams in different AWS accounts or
/// different regions in the same AWS account can have the same name.
/// </para>
///
/// <para>
/// By default, you can create up to 5 delivery streams per region.
/// </para>
///
/// <para>
/// A delivery stream can only be configured with a single destination, Amazon S3 or Amazon
/// Redshift. For correct <a>CreateDeliveryStream</a> request syntax, specify only one
/// destination configuration parameter: either <code>RedshiftDestinationConfiguration</code>
/// or <code>S3DestinationConfiguration</code>
/// </para>
///
/// <para>
/// As part of <code>S3DestinationConfiguration</code>, optional values <code>BufferingHints</code>,
/// <code>EncryptionConfiguration</code>, and <code>CompressionFormat</code> can be provided.
/// By default, if no <code>BufferingHints</code> value is provided, Amazon Kinesis Firehose
/// buffers data up to 5 MB or for 5 minutes, whichever condition is satisfied first.
/// Note that <code>BufferingHints</code> is a hint, so there are some cases where the
/// service cannot adhere to these conditions strictly; for example, record boundaries
/// are such that the size is a little over or under the configured buffering size. By
/// default, no encryption is performed. We strongly recommend that you enable encryption
/// to ensure secure data storage in Amazon S3.
/// </para>
///
/// <para>
/// A few notes about <code>RedshiftDestinationConfiguration</code>:
/// </para>
/// <ul> <li>An Amazon Redshift destination requires an S3 bucket as intermediate location,
/// as Amazon Kinesis Firehose first delivers data to S3 and then uses <code>COPY</code>
/// syntax to load data into an Amazon Redshift table. This is specified in the <code>RedshiftDestinationConfiguration.S3Configuration</code>
/// parameter element.</li> <li>The compression formats <code>SNAPPY</code> or <code>ZIP</code>
/// cannot be specified in <code>RedshiftDestinationConfiguration.S3Configuration</code>
/// because the Amazon Redshift <code>COPY</code> operation that reads from the S3 bucket
/// doesn't support these compression formats.</li> <li>We strongly recommend that the
/// username and password provided is used exclusively for Amazon Kinesis Firehose purposes,
/// and that the permissions for the account are restricted for Amazon Redshift <code>INSERT</code>
/// permissions.</li> </ul>
/// <para>
/// Amazon Kinesis Firehose assumes the IAM role that is configured as part of destinations.
/// The IAM role should allow the Amazon Kinesis Firehose principal to assume the role,
/// and the role should have permissions that allows the service to deliver the data.
/// For more information, see <a href="http://docs.aws.amazon.com/firehose/latest/dev/controlling-access.html#using-iam-s3">Amazon
/// S3 Bucket Access</a> in the <i>Amazon Kinesis Firehose Developer Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateDeliveryStream service method.</param>
///
/// <returns>The response from the CreateDeliveryStream service method, as returned by KinesisFirehose.</returns>
/// <exception cref="Amazon.KinesisFirehose.Model.InvalidArgumentException">
/// The specified input parameter has an value that is not valid.
/// </exception>
/// <exception cref="Amazon.KinesisFirehose.Model.LimitExceededException">
/// You have already reached the limit for a requested resource.
/// </exception>
/// <exception cref="Amazon.KinesisFirehose.Model.ResourceInUseException">
/// The resource is already in use and not available for this operation.
/// </exception>
CreateDeliveryStreamResponse CreateDeliveryStream(CreateDeliveryStreamRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateDeliveryStream operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateDeliveryStream operation on AmazonKinesisFirehoseClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateDeliveryStream
/// operation.</returns>
IAsyncResult BeginCreateDeliveryStream(CreateDeliveryStreamRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateDeliveryStream operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateDeliveryStream.</param>
///
/// <returns>Returns a CreateDeliveryStreamResult from KinesisFirehose.</returns>
CreateDeliveryStreamResponse EndCreateDeliveryStream(IAsyncResult asyncResult);
#endregion
#region DeleteDeliveryStream
/// <summary>
/// Deletes a delivery stream and its data.
///
///
/// <para>
/// You can delete a delivery stream only if it is in <code>ACTIVE</code> or <code>DELETING</code>
/// state, and not in the <code>CREATING</code> state. While the deletion request is in
/// process, the delivery stream is in the <code>DELETING</code> state.
/// </para>
///
/// <para>
/// To check the state of a delivery stream, use <a>DescribeDeliveryStream</a>.
/// </para>
///
/// <para>
/// While the delivery stream is <code>DELETING</code> state, the service may continue
/// to accept the records, but the service doesn't make any guarantees with respect to
/// delivering the data. Therefore, as a best practice, you should first stop any applications
/// that are sending records before deleting a delivery stream.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteDeliveryStream service method.</param>
///
/// <returns>The response from the DeleteDeliveryStream service method, as returned by KinesisFirehose.</returns>
/// <exception cref="Amazon.KinesisFirehose.Model.ResourceInUseException">
/// The resource is already in use and not available for this operation.
/// </exception>
/// <exception cref="Amazon.KinesisFirehose.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
DeleteDeliveryStreamResponse DeleteDeliveryStream(DeleteDeliveryStreamRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteDeliveryStream operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteDeliveryStream operation on AmazonKinesisFirehoseClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteDeliveryStream
/// operation.</returns>
IAsyncResult BeginDeleteDeliveryStream(DeleteDeliveryStreamRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteDeliveryStream operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteDeliveryStream.</param>
///
/// <returns>Returns a DeleteDeliveryStreamResult from KinesisFirehose.</returns>
DeleteDeliveryStreamResponse EndDeleteDeliveryStream(IAsyncResult asyncResult);
#endregion
#region DescribeDeliveryStream
/// <summary>
/// Describes the specified delivery stream and gets the status. For example, after your
/// delivery stream is created, call <a>DescribeDeliveryStream</a> to see if the delivery
/// stream is <code>ACTIVE</code> and therefore ready for data to be sent to it.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryStream service method.</param>
///
/// <returns>The response from the DescribeDeliveryStream service method, as returned by KinesisFirehose.</returns>
/// <exception cref="Amazon.KinesisFirehose.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
DescribeDeliveryStreamResponse DescribeDeliveryStream(DescribeDeliveryStreamRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeDeliveryStream operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryStream operation on AmazonKinesisFirehoseClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeDeliveryStream
/// operation.</returns>
IAsyncResult BeginDescribeDeliveryStream(DescribeDeliveryStreamRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeDeliveryStream operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeDeliveryStream.</param>
///
/// <returns>Returns a DescribeDeliveryStreamResult from KinesisFirehose.</returns>
DescribeDeliveryStreamResponse EndDescribeDeliveryStream(IAsyncResult asyncResult);
#endregion
#region ListDeliveryStreams
/// <summary>
/// Lists your delivery streams.
///
///
/// <para>
/// The number of delivery streams might be too large to return using a single call to
/// <a>ListDeliveryStreams</a>. You can limit the number of delivery streams returned,
/// using the <code>Limit</code> parameter. To determine whether there are more delivery
/// streams to list, check the value of <code>HasMoreDeliveryStreams</code> in the output.
/// If there are more delivery streams to list, you can request them by specifying the
/// name of the last delivery stream returned in the call in the <code>ExclusiveStartDeliveryStreamName</code>
/// parameter of a subsequent call.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListDeliveryStreams service method.</param>
///
/// <returns>The response from the ListDeliveryStreams service method, as returned by KinesisFirehose.</returns>
ListDeliveryStreamsResponse ListDeliveryStreams(ListDeliveryStreamsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListDeliveryStreams operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListDeliveryStreams operation on AmazonKinesisFirehoseClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListDeliveryStreams
/// operation.</returns>
IAsyncResult BeginListDeliveryStreams(ListDeliveryStreamsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListDeliveryStreams operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListDeliveryStreams.</param>
///
/// <returns>Returns a ListDeliveryStreamsResult from KinesisFirehose.</returns>
ListDeliveryStreamsResponse EndListDeliveryStreams(IAsyncResult asyncResult);
#endregion
#region PutRecord
/// <summary>
/// Writes a single data record into an Amazon Kinesis Firehose delivery stream. To write
/// multiple data records into a delivery stream, use <a>PutRecordBatch</a>. Applications
/// using these operations are referred to as producers.
///
///
/// <para>
/// By default, each delivery stream can take in up to 2,000 transactions per second,
/// 5,000 records per second, or 5 MB per second. Note that if you use <a>PutRecord</a>
/// and <a>PutRecordBatch</a>, the limits are an aggregate across these two operations
/// for each delivery stream. For more information about limits and how to request an
/// increase, see <a href="http://docs.aws.amazon.com/firehose/latest/dev/limits.html">Amazon
/// Kinesis Firehose Limits</a>.
/// </para>
///
/// <para>
/// You must specify the name of the delivery stream and the data record when using <a>PutRecord</a>.
/// The data record consists of a data blob that can be up to 1,000 KB in size, and any
/// kind of data, for example, a segment from a log file, geographic location data, web
/// site clickstream data, etc.
/// </para>
///
/// <para>
/// Amazon Kinesis Firehose buffers records before delivering them to the destination.
/// To disambiguate the data blobs at the destination, a common solution is to use delimiters
/// in the data, such as a newline (<code>\n</code>) or some other character unique within
/// the data. This allows the consumer application(s) to parse individual data items when
/// reading the data from the destination.
/// </para>
///
/// <para>
/// Amazon Kinesis Firehose does not maintain data record ordering. If the destination
/// data needs to be re-ordered by the consumer application, the producer should include
/// some form of sequence number in each data record.
/// </para>
///
/// <para>
/// The <a>PutRecord</a> operation returns a <code>RecordId</code>, which is a unique
/// string assigned to each record. Producer applications can use this ID for purposes
/// such as auditability and investigation.
/// </para>
///
/// <para>
/// If the <a>PutRecord</a> operation throws a <code>ServiceUnavailableException</code>,
/// back off and retry. If the exception persists, it is possible that the throughput
/// limits have been exceeded for the delivery stream.
/// </para>
///
/// <para>
/// Data records sent to Amazon Kinesis Firehose are stored for 24 hours from the time
/// they are added to a delivery stream as it attempts to send the records to the destination.
/// If the destination is unreachable for more than 24 hours, the data is no longer available.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutRecord service method.</param>
///
/// <returns>The response from the PutRecord service method, as returned by KinesisFirehose.</returns>
/// <exception cref="Amazon.KinesisFirehose.Model.InvalidArgumentException">
/// The specified input parameter has an value that is not valid.
/// </exception>
/// <exception cref="Amazon.KinesisFirehose.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.KinesisFirehose.Model.ServiceUnavailableException">
/// The service is unavailable, back off and retry the operation. If you continue to see
/// the exception, throughput limits for the delivery stream may have been exceeded. For
/// more information about limits and how to request an increase, see <a href="http://docs.aws.amazon.com/firehose/latest/dev/limits.html">Amazon
/// Kinesis Firehose Limits</a>.
/// </exception>
PutRecordResponse PutRecord(PutRecordRequest request);
/// <summary>
/// Initiates the asynchronous execution of the PutRecord operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutRecord operation on AmazonKinesisFirehoseClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutRecord
/// operation.</returns>
IAsyncResult BeginPutRecord(PutRecordRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the PutRecord operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutRecord.</param>
///
/// <returns>Returns a PutRecordResult from KinesisFirehose.</returns>
PutRecordResponse EndPutRecord(IAsyncResult asyncResult);
#endregion
#region PutRecordBatch
/// <summary>
/// Writes multiple data records into a delivery stream in a single call, which can achieve
/// higher throughput per producer than when writing single records. To write single data
/// records into a delivery stream, use <a>PutRecord</a>. Applications using these operations
/// are referred to as producers.
///
///
/// <para>
/// Each <a>PutRecordBatch</a> request supports up to 500 records. Each record in the
/// request can be as large as 1,000 KB (before 64-bit encoding), up to a limit of 4 MB
/// for the entire request. By default, each delivery stream can take in up to 2,000 transactions
/// per second, 5,000 records per second, or 5 MB per second. Note that if you use <a>PutRecord</a>
/// and <a>PutRecordBatch</a>, the limits are an aggregate across these two operations
/// for each delivery stream. For more information about limits and how to request an
/// increase, see <a href="http://docs.aws.amazon.com/firehose/latest/dev/limits.html">Amazon
/// Kinesis Firehose Limits</a>.
/// </para>
///
/// <para>
/// You must specify the name of the delivery stream and the data record when using <a>PutRecord</a>.
/// The data record consists of a data blob that can be up to 1,000 KB in size, and any
/// kind of data, for example, a segment from a log file, geographic location data, web
/// site clickstream data, and so on.
/// </para>
///
/// <para>
/// Amazon Kinesis Firehose buffers records before delivering them to the destination.
/// To disambiguate the data blobs at the destination, a common solution is to use delimiters
/// in the data, such as a newline (<code>\n</code>) or some other character unique within
/// the data. This allows the consumer application(s) to parse individual data items when
/// reading the data from the destination.
/// </para>
///
/// <para>
/// The <a>PutRecordBatch</a> response includes a count of any failed records, <code>FailedPutCount</code>,
/// and an array of responses, <code>RequestResponses</code>. The <code>FailedPutCount</code>
/// value is a count of records that failed. Each entry in the <code>RequestResponses</code>
/// array gives additional information of the processed record. Each entry in <code>RequestResponses</code>
/// directly correlates with a record in the request array using the same ordering, from
/// the top to the bottom of the request and response. <code>RequestResponses</code> always
/// includes the same number of records as the request array. <code>RequestResponses</code>
/// both successfully and unsuccessfully processed records. Amazon Kinesis Firehose attempts
/// to process all records in each <a>PutRecordBatch</a> request. A single record failure
/// does not stop the processing of subsequent records.
/// </para>
///
/// <para>
/// A successfully processed record includes a <code>RecordId</code> value, which is a
/// unique value identified for the record. An unsuccessfully processed record includes
/// <code>ErrorCode</code> and <code>ErrorMessage</code> values. <code>ErrorCode</code>
/// reflects the type of error and is one of the following values: <code>ServiceUnavailable</code>
/// or <code>InternalFailure</code>. <code>ErrorMessage</code> provides more detailed
/// information about the error.
/// </para>
///
/// <para>
/// If <code>FailedPutCount</code> is greater than 0 (zero), retry the request. A retry
/// of the entire batch of records is possible; however, we strongly recommend that you
/// inspect the entire response and resend only those records that failed processing.
/// This minimizes duplicate records and also reduces the total bytes sent (and corresponding
/// charges).
/// </para>
///
/// <para>
/// If the <a>PutRecordBatch</a> operation throws a <code>ServiceUnavailableException</code>,
/// back off and retry. If the exception persists, it is possible that the throughput
/// limits have been exceeded for the delivery stream.
/// </para>
///
/// <para>
/// Data records sent to Amazon Kinesis Firehose are stored for 24 hours from the time
/// they are added to a delivery stream as it attempts to send the records to the destination.
/// If the destination is unreachable for more than 24 hours, the data is no longer available.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutRecordBatch service method.</param>
///
/// <returns>The response from the PutRecordBatch service method, as returned by KinesisFirehose.</returns>
/// <exception cref="Amazon.KinesisFirehose.Model.InvalidArgumentException">
/// The specified input parameter has an value that is not valid.
/// </exception>
/// <exception cref="Amazon.KinesisFirehose.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.KinesisFirehose.Model.ServiceUnavailableException">
/// The service is unavailable, back off and retry the operation. If you continue to see
/// the exception, throughput limits for the delivery stream may have been exceeded. For
/// more information about limits and how to request an increase, see <a href="http://docs.aws.amazon.com/firehose/latest/dev/limits.html">Amazon
/// Kinesis Firehose Limits</a>.
/// </exception>
PutRecordBatchResponse PutRecordBatch(PutRecordBatchRequest request);
/// <summary>
/// Initiates the asynchronous execution of the PutRecordBatch operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutRecordBatch operation on AmazonKinesisFirehoseClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutRecordBatch
/// operation.</returns>
IAsyncResult BeginPutRecordBatch(PutRecordBatchRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the PutRecordBatch operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutRecordBatch.</param>
///
/// <returns>Returns a PutRecordBatchResult from KinesisFirehose.</returns>
PutRecordBatchResponse EndPutRecordBatch(IAsyncResult asyncResult);
#endregion
#region UpdateDestination
/// <summary>
/// Updates the specified destination of the specified delivery stream.
///
///
/// <para>
/// This operation can be used to change the destination type (for example, to replace
/// the Amazon S3 destination with Amazon Redshift) or change the parameters associated
/// with a given destination (for example, to change the bucket name of the Amazon S3
/// destination). The update may not occur immediately. The target delivery stream remains
/// active while the configurations are updated, so data writes to the delivery stream
/// can continue during this process. The updated configurations are normally effective
/// within a few minutes.
/// </para>
///
/// <para>
/// If the destination type is the same, Amazon Kinesis Firehose merges the configuration
/// parameters specified in the <a>UpdateDestination</a> request with the destination
/// configuration that already exists on the delivery stream. If any of the parameters
/// are not specified in the update request, then the existing configuration parameters
/// are retained. For example, in the Amazon S3 destination, if <a>EncryptionConfiguration</a>
/// is not specified then the existing <a>EncryptionConfiguration</a> is maintained on
/// the destination.
/// </para>
///
/// <para>
/// If the destination type is not the same, for example, changing the destination from
/// Amazon S3 to Amazon Redshift, Amazon Kinesis Firehose does not merge any parameters.
/// In this case, all parameters must be specified.
/// </para>
///
/// <para>
/// Amazon Kinesis Firehose uses the <code>CurrentDeliveryStreamVersionId</code> to avoid
/// race conditions and conflicting merges. This is a required field in every request
/// and the service only updates the configuration if the existing configuration matches
/// the <code>VersionId</code>. After the update is applied successfully, the <code>VersionId</code>
/// is updated, which can be retrieved with the <a>DescribeDeliveryStream</a> operation.
/// The new <code>VersionId</code> should be uses to set <code>CurrentDeliveryStreamVersionId</code>
/// in the next <a>UpdateDestination</a> operation.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateDestination service method.</param>
///
/// <returns>The response from the UpdateDestination service method, as returned by KinesisFirehose.</returns>
/// <exception cref="Amazon.KinesisFirehose.Model.ConcurrentModificationException">
/// Another modification has already happened. Fetch <code>VersionId</code> again and
/// use it to update the destination.
/// </exception>
/// <exception cref="Amazon.KinesisFirehose.Model.InvalidArgumentException">
/// The specified input parameter has an value that is not valid.
/// </exception>
/// <exception cref="Amazon.KinesisFirehose.Model.ResourceInUseException">
/// The resource is already in use and not available for this operation.
/// </exception>
/// <exception cref="Amazon.KinesisFirehose.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
UpdateDestinationResponse UpdateDestination(UpdateDestinationRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateDestination operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateDestination operation on AmazonKinesisFirehoseClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateDestination
/// operation.</returns>
IAsyncResult BeginUpdateDestination(UpdateDestinationRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateDestination operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateDestination.</param>
///
/// <returns>Returns a UpdateDestinationResult from KinesisFirehose.</returns>
UpdateDestinationResponse EndUpdateDestination(IAsyncResult asyncResult);
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
namespace Orleans.Runtime
{
/// <summary>
/// Identifies activations that have been idle long enough to be deactivated.
/// </summary>
internal class ActivationCollector : IActivationCollector
{
internal Action<GrainId> Debug_OnDecideToCollectActivation;
private readonly TimeSpan quantum;
private readonly TimeSpan shortestAgeLimit;
private readonly ConcurrentDictionary<DateTime, Bucket> buckets;
private readonly object nextTicketLock;
private DateTime nextTicket;
private static readonly List<ActivationData> nothing = new List<ActivationData> { Capacity = 0 };
private readonly ILogger logger;
public ActivationCollector(IOptions<GrainCollectionOptions> options, ILogger<ActivationCollector> logger)
{
quantum = options.Value.CollectionQuantum;
shortestAgeLimit = TimeSpan.FromTicks(options.Value.ClassSpecificCollectionAge.Values
.Aggregate(options.Value.CollectionAge.Ticks, (a,v) => Math.Min(a,v.Ticks)));
buckets = new ConcurrentDictionary<DateTime, Bucket>();
nextTicket = MakeTicketFromDateTime(DateTime.UtcNow);
nextTicketLock = new object();
this.logger = logger;
}
public TimeSpan Quantum { get { return quantum; } }
private int ApproximateCount
{
get
{
int sum = 0;
foreach (var bucket in buckets.Values)
{
sum += bucket.ApproximateCount;
}
return sum;
}
}
// Return the number of activations that were used (touched) in the last recencyPeriod.
public int GetNumRecentlyUsed(TimeSpan recencyPeriod)
{
var now = DateTime.UtcNow;
int sum = 0;
foreach (var bucket in buckets)
{
// Ticket is the date time when this bucket should be collected (last touched time plus age limit)
// For now we take the shortest age limit as an approximation of the per-type age limit.
DateTime ticket = bucket.Key;
var timeTillCollection = ticket - now;
var timeSinceLastUsed = shortestAgeLimit - timeTillCollection;
if (timeSinceLastUsed <= recencyPeriod)
{
sum += bucket.Value.ApproximateCount;
}
}
return sum;
}
public void ScheduleCollection(ActivationData item)
{
lock (item)
{
if (item.IsExemptFromCollection)
{
return;
}
TimeSpan timeout = item.CollectionAgeLimit;
DateTime ticket = MakeTicketFromTimeSpan(timeout);
if (default(DateTime) != item.CollectionTicket)
{
throw new InvalidOperationException("Call CancelCollection before calling ScheduleCollection.");
}
Add(item, ticket);
}
}
public bool TryCancelCollection(ActivationData item)
{
if (item.IsExemptFromCollection) return false;
lock (item)
{
DateTime ticket = item.CollectionTicket;
if (default(DateTime) == ticket) return false;
if (IsExpired(ticket)) return false;
// first, we attempt to remove the ticket.
Bucket bucket;
if (!buckets.TryGetValue(ticket, out bucket) || !bucket.TryRemove(item)) return false;
}
return true;
}
public bool TryRescheduleCollection(ActivationData item)
{
if (item.IsExemptFromCollection) return false;
lock (item)
{
if (TryRescheduleCollection_Impl(item, item.CollectionAgeLimit)) return true;
item.ResetCollectionTicket();
return false;
}
}
private bool TryRescheduleCollection_Impl(ActivationData item, TimeSpan timeout)
{
// note: we expect the activation lock to be held.
if (default(DateTime) == item.CollectionTicket) return false;
ThrowIfTicketIsInvalid(item.CollectionTicket);
if (IsExpired(item.CollectionTicket)) return false;
DateTime oldTicket = item.CollectionTicket;
DateTime newTicket = MakeTicketFromTimeSpan(timeout);
// if the ticket value doesn't change, then the source and destination bucket are the same and there's nothing to do.
if (newTicket.Equals(oldTicket)) return true;
Bucket bucket;
if (!buckets.TryGetValue(oldTicket, out bucket) || !bucket.TryRemove(item))
{
// fail: item is not associated with currentKey.
return false;
}
// it shouldn't be possible for Add to throw an exception here, as only one concurrent competitor should be able to reach to this point in the method.
item.ResetCollectionTicket();
Add(item, newTicket);
return true;
}
private bool DequeueQuantum(out IEnumerable<ActivationData> items, DateTime now)
{
DateTime key;
lock (nextTicketLock)
{
if (nextTicket > now)
{
items = null;
return false;
}
key = nextTicket;
nextTicket += quantum;
}
Bucket bucket;
if (!buckets.TryRemove(key, out bucket))
{
items = nothing;
return true;
}
items = bucket.CancelAll();
return true;
}
public override string ToString()
{
var now = DateTime.UtcNow;
return string.Format("<#Activations={0}, #Buckets={1}, buckets={2}>",
ApproximateCount,
buckets.Count,
Utils.EnumerableToString(
buckets.Values.OrderBy(bucket => bucket.Key), bucket => Utils.TimeSpanToString(bucket.Key - now) + "->" + bucket.ApproximateCount + " items"));
}
/// <summary>
/// Scans for activations that are due for collection.
/// </summary>
/// <returns>A list of activations that are due for collection.</returns>
public List<ActivationData> ScanStale()
{
var now = DateTime.UtcNow;
List<ActivationData> result = null;
IEnumerable<ActivationData> activations;
while (DequeueQuantum(out activations, now))
{
// at this point, all tickets associated with activations are cancelled and any attempts to reschedule will fail silently. if the activation is to be reactivated, it's our job to clear the activation's copy of the ticket.
foreach (var activation in activations)
{
lock (activation)
{
activation.ResetCollectionTicket();
if (activation.State != ActivationState.Valid)
{
// Do nothing: don't collect, don't reschedule.
// The activation can't be in Created or Activating, since we only ScheduleCollection after successfull activation.
// If the activation is already in Deactivating or Invalid state, its already being collected or was collected
// (both mean a bug, this activation should not be in the collector)
// So in any state except for Valid we should just not collect and not reschedule.
logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_1,
"ActivationCollector found an activation in a non Valid state. All activation inside the ActivationCollector should be in Valid state. Activation: {0}",
activation.ToDetailedString());
}
else if (activation.ShouldBeKeptAlive)
{
// Consider: need to reschedule to what is the remaining time for ShouldBeKeptAlive, not the full CollectionAgeLimit.
ScheduleCollection(activation);
}
else if (!activation.IsInactive)
{
// This is essentialy a bug, an active activation should not be in the last bucket.
logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_2,
"ActivationCollector found an active activation in it's last bucket. This is violation of ActivationCollector invariants. " +
"For now going to defer it's collection. Activation: {0}",
activation.ToDetailedString());
ScheduleCollection(activation);
}
else if (!activation.IsStale(now))
{
// This is essentialy a bug, a non stale activation should not be in the last bucket.
logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_3,
"ActivationCollector found a non stale activation in it's last bucket. This is violation of ActivationCollector invariants. Now: {0}" +
"For now going to defer it's collection. Activation: {1}",
LogFormatter.PrintDate(now),
activation.ToDetailedString());
ScheduleCollection(activation);
}
else
{
// Atomically set Deactivating state, to disallow any new requests or new timer ticks to be dispatched on this activation.
activation.PrepareForDeactivation();
DecideToCollectActivation(activation, ref result);
}
}
}
}
return result ?? nothing;
}
/// <summary>
/// Scans for activations that have been idle for the specified age limit.
/// </summary>
/// <param name="ageLimit">The age limit.</param>
/// <returns></returns>
public List<ActivationData> ScanAll(TimeSpan ageLimit)
{
List<ActivationData> result = null;
var now = DateTime.UtcNow;
int bucketCount = buckets.Count;
int i = 0;
foreach (var bucket in buckets.Values)
{
if (i >= bucketCount) break;
int notToExceed = bucket.ApproximateCount;
int j = 0;
foreach (var activation in bucket)
{
// theoretically, we could iterate forever on the ConcurrentDictionary. we limit ourselves to an approximation of the bucket's Count property to limit the number of iterations we perform.
if (j >= notToExceed) break;
lock (activation)
{
if (activation.State != ActivationState.Valid)
{
// Do nothing: don't collect, don't reschedule.
}
else if (activation.ShouldBeKeptAlive)
{
// do nothing
}
else if (!activation.IsInactive)
{
// do nothing
}
else
{
if (activation.GetIdleness(now) >= ageLimit)
{
if (bucket.TryRemove(activation))
{
// we removed the activation from the collector. it's our responsibility to deactivate it.
activation.PrepareForDeactivation();
DecideToCollectActivation(activation, ref result);
}
// someone else has already deactivated the activation, so there's nothing to do.
}
else
{
// activation is not idle long enough for collection. do nothing.
}
}
}
++j;
}
++i;
}
return result ?? nothing;
}
private void DecideToCollectActivation(ActivationData activation, ref List<ActivationData> condemned)
{
if (null == condemned)
{
condemned = new List<ActivationData> { activation };
}
else
{
condemned.Add(activation);
}
this.Debug_OnDecideToCollectActivation?.Invoke(activation.Grain);
}
private static void ThrowIfTicketIsInvalid(DateTime ticket, TimeSpan quantum)
{
ThrowIfDefault(ticket, "ticket");
if (0 != ticket.Ticks % quantum.Ticks)
{
throw new ArgumentException(string.Format("invalid ticket ({0})", ticket));
}
}
private void ThrowIfTicketIsInvalid(DateTime ticket)
{
ThrowIfTicketIsInvalid(ticket, quantum);
}
private void ThrowIfExemptFromCollection(ActivationData activation, string name)
{
if (activation.IsExemptFromCollection)
{
throw new ArgumentException(string.Format("{0} should not refer to a system target or system grain.", name), name);
}
}
private bool IsExpired(DateTime ticket)
{
return ticket < nextTicket;
}
private DateTime MakeTicketFromDateTime(DateTime timestamp)
{
// round the timestamp to the next quantum. e.g. if the quantum is 1 minute and the timestamp is 3:45:22, then the ticket will be 3:46. note that TimeStamp.Ticks and DateTime.Ticks both return a long.
DateTime ticket = new DateTime(((timestamp.Ticks - 1) / quantum.Ticks + 1) * quantum.Ticks, DateTimeKind.Utc);
if (ticket < nextTicket)
{
throw new ArgumentException(string.Format("The earliest collection that can be scheduled from now is for {0}", new DateTime(nextTicket.Ticks - quantum.Ticks + 1, DateTimeKind.Utc)));
}
return ticket;
}
private DateTime MakeTicketFromTimeSpan(TimeSpan timeout)
{
if (timeout < quantum)
{
throw new ArgumentException(String.Format("timeout must be at least {0}, but it is {1}", quantum, timeout), "timeout");
}
return MakeTicketFromDateTime(DateTime.UtcNow + timeout);
}
private void Add(ActivationData item, DateTime ticket)
{
// note: we expect the activation lock to be held.
item.ResetCollectionCancelledFlag();
Bucket bucket =
buckets.GetOrAdd(
ticket,
key =>
new Bucket(key, quantum));
bucket.Add(item);
item.SetCollectionTicket(ticket);
}
static private void ThrowIfDefault<T>(T value, string name) where T : IEquatable<T>
{
if (value.Equals(default(T)))
{
throw new ArgumentException(string.Format("default({0}) is not allowed in this context.", typeof(T).Name), name);
}
}
private class Bucket : IEnumerable<ActivationData>
{
private readonly DateTime key;
private readonly ConcurrentDictionary<ActivationId, ActivationData> items;
public DateTime Key { get { return key; } }
public int ApproximateCount { get { return items.Count; } }
public Bucket(DateTime key, TimeSpan quantum)
{
ThrowIfTicketIsInvalid(key, quantum);
this.key = key;
items = new ConcurrentDictionary<ActivationId, ActivationData>();
}
public void Add(ActivationData item)
{
if (!items.TryAdd(item.ActivationId, item))
{
throw new InvalidOperationException("item is already associated with this bucket");
}
}
public bool TryRemove(ActivationData item)
{
if (!item.TrySetCollectionCancelledFlag()) return false;
return items.TryRemove(item.ActivationId, out ActivationData unused);
}
public IEnumerable<ActivationData> CancelAll()
{
List<ActivationData> result = null;
foreach (var pair in items)
{
// attempt to cancel the item. if we succeed, it wasn't already cancelled and we can return it. otherwise, we silently ignore it.
if (pair.Value.TrySetCollectionCancelledFlag())
{
if (result == null)
{
// we only need to ensure there's enough space left for this element and any potential entries.
result = new List<ActivationData>();
}
result.Add(pair.Value);
}
}
return result ?? nothing;
}
public IEnumerator<ActivationData> GetEnumerator()
{
return items.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
#if DEV14_OR_LATER
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
#endif
namespace Microsoft.VisualStudioTools.Project {
internal abstract class ReferenceNode : HierarchyNode {
internal delegate void CannotAddReferenceErrorMessage();
#region ctors
/// <summary>
/// constructor for the ReferenceNode
/// </summary>
protected ReferenceNode(ProjectNode root, ProjectElement element)
: base(root, element) {
this.ExcludeNodeFromScc = true;
}
/// <summary>
/// constructor for the ReferenceNode
/// </summary>
internal ReferenceNode(ProjectNode root)
: base(root) {
this.ExcludeNodeFromScc = true;
}
#endregion
#region overridden properties
public override int MenuCommandId {
get { return VsMenus.IDM_VS_CTXT_REFERENCE; }
}
public override Guid ItemTypeGuid {
get { return Guid.Empty; }
}
public override string Url {
get {
return String.Empty;
}
}
public override string Caption {
get {
return String.Empty;
}
}
#endregion
#region overridden methods
protected override NodeProperties CreatePropertiesObject() {
return new ReferenceNodeProperties(this);
}
/// <summary>
/// Get an instance of the automation object for ReferenceNode
/// </summary>
/// <returns>An instance of Automation.OAReferenceItem type if succeeded</returns>
public override object GetAutomationObject() {
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return null;
}
return new Automation.OAReferenceItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Disable inline editing of Caption of a ReferendeNode
/// </summary>
/// <returns>null</returns>
public override string GetEditLabel() {
return null;
}
#if DEV14_OR_LATER
protected override bool SupportsIconMonikers {
get { return true; }
}
protected override ImageMoniker GetIconMoniker(bool open) {
return CanShowDefaultIcon() ? KnownMonikers.Reference : KnownMonikers.ReferenceWarning;
}
#else
public override int ImageIndex {
get {
return ProjectMgr.GetIconIndex(CanShowDefaultIcon() ?
ProjectNode.ImageName.Reference :
ProjectNode.ImageName.DanglingReference
);
}
}
#endif
/// <summary>
/// Not supported.
/// </summary>
internal override int ExcludeFromProject() {
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
public override bool Remove(bool removeFromStorage) {
ReferenceContainerNode parent = Parent as ReferenceContainerNode;
if (base.Remove(removeFromStorage)) {
if (parent != null) {
parent.FireChildRemoved(this);
}
return true;
}
return false;
}
/// <summary>
/// References node cannot be dragged.
/// </summary>
/// <returns>A stringbuilder.</returns>
protected internal override string PrepareSelectedNodesForClipBoard() {
return null;
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
if ((VsCommands2K)cmd == VsCommands2K.QUICKOBJECTSEARCH) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
} else {
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
if ((VsCommands2K)cmd == VsCommands2K.QUICKOBJECTSEARCH) {
return this.ShowObjectBrowser();
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
protected internal override void ShowDeleteMessage(IList<HierarchyNode> nodes, __VSDELETEITEMOPERATION action, out bool cancel, out bool useStandardDialog) {
// Don't prompt if all the nodes are references
useStandardDialog = !nodes.All(n => n is ReferenceNode);
cancel = false;
}
#endregion
#region methods
/// <summary>
/// Links a reference node to the project and hierarchy.
/// </summary>
public virtual void AddReference() {
ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread();
ReferenceContainerNode referencesFolder = this.ProjectMgr.GetReferenceContainer() as ReferenceContainerNode;
Utilities.CheckNotNull(referencesFolder, "Could not find the References node");
CannotAddReferenceErrorMessage referenceErrorMessageHandler = null;
if (!this.CanAddReference(out referenceErrorMessageHandler)) {
if (referenceErrorMessageHandler != null) {
referenceErrorMessageHandler.DynamicInvoke(new object[] { });
}
return;
}
// Link the node to the project file.
this.BindReferenceData();
// At this point force the item to be refreshed
this.ItemNode.RefreshProperties();
referencesFolder.AddChild(this);
return;
}
/// <summary>
/// Refreshes a reference by re-resolving it and redrawing the icon.
/// </summary>
internal virtual void RefreshReference() {
this.ResolveReference();
ProjectMgr.ReDrawNode(this, UIHierarchyElement.Icon);
}
/// <summary>
/// Resolves references.
/// </summary>
protected virtual void ResolveReference() {
}
/// <summary>
/// Validates that a reference can be added.
/// </summary>
/// <param name="errorHandler">A CannotAddReferenceErrorMessage delegate to show the error message.</param>
/// <returns>true if the reference can be added.</returns>
protected virtual bool CanAddReference(out CannotAddReferenceErrorMessage errorHandler) {
// When this method is called this refererence has not yet been added to the hierarchy, only instantiated.
errorHandler = null;
if (this.IsAlreadyAdded()) {
return false;
}
return true;
}
/// <summary>
/// Checks if a reference is already added. The method parses all references and compares the Url.
/// </summary>
/// <returns>true if the assembly has already been added.</returns>
protected virtual bool IsAlreadyAdded() {
ReferenceContainerNode referencesFolder = this.ProjectMgr.GetReferenceContainer() as ReferenceContainerNode;
Utilities.CheckNotNull(referencesFolder, "Could not find the References node");
for (HierarchyNode n = referencesFolder.FirstChild; n != null; n = n.NextSibling) {
ReferenceNode refererenceNode = n as ReferenceNode;
if (null != refererenceNode) {
// We check if the Url of the assemblies is the same.
if (CommonUtils.IsSamePath(refererenceNode.Url, this.Url)) {
return true;
}
}
}
return false;
}
/// <summary>
/// Shows the Object Browser
/// </summary>
/// <returns></returns>
protected virtual int ShowObjectBrowser() {
if (!File.Exists(this.Url)) {
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
// Request unmanaged code permission in order to be able to create the unmanaged memory representing the guid.
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
Guid guid = VSConstants.guidCOMPLUSLibrary;
IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(guid.ToByteArray().Length);
System.Runtime.InteropServices.Marshal.StructureToPtr(guid, ptr, false);
int returnValue = VSConstants.S_OK;
try {
VSOBJECTINFO[] objInfo = new VSOBJECTINFO[1];
objInfo[0].pguidLib = ptr;
objInfo[0].pszLibName = this.Url;
IVsObjBrowser objBrowser = this.ProjectMgr.Site.GetService(typeof(SVsObjBrowser)) as IVsObjBrowser;
ErrorHandler.ThrowOnFailure(objBrowser.NavigateTo(objInfo, 0));
} catch (COMException e) {
Trace.WriteLine("Exception" + e.ErrorCode);
returnValue = e.ErrorCode;
} finally {
if (ptr != IntPtr.Zero) {
System.Runtime.InteropServices.Marshal.FreeCoTaskMem(ptr);
}
}
return returnValue;
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject) {
return true;
}
return false;
}
protected abstract void BindReferenceData();
#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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeRefactorings.ExtractMethod;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ExtractMethod
{
public class ExtractMethodTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new ExtractMethodCodeRefactoringProvider();
[WorkItem(540799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestPartialSelection()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine([|b != true|] ? b = true : b = false);
}
}",
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false);
}
private static bool NewMethod(bool b)
{
return b != true;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestUseExpressionBodyWhenPossible()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine([|b != true|] ? b = true : b = false);
}
}",
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false);
}
private static bool NewMethod(bool b) => b != true;
}",
options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine([|b != true|] ? b = true : b = false);
}
}",
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false);
}
private static bool NewMethod(bool b) => b != true;
}",
options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithNoneEnforcement));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine2()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine(
[|b != true|]
? b = true : b = false);
}
}",
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine(
{|Rename:NewMethod|}(b)
? b = true : b = false);
}
private static bool NewMethod(bool b) => b != true;
}",
options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithNoneEnforcement));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine([|b !=
true|] ? b = true : b = false);
}
}",
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false);
}
private static bool NewMethod(bool b)
{
return b !=
true;
}
}",
options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithNoneEnforcement));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine2()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine([|b !=/*
*/true|] ? b = true : b = false);
}
}",
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false);
}
private static bool NewMethod(bool b)
{
return b !=/*
*/true;
}
}",
options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithNoneEnforcement));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine3()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine([|"""" != @""
""|] ? b = true : b = false);
}
}",
@"class Program
{
static void Main(string[] args)
{
bool b = true;
System.Console.WriteLine({|Rename:NewMethod|}() ? b = true : b = false);
}
private static bool NewMethod()
{
return """" != @""
"";
}
}",
options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithNoneEnforcement));
}
[WorkItem(540796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540796")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestReadOfDataThatDoesNotFlowIn()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
int x = 1;
object y = 0;
[|int s = true ? fun(x) : fun(y);|]
}
private static T fun<T>(T t)
{
return t;
}
}",
@"class Program
{
static void Main(string[] args)
{
int x = 1;
object y = 0;
{|Rename:NewMethod|}(x, y);
}
private static void NewMethod(int x, object y)
{
int s = true ? fun(x) : fun(y);
}
private static T fun<T>(T t)
{
return t;
}
}");
}
[WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestMissingOnGoto()
{
await TestMissingInRegularAndScriptAsync(
@"delegate int del(int i);
class C
{
static void Main(string[] args)
{
del q = x => {
[|goto label2;
return x * x;|]
};
label2:
return;
}
}");
}
[WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestOnStatementAfterUnconditionalGoto()
{
await TestInRegularAndScriptAsync(
@"delegate int del(int i);
class C
{
static void Main(string[] args)
{
del q = x => {
goto label2;
[|return x * x;|]
};
label2:
return;
}
}",
@"delegate int del(int i);
class C
{
static void Main(string[] args)
{
del q = x => {
goto label2;
return {|Rename:NewMethod|}(x);
};
label2:
return;
}
private static int NewMethod(int x)
{
return x * x;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestMissingOnNamespace()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void Main()
{
[|System|].Console.WriteLine(4);
}
}",
@"class Program
{
void Main()
{
{|Rename:NewMethod|}();
}
private static void NewMethod()
{
System.Console.WriteLine(4);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestMissingOnType()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void Main()
{
[|System.Console|].WriteLine(4);
}
}",
@"class Program
{
void Main()
{
{|Rename:NewMethod|}();
}
private static void NewMethod()
{
System.Console.WriteLine(4);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestMissingOnBase()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void Main()
{
[|base|].ToString();
}
}",
@"class Program
{
void Main()
{
{|Rename:NewMethod|}();
}
private void NewMethod()
{
base.ToString();
}
}");
}
[WorkItem(545623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestOnActionInvocation()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public static Action X { get; set; }
}
class Program
{
void Main()
{
[|C.X|]();
}
}",
@"using System;
class C
{
public static Action X { get; set; }
}
class Program
{
void Main()
{
{|Rename:GetX|}()();
}
private static Action GetX()
{
return C.X;
}
}");
}
[WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task DisambiguateCallSiteIfNecessary1()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main()
{
byte z = 0;
Foo([|x => 0|], y => 0, z, z);
}
static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); }
static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); }
}",
@"using System;
class Program
{
static void Main()
{
byte z = 0;
Foo<byte, byte>({|Rename:NewMethod|}(), y => 0, z, z);
}
private static Func<byte, byte> NewMethod()
{
return x => 0;
}
static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); }
static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); }
}",
ignoreTrivia: false);
}
[WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task DisambiguateCallSiteIfNecessary2()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main()
{
byte z = 0;
Foo([|x => 0|], y => { return 0; }, z, z);
}
static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); }
static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); }
}",
@"using System;
class Program
{
static void Main()
{
byte z = 0;
Foo<byte, byte>({|Rename:NewMethod|}(), y => { return 0; }, z, z);
}
private static Func<byte, byte> NewMethod()
{
return x => 0;
}
static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); }
static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); }
}",
ignoreTrivia: false);
}
[WorkItem(530709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530709")]
[WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task DontOverparenthesize()
{
await TestAsync(
@"using System;
static class C
{
static void Ex(this string x)
{
}
static void Inner(Action<string> x, string y)
{
}
static void Inner(Action<string> x, int y)
{
}
static void Inner(Action<int> x, int y)
{
}
static void Outer(Action<string> x, object y)
{
Console.WriteLine(1);
}
static void Outer(Action<int> x, int y)
{
Console.WriteLine(2);
}
static void Main()
{
Outer(y => Inner(x => [|x|].Ex(), y), - -1);
}
}
static class E
{
public static void Ex(this int x)
{
}
}",
@"using System;
static class C
{
static void Ex(this string x)
{
}
static void Inner(Action<string> x, string y)
{
}
static void Inner(Action<string> x, int y)
{
}
static void Inner(Action<int> x, int y)
{
}
static void Outer(Action<string> x, object y)
{
Console.WriteLine(1);
}
static void Outer(Action<int> x, int y)
{
Console.WriteLine(2);
}
static void Main()
{
Outer(y => Inner(x => {|Rename:GetX|}(x).Ex(), y), (object)- -1);
}
private static string GetX(string x)
{
return x;
}
}
static class E
{
public static void Ex(this int x)
{
}
}",
parseOptions: Options.Regular);
}
[WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task DontOverparenthesizeGenerics()
{
await TestAsync(
@"using System;
static class C
{
static void Ex<T>(this string x)
{
}
static void Inner(Action<string> x, string y)
{
}
static void Inner(Action<string> x, int y)
{
}
static void Inner(Action<int> x, int y)
{
}
static void Outer(Action<string> x, object y)
{
Console.WriteLine(1);
}
static void Outer(Action<int> x, int y)
{
Console.WriteLine(2);
}
static void Main()
{
Outer(y => Inner(x => [|x|].Ex<int>(), y), - -1);
}
}
static class E
{
public static void Ex<T>(this int x)
{
}
}",
@"using System;
static class C
{
static void Ex<T>(this string x)
{
}
static void Inner(Action<string> x, string y)
{
}
static void Inner(Action<string> x, int y)
{
}
static void Inner(Action<int> x, int y)
{
}
static void Outer(Action<string> x, object y)
{
Console.WriteLine(1);
}
static void Outer(Action<int> x, int y)
{
Console.WriteLine(2);
}
static void Main()
{
Outer(y => Inner(x => {|Rename:GetX|}(x).Ex<int>(), y), (object)- -1);
}
private static string GetX(string x)
{
return x;
}
}
static class E
{
public static void Ex<T>(this int x)
{
}
}",
parseOptions: Options.Regular);
}
[WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task PreserveCommentsBeforeDeclaration_1()
{
await TestInRegularAndScriptAsync(
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
[|Construct obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
Construct obj2 = new Construct();
obj2.Do();|]
obj1.Do();
obj2.Do();
}
}",
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
Construct obj1, obj2;
{|Rename:NewMethod|}(out obj1, out obj2);
obj1.Do();
obj2.Do();
}
private static void NewMethod(out Construct obj1, out Construct obj2)
{
obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
obj2 = new Construct();
obj2.Do();
}
}",
ignoreTrivia: false);
}
[WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task PreserveCommentsBeforeDeclaration_2()
{
await TestInRegularAndScriptAsync(
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
[|Construct obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
Construct obj2 = new Construct();
obj2.Do();
/* Second Interesting comment. */
Construct obj3 = new Construct();
obj3.Do();|]
obj1.Do();
obj2.Do();
obj3.Do();
}
}",
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
Construct obj1, obj2, obj3;
{|Rename:NewMethod|}(out obj1, out obj2, out obj3);
obj1.Do();
obj2.Do();
obj3.Do();
}
private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3)
{
obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
obj2 = new Construct();
obj2.Do();
/* Second Interesting comment. */
obj3 = new Construct();
obj3.Do();
}
}",
ignoreTrivia: false);
}
[WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task PreserveCommentsBeforeDeclaration_3()
{
await TestInRegularAndScriptAsync(
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
[|Construct obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
Construct obj2 = new Construct(), obj3 = new Construct();
obj2.Do();
obj3.Do();|]
obj1.Do();
obj2.Do();
obj3.Do();
}
}",
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
Construct obj1, obj2, obj3;
{|Rename:NewMethod|}(out obj1, out obj2, out obj3);
obj1.Do();
obj2.Do();
obj3.Do();
}
private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3)
{
obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
obj2 = new Construct();
obj3 = new Construct();
obj2.Do();
obj3.Do();
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTuple()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
[|(int, int) x = (1, 2);|]
System.Console.WriteLine(x.Item1);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program
{
static void Main(string[] args)
{
(int, int) x = {|Rename:NewMethod|}();
System.Console.WriteLine(x.Item1);
}
private static (int, int) NewMethod()
{
return (1, 2);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleDeclarationWithNames()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
[|(int a, int b) x = (1, 2);|]
System.Console.WriteLine(x.a);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program
{
static void Main(string[] args)
{
(int a, int b) x = {|Rename:NewMethod|}();
System.Console.WriteLine(x.a);
}
private static (int a, int b) NewMethod()
{
return (1, 2);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleDeclarationWithSomeNames()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
[|(int a, int) x = (1, 2);|]
System.Console.WriteLine(x.a);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program
{
static void Main(string[] args)
{
(int a, int) x = {|Rename:NewMethod|}();
System.Console.WriteLine(x.a);
}
private static (int a, int) NewMethod()
{
return (1, 2);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
public async Task TestTupleWith1Arity()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
ValueTuple<int> y = ValueTuple.Create(1);
[|y.Item1.ToString();|]
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"using System;
class Program
{
static void Main(string[] args)
{
ValueTuple<int> y = ValueTuple.Create(1);
{|Rename:NewMethod|}(y);
}
private static void NewMethod(ValueTuple<int> y)
{
y.Item1.ToString();
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleLiteralWithNames()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
[|(int, int) x = (a: 1, b: 2);|]
System.Console.WriteLine(x.Item1);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program
{
static void Main(string[] args)
{
(int, int) x = {|Rename:NewMethod|}();
System.Console.WriteLine(x.Item1);
}
private static (int, int) NewMethod()
{
return (a: 1, b: 2);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleDeclarationAndLiteralWithNames()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
[|(int a, int b) x = (c: 1, d: 2);|]
System.Console.WriteLine(x.a);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program
{
static void Main(string[] args)
{
(int a, int b) x = {|Rename:NewMethod|}();
System.Console.WriteLine(x.a);
}
private static (int a, int b) NewMethod()
{
return (c: 1, d: 2);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleIntoVar()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
[|var x = (c: 1, d: 2);|]
System.Console.WriteLine(x.c);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program
{
static void Main(string[] args)
{
(int c, int d) x = {|Rename:NewMethod|}();
System.Console.WriteLine(x.c);
}
private static (int c, int d) NewMethod()
{
return (c: 1, d: 2);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task RefactorWithoutSystemValueTuple()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
[|var x = (c: 1, d: 2);|]
System.Console.WriteLine(x.c);
}
}",
@"class Program
{
static void Main(string[] args)
{
(int c, int d) x = {|Rename:NewMethod|}();
System.Console.WriteLine(x.c);
}
private static (int c, int d) NewMethod()
{
return (c: 1, d: 2);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleWithNestedNamedTuple()
{
// This is not the best refactoring, but this is an edge case
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
[|var x = new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world""));|]
System.Console.WriteLine(x.c);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program
{
static void Main(string[] args)
{
(int, int, int, int, int, int, int, string, string) x = {|Rename:NewMethod|}();
System.Console.WriteLine(x.c);
}
private static (int, int, int, int, int, int, int, string, string) NewMethod()
{
return new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world""));
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
public async Task TestDeconstruction()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
var (x, y) = [|(1, 2)|];
System.Console.WriteLine(x);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program
{
static void Main(string[] args)
{
var (x, y) = {|Rename:NewMethod|}();
System.Console.WriteLine(x);
}
private static (int, int) NewMethod()
{
return (1, 2);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
public async Task TestDeconstruction2()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
var (x, y) = (1, 2);
var z = [|3;|]
System.Console.WriteLine(z);
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program
{
static void Main(string[] args)
{
var (x, y) = (1, 2);
int z = {|Rename:NewMethod|}();
System.Console.WriteLine(z);
}
private static int NewMethod()
{
return 3;
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
[Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.OutVar)]
public async Task TestOutVar()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M(int i)
{
int r;
[|r = M1(out int y, i);|]
System.Console.WriteLine(r + y);
}
}",
@"class C
{
static void M(int i)
{
int r;
int y;
{|Rename:NewMethod|}(i, out r, out y);
System.Console.WriteLine(r + y);
}
private static void NewMethod(int i, out int r, out int y)
{
r = M1(out y, i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
[Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)]
public async Task TestIsPattern()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M(int i)
{
int r;
[|r = M1(3 is int y, i);|]
System.Console.WriteLine(r + y);
}
}",
@"class C
{
static void M(int i)
{
int r;
int y;
{|Rename:NewMethod|}(i, out r, out y);
System.Console.WriteLine(r + y);
}
private static void NewMethod(int i, out int r, out int y)
{
r = M1(3 is int {|Conflict:y|}, i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
[Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)]
public async Task TestOutVarAndIsPattern()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
int r;
[|r = M1(out /*out*/ int /*int*/ y /*y*/) + M2(3 is int z);|]
System.Console.WriteLine(r + y + z);
}
} ",
@"class C
{
static void M()
{
int r;
int y, z;
{|Rename:NewMethod|}(out r, out y, out z);
System.Console.WriteLine(r + y + z);
}
private static void NewMethod(out int r, out int y, out int z)
{
r = M1(out /*out*/ /*int*/ y /*y*/) + M2(3 is int {|Conflict:z|});
}
} ",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
[Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)]
public async Task ConflictingOutVarLocals()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
int r;
[|r = M1(out int y);
{
M2(out int y);
System.Console.Write(y);
}|]
System.Console.WriteLine(r + y);
}
}",
@"class C
{
static void M()
{
int r;
int y;
{|Rename:NewMethod|}(out r, out y);
System.Console.WriteLine(r + y);
}
private static void NewMethod(out int r, out int y)
{
r = M1(out y);
{
M2(out int y);
System.Console.Write(y);
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
[Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)]
public async Task ConflictingPatternLocals()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
int r;
[|r = M1(1 is int y);
{
M2(2 is int y);
System.Console.Write(y);
}|]
System.Console.WriteLine(r + y);
}
}",
@"class C
{
static void M()
{
int r;
int y;
{|Rename:NewMethod|}(out r, out y);
System.Console.WriteLine(r + y);
}
private static void NewMethod(out int r, out int y)
{
r = M1(1 is int {|Conflict:y|});
{
M2(2 is int y);
System.Console.Write(y);
}
}
}");
}
[WorkItem(15218, "https://github.com/dotnet/roslyn/issues/15218")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestCancellationTokenGoesLast()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading;
class C
{
void M(CancellationToken ct)
{
var v = 0;
[|if (true)
{
ct.ThrowIfCancellationRequested();
Console.WriteLine(v);
}|]
}
}",
@"using System;
using System.Threading;
class C
{
void M(CancellationToken ct)
{
var v = 0;
{|Rename:NewMethod|}(v, ct);
}
private static void NewMethod(int v, CancellationToken ct)
{
if (true)
{
ct.ThrowIfCancellationRequested();
Console.WriteLine(v);
}
}
}");
}
[WorkItem(15219, "https://github.com/dotnet/roslyn/issues/15219")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestUseVar1()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void Foo(int i)
{
[|var v = (string)null;
switch (i)
{
case 0: v = ""0""; break;
case 1: v = ""1""; break;
}|]
Console.WriteLine(v);
}
}",
@"using System;
class C
{
void Foo(int i)
{
var v = {|Rename:NewMethod|}(i);
Console.WriteLine(v);
}
private static string NewMethod(int i)
{
var v = (string)null;
switch (i)
{
case 0: v = ""0""; break;
case 1: v = ""1""; break;
}
return v;
}
}", options: Option(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, CodeStyleOptions.TrueWithSuggestionEnforcement));
}
[WorkItem(15219, "https://github.com/dotnet/roslyn/issues/15219")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestUseVar2()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void Foo(int i)
{
[|var v = (string)null;
switch (i)
{
case 0: v = ""0""; break;
case 1: v = ""1""; break;
}|]
Console.WriteLine(v);
}
}",
@"using System;
class C
{
void Foo(int i)
{
string v = {|Rename:NewMethod|}(i);
Console.WriteLine(v);
}
private static string NewMethod(int i)
{
var v = (string)null;
switch (i)
{
case 0: v = ""0""; break;
case 1: v = ""1""; break;
}
return v;
}
}", options: Option(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, CodeStyleOptions.TrueWithSuggestionEnforcement));
}
[Fact]
[WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")]
public async Task ExtractLocalFunctionCall()
{
await TestInRegularAndScriptAsync(@"
class C
{
public static void Main()
{
void Local() { }
[|Local();|]
}
}", @"
class C
{
public static void Main()
{
void Local() { }
{|Rename:NewMethod|}();
}
private static void NewMethod()
{
{|Warning:Local();|}
}
}");
}
[Fact]
[WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")]
public async Task ExtractLocalFunctionCallWithCapture()
{
await TestInRegularAndScriptAsync(@"
class C
{
public static void Main(string[] args)
{
bool Local() => args == null;
[|Local();|]
}
}", @"
class C
{
public static void Main(string[] args)
{
bool Local() => args == null;
{|Rename:NewMethod|}();
}
private static void NewMethod()
{
{|Warning:Local();|}
}
}");
}
[Fact]
[WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")]
public async Task ExtractLocalFunctionDeclaration()
{
await TestMissingInRegularAndScriptAsync(@"
class C
{
public static void Main()
{
[|bool Local() => args == null;|]
Local();
}
}");
}
[Fact]
[WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")]
public async Task ExtractLocalFunctionInterior()
{
await TestInRegularAndScriptAsync(@"
class C
{
public static void Main()
{
void Local()
{
[|int x = 0;
x++;|]
}
Local();
}
}", @"
class C
{
public static void Main()
{
void Local()
{
{|Rename:NewMethod|}();
}
Local();
}
private static void NewMethod()
{
{|Warning:int x = 0;
x++;|}
}
}");
}
[WorkItem(538229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task Bug3790()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void method()
{
static void Main(string[] args)
{
int v = 0;
for(int i=0 ; i<5; i++)
{
[|v = v + i;|]
}
}
}
}", @"
class Test
{
void method()
{
static void Main(string[] args)
{
int v = 0;
for(int i=0 ; i<5; i++)
{
{|Rename:NewMethod|}();
}
}
}
private static void NewMethod()
{
{|Warning:v = v + i|};
}
}");
}
[WorkItem(538229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task Bug3790_1()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void method()
{
static void Main(string[] args)
{
int v = 0;
for(int i=0 ; i<5; i++)
{
[|v = v + i|];
}
}
}
}", @"
class Test
{
void method()
{
static void Main(string[] args)
{
int v = 0;
for(int i=0 ; i<5; i++)
{
v = {|Rename:NewMethod|}();
}
}
}
private static int NewMethod()
{
{|Warning:return v + i|};
}
}");
}
[WorkItem(538229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task Bug3790_2()
{
await TestInRegularAndScriptAsync(@"
class Test
{
void method()
{
static void Main(string[] args)
{
int v = 0;
for(int i=0 ; i<5; i++)
{
[|i = v = v + i|];
}
}
}
}", @"
class Test
{
void method()
{
static void Main(string[] args)
{
int v = 0;
for(int i=0 ; i<5; i++)
{
i = {|Rename:NewMethod|}();
}
}
}
private static int NewMethod()
{
{|Warning:return v = v + i;|}
}
}");
}
[WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task TestExpressionBodyProperty()
{
await TestInRegularAndScriptAsync(@"
class Program
{
int field;
public int Blah => [|this.field|];
}",
@"
class Program
{
int field;
public int Blah => {|Rename:GetField|}();
private int GetField()
{
return this.field;
}
}");
}
[WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task TestExpressionBodyIndexer()
{
await TestInRegularAndScriptAsync(@"
class Program
{
int field;
public int this[int i] => [|this.field|];
}",
@"
class Program
{
int field;
public int this[int i] => {|Rename:GetField|}();
private int GetField()
{
return this.field;
}
}");
}
[WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task TestExpressionBodyPropertyGetAccessor()
{
await TestInRegularAndScriptAsync(@"
class Program
{
int field;
public int Blah
{
get => [|this.field|];
set => field = value;
}
}",
@"
class Program
{
int field;
public int Blah
{
get => {|Rename:GetField|}();
set => field = value;
}
private int GetField()
{
return this.field;
}
}");
}
[WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task TestExpressionBodyPropertySetAccessor()
{
await TestInRegularAndScriptAsync(@"
class Program
{
int field;
public int Blah
{
get => this.field;
set => field = [|value|];
}
}",
@"
class Program
{
int field;
public int Blah
{
get => this.field;
set => field = {|Rename:GetValue|}(value);
}
private static int GetValue(int value)
{
return value;
}
}");
}
[WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task TestExpressionBodyIndexerGetAccessor()
{
await TestInRegularAndScriptAsync(@"
class Program
{
int field;
public int this[int i]
{
get => [|this.field|];
set => field = value;
}
}",
@"
class Program
{
int field;
public int this[int i]
{
get => {|Rename:GetField|}();
set => field = value;
}
private int GetField()
{
return this.field;
}
}");
}
[WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task TestExpressionBodyIndexerSetAccessor()
{
await TestInRegularAndScriptAsync(@"
class Program
{
int field;
public int this[int i]
{
get => this.field;
set => field = [|value|];
}
}",
@"
class Program
{
int field;
public int this[int i]
{
get => this.field;
set => field = {|Rename:GetValue|}(value);
}
private static int GetValue(int value)
{
return value;
}
}");
}
}
}
| |
//
// decl.cs: Declaration base class for structs, classes, enums and interfaces.
//
// Author: Miguel de Icaza (miguel@gnu.org)
// Marek Safar (marek.safar@seznam.cz)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001 Ximian, Inc (http://www.ximian.com)
// Copyright 2004-2008 Novell, Inc
// Copyright 2011 Xamarin Inc
//
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Mono.CompilerServices.SymbolWriter;
#if NET_2_1
using XmlElement = System.Object;
#else
using System.Xml;
#endif
#if STATIC
using IKVM.Reflection;
using IKVM.Reflection.Emit;
#else
using System.Reflection;
using System.Reflection.Emit;
#endif
namespace Mono.CSharp {
//
// Better name would be DottenName
//
[DebuggerDisplay ("{GetSignatureForError()}")]
public class MemberName
{
public static readonly MemberName Null = new MemberName ("");
public readonly string Name;
public TypeParameters TypeParameters;
public readonly FullNamedExpression ExplicitInterface;
public readonly Location Location;
public readonly MemberName Left;
public MemberName (string name)
: this (name, Location.Null)
{ }
#if FULL_AST
public Location DotLocation {
get;
set;
}
#endif
public MemberName (string name, Location loc)
: this (null, name, loc)
{ }
public MemberName (string name, TypeParameters tparams, Location loc)
{
this.Name = name;
this.Location = loc;
this.TypeParameters = tparams;
}
public MemberName (string name, TypeParameters tparams, FullNamedExpression explicitInterface, Location loc)
: this (name, tparams, loc)
{
this.ExplicitInterface = explicitInterface;
}
public MemberName (MemberName left, string name, Location loc)
{
this.Name = name;
this.Location = loc;
this.Left = left;
}
public MemberName (MemberName left, string name, FullNamedExpression explicitInterface, Location loc)
: this (left, name, loc)
{
this.ExplicitInterface = explicitInterface;
}
public MemberName (MemberName left, MemberName right)
{
this.Name = right.Name;
this.Location = right.Location;
this.TypeParameters = right.TypeParameters;
this.Left = left;
}
public int Arity {
get {
return TypeParameters == null ? 0 : TypeParameters.Count;
}
}
public bool IsGeneric {
get {
return TypeParameters != null;
}
}
public string Basename {
get {
if (TypeParameters != null)
return MakeName (Name, TypeParameters);
return Name;
}
}
public void CreateMetadataName (StringBuilder sb)
{
if (Left != null)
Left.CreateMetadataName (sb);
if (sb.Length != 0) {
sb.Append (".");
}
sb.Append (Basename);
}
public string GetSignatureForDocumentation ()
{
var s = Basename;
if (ExplicitInterface != null)
s = ExplicitInterface.GetSignatureForError () + "." + s;
if (Left == null)
return s;
return Left.GetSignatureForDocumentation () + "." + s;
}
public string GetSignatureForError ()
{
string s = TypeParameters == null ? null : "<" + TypeParameters.GetSignatureForError () + ">";
s = Name + s;
if (ExplicitInterface != null)
s = ExplicitInterface.GetSignatureForError () + "." + s;
if (Left == null)
return s;
return Left.GetSignatureForError () + "." + s;
}
public override bool Equals (object other)
{
return Equals (other as MemberName);
}
public bool Equals (MemberName other)
{
if (this == other)
return true;
if (other == null || Name != other.Name)
return false;
if ((TypeParameters != null) &&
(other.TypeParameters == null || TypeParameters.Count != other.TypeParameters.Count))
return false;
if ((TypeParameters == null) && (other.TypeParameters != null))
return false;
if (Left == null)
return other.Left == null;
return Left.Equals (other.Left);
}
public override int GetHashCode ()
{
int hash = Name.GetHashCode ();
for (MemberName n = Left; n != null; n = n.Left)
hash ^= n.Name.GetHashCode ();
if (TypeParameters != null)
hash ^= TypeParameters.Count << 5;
return hash & 0x7FFFFFFF;
}
public static string MakeName (string name, TypeParameters args)
{
if (args == null)
return name;
return name + "`" + args.Count;
}
public static string MakeName (string name, int count)
{
return name + "`" + count;
}
}
public class SimpleMemberName
{
public string Value;
public Location Location;
public SimpleMemberName (string name, Location loc)
{
this.Value = name;
this.Location = loc;
}
}
/// <summary>
/// Base representation for members. This is used to keep track
/// of Name, Location and Modifier flags, and handling Attributes.
/// </summary>
[System.Diagnostics.DebuggerDisplay ("{GetSignatureForError()}")]
public abstract class MemberCore : Attributable, IMemberContext, IMemberDefinition
{
string IMemberDefinition.Name {
get {
return member_name.Name;
}
}
// Is not readonly because of IndexerName attribute
private MemberName member_name;
public MemberName MemberName {
get { return member_name; }
}
/// <summary>
/// Modifier flags that the user specified in the source code
/// </summary>
private Modifiers mod_flags;
public Modifiers ModFlags {
set {
mod_flags = value;
if ((value & Modifiers.COMPILER_GENERATED) != 0)
caching_flags = Flags.IsUsed | Flags.IsAssigned;
}
get {
return mod_flags;
}
}
public virtual ModuleContainer Module {
get {
return Parent.Module;
}
}
public /*readonly*/ TypeContainer Parent;
/// <summary>
/// Location where this declaration happens
/// </summary>
public Location Location {
get { return member_name.Location; }
}
/// <summary>
/// XML documentation comment
/// </summary>
protected string comment;
/// <summary>
/// Represents header string for documentation comment
/// for each member types.
/// </summary>
public abstract string DocCommentHeader { get; }
[Flags]
public enum Flags {
Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
Obsolete = 1 << 1, // Type has obsolete attribute
ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
ClsCompliant = 1 << 3, // Type is CLS Compliant
CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
ClsCompliantAttributeFalse = 1 << 7, // Member has CLSCompliant(false)
Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
Excluded = 1 << 9, // Method is conditional
MethodOverloadsExist = 1 << 10, // Test for duplication must be performed
IsUsed = 1 << 11,
IsAssigned = 1 << 12, // Field is assigned
HasExplicitLayout = 1 << 13,
PartialDefinitionExists = 1 << 14, // Set when corresponding partial method definition exists
HasStructLayout = 1 << 15, // Has StructLayoutAttribute
HasInstanceConstructor = 1 << 16,
HasUserOperators = 1 << 17,
CanBeReused = 1 << 18
}
/// <summary>
/// MemberCore flags at first detected then cached
/// </summary>
internal Flags caching_flags;
public MemberCore (TypeContainer parent, MemberName name, Attributes attrs)
{
this.Parent = parent;
member_name = name;
caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
AddAttributes (attrs, this);
}
protected virtual void SetMemberName (MemberName new_name)
{
member_name = new_name;
}
public virtual void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
protected bool CheckAbstractAndExtern (bool has_block)
{
if (Parent.PartialContainer.Kind == MemberKind.Interface)
return true;
if (has_block) {
if ((ModFlags & Modifiers.EXTERN) != 0) {
Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
GetSignatureForError ());
return false;
}
if ((ModFlags & Modifiers.ABSTRACT) != 0) {
Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
GetSignatureForError ());
return false;
}
} else {
if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN | Modifiers.PARTIAL)) == 0 && !(Parent is Delegate)) {
if (Compiler.Settings.Version >= LanguageVersion.V_3) {
Property.PropertyMethod pm = this as Property.PropertyMethod;
if (pm is Indexer.GetIndexerMethod || pm is Indexer.SetIndexerMethod)
pm = null;
if (pm != null && pm.Property.AccessorSecond == null) {
Report.Error (840, Location,
"`{0}' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors",
GetSignatureForError ());
return false;
}
}
Report.Error (501, Location, "`{0}' must have a body because it is not marked abstract, extern, or partial",
GetSignatureForError ());
return false;
}
}
return true;
}
protected void CheckProtectedModifier ()
{
if ((ModFlags & Modifiers.PROTECTED) == 0)
return;
if (Parent.PartialContainer.Kind == MemberKind.Struct) {
Report.Error (666, Location, "`{0}': Structs cannot contain protected members",
GetSignatureForError ());
return;
}
if ((Parent.ModFlags & Modifiers.STATIC) != 0) {
Report.Error (1057, Location, "`{0}': Static classes cannot contain protected members",
GetSignatureForError ());
return;
}
if ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.OVERRIDE) == 0 &&
!(this is Destructor)) {
Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class",
GetSignatureForError ());
return;
}
}
public abstract bool Define ();
public virtual string DocComment {
get {
return comment;
}
set {
comment = value;
}
}
//
// Returns full member name for error message
//
public virtual string GetSignatureForError ()
{
var parent = Parent.GetSignatureForError ();
if (parent == null)
return member_name.GetSignatureForError ();
return parent + "." + member_name.GetSignatureForError ();
}
/// <summary>
/// Base Emit method. This is also entry point for CLS-Compliant verification.
/// </summary>
public virtual void Emit ()
{
if (!Compiler.Settings.VerifyClsCompliance)
return;
VerifyClsCompliance ();
}
public bool IsAvailableForReuse {
get {
return (caching_flags & Flags.CanBeReused) != 0;
}
set {
caching_flags = value ? (caching_flags | Flags.CanBeReused) : (caching_flags & ~Flags.CanBeReused);
}
}
public bool IsCompilerGenerated {
get {
if ((mod_flags & Modifiers.COMPILER_GENERATED) != 0)
return true;
return Parent == null ? false : Parent.IsCompilerGenerated;
}
}
public bool IsImported {
get {
return false;
}
}
public virtual bool IsUsed {
get {
return (caching_flags & Flags.IsUsed) != 0;
}
}
protected Report Report {
get {
return Compiler.Report;
}
}
public void SetIsUsed ()
{
caching_flags |= Flags.IsUsed;
}
public void SetIsAssigned ()
{
caching_flags |= Flags.IsAssigned;
}
public void SetConstraints (List<Constraints> constraints_list)
{
var tparams = member_name.TypeParameters;
if (tparams == null) {
Report.Error (80, Location, "Constraints are not allowed on non-generic declarations");
return;
}
foreach (var c in constraints_list) {
var tp = tparams.Find (c.TypeParameter.Value);
if (tp == null) {
Report.Error (699, c.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
GetSignatureForError (), c.TypeParameter.Value);
continue;
}
tp.Constraints = c;
}
}
/// <summary>
/// Returns instance of ObsoleteAttribute for this MemberCore
/// </summary>
public virtual ObsoleteAttribute GetAttributeObsolete ()
{
if ((caching_flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0)
return null;
caching_flags &= ~Flags.Obsolete_Undetected;
if (OptAttributes == null)
return null;
Attribute obsolete_attr = OptAttributes.Search (Module.PredefinedAttributes.Obsolete);
if (obsolete_attr == null)
return null;
caching_flags |= Flags.Obsolete;
ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
if (obsolete == null)
return null;
return obsolete;
}
/// <summary>
/// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
/// </summary>
public virtual void CheckObsoleteness (Location loc)
{
ObsoleteAttribute oa = GetAttributeObsolete ();
if (oa != null)
AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, Report);
}
//
// Checks whether the type P is as accessible as this member
//
public bool IsAccessibleAs (TypeSpec p)
{
//
// if M is private, its accessibility is the same as this declspace.
// we already know that P is accessible to T before this method, so we
// may return true.
//
if ((mod_flags & Modifiers.PRIVATE) != 0)
return true;
while (TypeManager.HasElementType (p))
p = TypeManager.GetElementType (p);
if (p.IsGenericParameter)
return true;
for (TypeSpec p_parent; p != null; p = p_parent) {
p_parent = p.DeclaringType;
if (p.IsGeneric) {
foreach (TypeSpec t in p.TypeArguments) {
if (!IsAccessibleAs (t))
return false;
}
}
var pAccess = p.Modifiers & Modifiers.AccessibilityMask;
if (pAccess == Modifiers.PUBLIC)
continue;
bool same_access_restrictions = false;
for (MemberCore mc = this; !same_access_restrictions && mc != null && mc.Parent != null; mc = mc.Parent) {
var al = mc.ModFlags & Modifiers.AccessibilityMask;
switch (pAccess) {
case Modifiers.INTERNAL:
if (al == Modifiers.PRIVATE || al == Modifiers.INTERNAL)
same_access_restrictions = p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
break;
case Modifiers.PROTECTED:
if (al == Modifiers.PROTECTED) {
same_access_restrictions = mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent);
break;
}
if (al == Modifiers.PRIVATE) {
//
// When type is private and any of its parents derives from
// protected type then the type is accessible
//
while (mc.Parent != null && mc.Parent.PartialContainer != null) {
if (mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent))
same_access_restrictions = true;
mc = mc.Parent;
}
}
break;
case Modifiers.PROTECTED | Modifiers.INTERNAL:
if (al == Modifiers.INTERNAL)
same_access_restrictions = p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
else if (al == (Modifiers.PROTECTED | Modifiers.INTERNAL))
same_access_restrictions = mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent) && p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
else
goto case Modifiers.PROTECTED;
break;
case Modifiers.PRIVATE:
//
// Both are private and share same parent
//
if (al == Modifiers.PRIVATE) {
var decl = mc.Parent;
do {
same_access_restrictions = decl.CurrentType.MemberDefinition == p_parent.MemberDefinition;
} while (!same_access_restrictions && !decl.PartialContainer.IsTopLevel && (decl = decl.Parent) != null);
}
break;
default:
throw new InternalErrorException (al.ToString ());
}
}
if (!same_access_restrictions)
return false;
}
return true;
}
/// <summary>
/// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
/// </summary>
public override bool IsClsComplianceRequired ()
{
if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
return (caching_flags & Flags.ClsCompliant) != 0;
caching_flags &= ~Flags.ClsCompliance_Undetected;
if (HasClsCompliantAttribute) {
if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0)
return false;
caching_flags |= Flags.ClsCompliant;
return true;
}
if (Parent.IsClsComplianceRequired ()) {
caching_flags |= Flags.ClsCompliant;
return true;
}
return false;
}
public virtual string[] ConditionalConditions ()
{
return null;
}
/// <summary>
/// Returns true when MemberCore is exposed from assembly.
/// </summary>
public bool IsExposedFromAssembly ()
{
if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
return this is NamespaceContainer;
var parentContainer = Parent.PartialContainer;
while (parentContainer != null) {
if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
return false;
parentContainer = parentContainer.Parent.PartialContainer;
}
return true;
}
//
// Does extension methods look up to find a method which matches name and extensionType.
// Search starts from this namespace and continues hierarchically up to top level.
//
public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
{
var m = Parent;
do {
var ns = m as NamespaceContainer;
if (ns != null)
return ns.LookupExtensionMethod (this, extensionType, name, arity, 0);
m = m.Parent;
} while (m != null);
return null;
}
public virtual FullNamedExpression LookupNamespaceAlias (string name)
{
return Parent.LookupNamespaceAlias (name);
}
public virtual FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
{
return Parent.LookupNamespaceOrType (name, arity, mode, loc);
}
/// <summary>
/// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
/// If no is attribute exists then assembly CLSCompliantAttribute is returned.
/// </summary>
public bool? CLSAttributeValue {
get {
if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0) {
if ((caching_flags & Flags.HasClsCompliantAttribute) == 0)
return null;
return (caching_flags & Flags.ClsCompliantAttributeFalse) == 0;
}
caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
if (OptAttributes != null) {
Attribute cls_attribute = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
if (cls_attribute != null) {
caching_flags |= Flags.HasClsCompliantAttribute;
if (cls_attribute.GetClsCompliantAttributeValue ())
return true;
caching_flags |= Flags.ClsCompliantAttributeFalse;
return false;
}
}
return null;
}
}
/// <summary>
/// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
/// </summary>
protected bool HasClsCompliantAttribute {
get {
return CLSAttributeValue.HasValue;
}
}
/// <summary>
/// Returns true when a member supports multiple overloads (methods, indexers, etc)
/// </summary>
public virtual bool EnableOverloadChecks (MemberCore overload)
{
return false;
}
/// <summary>
/// The main virtual method for CLS-Compliant verifications.
/// The method returns true if member is CLS-Compliant and false if member is not
/// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
/// and add their extra verifications.
/// </summary>
protected virtual bool VerifyClsCompliance ()
{
if (HasClsCompliantAttribute) {
if (!Module.DeclaringAssembly.HasCLSCompliantAttribute) {
Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
Report.Warning (3021, 2, a.Location,
"`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant",
GetSignatureForError ());
} else {
Report.Warning (3014, 1, a.Location,
"`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
GetSignatureForError ());
}
return false;
}
if (!IsExposedFromAssembly ()) {
Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
Report.Warning (3019, 2, a.Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
return false;
}
if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
if (Parent is Interface && Parent.IsClsComplianceRequired ()) {
Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
} else if (Parent.Kind == MemberKind.Class && (ModFlags & Modifiers.ABSTRACT) != 0 && Parent.IsClsComplianceRequired ()) {
Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
}
return false;
}
if (Parent.Kind != MemberKind.Namespace && Parent.Kind != 0 && !Parent.IsClsComplianceRequired ()) {
Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
Report.Warning (3018, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
GetSignatureForError (), Parent.GetSignatureForError ());
return false;
}
} else {
if (!IsExposedFromAssembly ())
return false;
if (!Parent.IsClsComplianceRequired ())
return false;
}
if (member_name.Name [0] == '_') {
Warning_IdentifierNotCompliant ();
}
if (member_name.TypeParameters != null)
member_name.TypeParameters.VerifyClsCompliance ();
return true;
}
protected void Warning_IdentifierNotCompliant ()
{
Report.Warning (3008, 1, MemberName.Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError ());
}
public virtual string GetCallerMemberName ()
{
return MemberName.Name;
}
//
// Returns a string that represents the signature for this
// member which should be used in XML documentation.
//
public abstract string GetSignatureForDocumentation ();
public virtual void GetCompletionStartingWith (string prefix, List<string> results)
{
Parent.GetCompletionStartingWith (prefix, results);
}
//
// Generates xml doc comments (if any), and if required,
// handle warning report.
//
internal virtual void GenerateDocComment (DocumentationBuilder builder)
{
if (DocComment == null) {
if (IsExposedFromAssembly ()) {
Constructor c = this as Constructor;
if (c == null || !c.IsDefault ())
Report.Warning (1591, 4, Location,
"Missing XML comment for publicly visible type or member `{0}'", GetSignatureForError ());
}
return;
}
try {
builder.GenerateDocumentationForMember (this);
} catch (Exception e) {
throw new InternalErrorException (this, e);
}
}
public virtual void WriteDebugSymbol (MonoSymbolFile file)
{
}
#region IMemberContext Members
public virtual CompilerContext Compiler {
get {
return Module.Compiler;
}
}
public virtual TypeSpec CurrentType {
get { return Parent.CurrentType; }
}
public MemberCore CurrentMemberDefinition {
get { return this; }
}
public virtual TypeParameters CurrentTypeParameters {
get { return null; }
}
public bool IsObsolete {
get {
if (GetAttributeObsolete () != null)
return true;
return Parent == null ? false : Parent.IsObsolete;
}
}
public bool IsUnsafe {
get {
if ((ModFlags & Modifiers.UNSAFE) != 0)
return true;
return Parent == null ? false : Parent.IsUnsafe;
}
}
public bool IsStatic {
get {
return (ModFlags & Modifiers.STATIC) != 0;
}
}
#endregion
}
//
// Base member specification. A member specification contains
// member details which can alter in the context (e.g. generic instances)
//
public abstract class MemberSpec
{
[Flags]
public enum StateFlags
{
Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
Obsolete = 1 << 1, // Member has obsolete attribute
CLSCompliant_Undetected = 1 << 2, // CLSCompliant attribute has not been detected yet
CLSCompliant = 1 << 3, // Member is CLS Compliant
MissingDependency_Undetected = 1 << 4,
MissingDependency = 1 << 5,
HasDynamicElement = 1 << 6,
ConstraintsChecked = 1 << 7,
IsAccessor = 1 << 9, // Method is an accessor
IsGeneric = 1 << 10, // Member contains type arguments
PendingMetaInflate = 1 << 12,
PendingMakeMethod = 1 << 13,
PendingMemberCacheMembers = 1 << 14,
PendingBaseTypeInflate = 1 << 15,
InterfacesExpanded = 1 << 16,
IsNotCSharpCompatible = 1 << 17,
SpecialRuntimeType = 1 << 18,
InflatedExpressionType = 1 << 19,
InflatedNullableType = 1 << 20,
GenericIterateInterface = 1 << 21,
GenericTask = 1 << 22
}
//
// Some flags can be copied directly from other member
//
protected const StateFlags SharedStateFlags =
StateFlags.CLSCompliant | StateFlags.CLSCompliant_Undetected |
StateFlags.Obsolete | StateFlags.Obsolete_Undetected |
StateFlags.MissingDependency | StateFlags.MissingDependency_Undetected |
StateFlags.HasDynamicElement;
protected Modifiers modifiers;
public StateFlags state;
protected IMemberDefinition definition;
public readonly MemberKind Kind;
protected TypeSpec declaringType;
#if DEBUG
static int counter;
public int ID = counter++;
#endif
protected MemberSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, Modifiers modifiers)
{
this.Kind = kind;
this.declaringType = declaringType;
this.definition = definition;
this.modifiers = modifiers;
state = StateFlags.Obsolete_Undetected | StateFlags.CLSCompliant_Undetected | StateFlags.MissingDependency_Undetected;
}
#region Properties
public virtual int Arity {
get {
return 0;
}
}
public TypeSpec DeclaringType {
get {
return declaringType;
}
set {
declaringType = value;
}
}
public IMemberDefinition MemberDefinition {
get {
return definition;
}
}
public Modifiers Modifiers {
get {
return modifiers;
}
set {
modifiers = value;
}
}
public virtual string Name {
get {
return definition.Name;
}
}
public bool IsAbstract {
get { return (modifiers & Modifiers.ABSTRACT) != 0; }
}
public bool IsAccessor {
get {
return (state & StateFlags.IsAccessor) != 0;
}
set {
state = value ? state | StateFlags.IsAccessor : state & ~StateFlags.IsAccessor;
}
}
//
// Return true when this member is a generic in C# terms
// A nested non-generic type of generic type will return false
//
public bool IsGeneric {
get {
return (state & StateFlags.IsGeneric) != 0;
}
set {
state = value ? state | StateFlags.IsGeneric : state & ~StateFlags.IsGeneric;
}
}
//
// Returns true for imported members which are not compatible with C# language
//
public bool IsNotCSharpCompatible {
get {
return (state & StateFlags.IsNotCSharpCompatible) != 0;
}
set {
state = value ? state | StateFlags.IsNotCSharpCompatible : state & ~StateFlags.IsNotCSharpCompatible;
}
}
public bool IsPrivate {
get { return (modifiers & Modifiers.PRIVATE) != 0; }
}
public bool IsPublic {
get { return (modifiers & Modifiers.PUBLIC) != 0; }
}
public bool IsStatic {
get {
return (modifiers & Modifiers.STATIC) != 0;
}
}
#endregion
public virtual ObsoleteAttribute GetAttributeObsolete ()
{
if ((state & (StateFlags.Obsolete | StateFlags.Obsolete_Undetected)) == 0)
return null;
state &= ~StateFlags.Obsolete_Undetected;
var oa = definition.GetAttributeObsolete ();
if (oa != null)
state |= StateFlags.Obsolete;
return oa;
}
//
// Returns a list of missing dependencies of this member. The list
// will contain types only but it can have numerous values for members
// like methods where both return type and all parameters are checked
//
public List<TypeSpec> GetMissingDependencies ()
{
if ((state & (StateFlags.MissingDependency | StateFlags.MissingDependency_Undetected)) == 0)
return null;
state &= ~StateFlags.MissingDependency_Undetected;
var imported = definition as ImportedDefinition;
List<TypeSpec> missing;
if (imported != null) {
missing = ResolveMissingDependencies ();
} else if (this is ElementTypeSpec) {
missing = ((ElementTypeSpec) this).Element.GetMissingDependencies ();
} else {
missing = null;
}
if (missing != null) {
state |= StateFlags.MissingDependency;
}
return missing;
}
public abstract List<TypeSpec> ResolveMissingDependencies ();
protected virtual bool IsNotCLSCompliant (out bool attrValue)
{
var cls = MemberDefinition.CLSAttributeValue;
attrValue = cls ?? false;
return cls == false;
}
public virtual string GetSignatureForDocumentation ()
{
return DeclaringType.GetSignatureForDocumentation () + "." + Name;
}
public virtual string GetSignatureForError ()
{
var bf = MemberDefinition as Property.BackingField;
string name;
if (bf == null) {
name = Name;
} else {
name = bf.OriginalProperty.MemberName.Name;
}
return DeclaringType.GetSignatureForError () + "." + name;
}
public virtual MemberSpec InflateMember (TypeParameterInflator inflator)
{
var inflated = (MemberSpec) MemberwiseClone ();
inflated.declaringType = inflator.TypeInstance;
if (DeclaringType.IsGenericOrParentIsGeneric)
inflated.state |= StateFlags.PendingMetaInflate;
#if DEBUG
inflated.ID += 1000000;
#endif
return inflated;
}
//
// Is this member accessible from invocation context
//
public bool IsAccessible (IMemberContext ctx)
{
var ma = Modifiers & Modifiers.AccessibilityMask;
if (ma == Modifiers.PUBLIC)
return true;
var parentType = /* this as TypeSpec ?? */ DeclaringType;
var ctype = ctx.CurrentType;
if (ma == Modifiers.PRIVATE) {
if (ctype == null)
return false;
//
// It's only accessible to the current class or children
//
if (parentType.MemberDefinition == ctype.MemberDefinition)
return true;
return TypeManager.IsNestedChildOf (ctype, parentType.MemberDefinition);
}
if ((ma & Modifiers.INTERNAL) != 0) {
bool b;
var assembly = ctype == null ? ctx.Module.DeclaringAssembly : ctype.MemberDefinition.DeclaringAssembly;
if (parentType == null) {
b = ((ITypeDefinition) MemberDefinition).IsInternalAsPublic (assembly);
} else {
b = DeclaringType.MemberDefinition.IsInternalAsPublic (assembly);
}
if (b || ma == Modifiers.INTERNAL)
return b;
}
//
// Checks whether `ctype' is a subclass or nested child of `parentType'.
//
while (ctype != null) {
if (TypeManager.IsFamilyAccessible (ctype, parentType))
return true;
// Handle nested types.
ctype = ctype.DeclaringType; // TODO: Untested ???
}
return false;
}
//
// Returns member CLS compliance based on full member hierarchy
//
public bool IsCLSCompliant ()
{
if ((state & StateFlags.CLSCompliant_Undetected) != 0) {
state &= ~StateFlags.CLSCompliant_Undetected;
bool compliant;
if (IsNotCLSCompliant (out compliant))
return false;
if (!compliant) {
if (DeclaringType != null) {
compliant = DeclaringType.IsCLSCompliant ();
} else {
compliant = ((ITypeDefinition) MemberDefinition).DeclaringAssembly.IsCLSCompliant;
}
}
if (compliant)
state |= StateFlags.CLSCompliant;
}
return (state & StateFlags.CLSCompliant) != 0;
}
public bool IsConditionallyExcluded (IMemberContext ctx, Location loc)
{
if ((Kind & (MemberKind.Class | MemberKind.Method)) == 0)
return false;
var conditions = MemberDefinition.ConditionalConditions ();
if (conditions == null)
return false;
var m = ctx.CurrentMemberDefinition;
CompilationSourceFile unit = null;
while (m != null && unit == null) {
unit = m as CompilationSourceFile;
m = m.Parent;
}
if (unit != null) {
foreach (var condition in conditions) {
if (unit.IsConditionalDefined (condition))
return false;
}
}
return true;
}
public override string ToString ()
{
return GetSignatureForError ();
}
}
//
// Member details which are same between all member
// specifications
//
public interface IMemberDefinition
{
bool? CLSAttributeValue { get; }
string Name { get; }
bool IsImported { get; }
string[] ConditionalConditions ();
ObsoleteAttribute GetAttributeObsolete ();
void SetIsAssigned ();
void SetIsUsed ();
}
public interface IParametersMember : IInterfaceMemberSpec
{
AParametersCollection Parameters { get; }
}
public interface IInterfaceMemberSpec
{
TypeSpec MemberType { get; }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
/// <summary>
/// Contains extension methods for conversion between WinRT streams and managed streams.
/// This class is the public facade for the stream adapters library.
/// </summary>
public static class WindowsRuntimeStreamExtensions
{
#region Constants and static Fields
private const Int32 DefaultBufferSize = 16384; // = 0x4000 = 16 KBytes.
private static ConditionalWeakTable<Object, Stream> s_winRtToNetFxAdapterMap
= new ConditionalWeakTable<Object, Stream>();
private static ConditionalWeakTable<Stream, NetFxToWinRtStreamAdapter> s_netFxToWinRtAdapterMap
= new ConditionalWeakTable<Stream, NetFxToWinRtStreamAdapter>();
#endregion Constants and static Fields
#region Helpers
#if DEBUG
private static void AssertMapContains<TKey, TValue>(ConditionalWeakTable<TKey, TValue> map, TKey key, TValue value,
bool valueMayBeWrappedInBufferedStream)
where TKey : class
where TValue : class
{
TValue valueInMap;
Debug.Assert(key != null);
bool hasValueForKey = map.TryGetValue(key, out valueInMap);
Debug.Assert(hasValueForKey);
if (valueMayBeWrappedInBufferedStream)
{
BufferedStream bufferedValueInMap = valueInMap as BufferedStream;
Debug.Assert(Object.ReferenceEquals(value, valueInMap)
|| (bufferedValueInMap != null && Object.ReferenceEquals(value, bufferedValueInMap.UnderlyingStream)));
}
else
{
Debug.Assert(Object.ReferenceEquals(value, valueInMap));
}
}
#endif // DEBUG
private static void EnsureAdapterBufferSize(Stream adapter, Int32 requiredBufferSize, String methodName)
{
Contract.Requires(adapter != null);
Contract.Requires(!String.IsNullOrWhiteSpace(methodName));
Int32 currentBufferSize = 0;
BufferedStream bufferedAdapter = adapter as BufferedStream;
if (bufferedAdapter != null)
currentBufferSize = bufferedAdapter.BufferSize;
if (requiredBufferSize != currentBufferSize)
{
if (requiredBufferSize == 0)
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_CannotChangeBufferSizeOfWinRtStreamAdapterToZero, methodName));
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_CannotChangeBufferSizeOfWinRtStreamAdapter, methodName));
}
}
#endregion Helpers
#region WinRt-to-NetFx conversion
[CLSCompliant(false)]
public static Stream AsStreamForRead(this IInputStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStreamForRead", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStreamForRead(this IInputStream windowsRuntimeStream, Int32 bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStreamForRead", forceBufferSize: true);
}
[CLSCompliant(false)]
public static Stream AsStreamForWrite(this IOutputStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStreamForWrite", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStreamForWrite(this IOutputStream windowsRuntimeStream, Int32 bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStreamForWrite", forceBufferSize: true);
}
[CLSCompliant(false)]
public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStream", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream, Int32 bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStream", forceBufferSize: true);
}
private static Stream AsStreamInternal(Object windowsRuntimeStream, Int32 bufferSize, String invokedMethodName, bool forceBufferSize)
{
if (windowsRuntimeStream == null)
throw new ArgumentNullException("windowsRuntimeStream");
if (bufferSize < 0)
throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_WinRtAdapterBufferSizeMayNotBeNegative);
Contract.Requires(!String.IsNullOrWhiteSpace(invokedMethodName));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
// If the WinRT stream is actually a wrapped managed stream, we will unwrap it and return the original.
// In that case we do not need to put the wrapper into the map.
// We currently do capability-based adapter selection for WinRt->NetFx, but not vice versa (time constraints).
// Once we added the reverse direction, we will be able replce this entire section with just a few lines.
NetFxToWinRtStreamAdapter sAdptr = windowsRuntimeStream as NetFxToWinRtStreamAdapter;
if (sAdptr != null)
{
Stream wrappedNetFxStream = sAdptr.GetManagedStream();
if (wrappedNetFxStream == null)
throw new ObjectDisposedException("windowsRuntimeStream", SR.ObjectDisposed_CannotPerformOperation);
#if DEBUG // In Chk builds, verify that the original managed stream is correctly entered into the NetFx->WinRT map:
AssertMapContains(s_netFxToWinRtAdapterMap, wrappedNetFxStream, sAdptr,
valueMayBeWrappedInBufferedStream: false);
#endif // DEBUG
return wrappedNetFxStream;
}
// We have a real WinRT stream.
Stream adapter;
bool adapterExists = s_winRtToNetFxAdapterMap.TryGetValue(windowsRuntimeStream, out adapter);
// There is already an adapter:
if (adapterExists)
{
Debug.Assert((adapter is BufferedStream && ((BufferedStream)adapter).UnderlyingStream is WinRtToNetFxStreamAdapter)
|| (adapter is WinRtToNetFxStreamAdapter));
if (forceBufferSize)
EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName);
return adapter;
}
// We do not have an adapter for this WinRT stream yet and we need to create one.
// Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating
// the required closure if this code path is hit:
return AsStreamInternalFactoryHelper(windowsRuntimeStream, bufferSize, invokedMethodName, forceBufferSize);
}
// Separate method so we only pay for closure allocation if this code is executed:
private static Stream WinRtToNetFxAdapterMap_GetValue(Object winRtStream)
{
return s_winRtToNetFxAdapterMap.GetValue(winRtStream, (wrtStr) => WinRtToNetFxStreamAdapter.Create(wrtStr));
}
// Separate method so we only pay for closure allocation if this code is executed:
private static Stream WinRtToNetFxAdapterMap_GetValue(Object winRtStream, Int32 bufferSize)
{
return s_winRtToNetFxAdapterMap.GetValue(winRtStream, (wrtStr) => new BufferedStream(WinRtToNetFxStreamAdapter.Create(wrtStr), bufferSize));
}
private static Stream AsStreamInternalFactoryHelper(Object windowsRuntimeStream, Int32 bufferSize, String invokedMethodName, bool forceBufferSize)
{
Contract.Requires(windowsRuntimeStream != null);
Contract.Requires(bufferSize >= 0);
Contract.Requires(!String.IsNullOrWhiteSpace(invokedMethodName));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
// Get the adapter for this windowsRuntimeStream again (it may have been created concurrently).
// If none exists yet, create a new one:
Stream adapter = (bufferSize == 0)
? WinRtToNetFxAdapterMap_GetValue(windowsRuntimeStream)
: WinRtToNetFxAdapterMap_GetValue(windowsRuntimeStream, bufferSize);
Debug.Assert(adapter != null);
Debug.Assert((adapter is BufferedStream && ((BufferedStream)adapter).UnderlyingStream is WinRtToNetFxStreamAdapter)
|| (adapter is WinRtToNetFxStreamAdapter));
if (forceBufferSize)
EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName);
WinRtToNetFxStreamAdapter actualAdapter = adapter as WinRtToNetFxStreamAdapter;
if (actualAdapter == null)
actualAdapter = ((BufferedStream)adapter).UnderlyingStream as WinRtToNetFxStreamAdapter;
actualAdapter.SetWonInitializationRace();
return adapter;
}
#endregion WinRt-to-NetFx conversion
#region NetFx-to-WinRt conversion
[CLSCompliant(false)]
public static IInputStream AsInputStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanRead)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotReadableToInputStream);
Contract.Ensures(Contract.Result<IInputStream>() != null);
Contract.EndContractBlock();
Object adapter = AsWindowsRuntimeStreamInternal(stream);
IInputStream winRtStream = adapter as IInputStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
[CLSCompliant(false)]
public static IOutputStream AsOutputStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanWrite)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotWritableToOutputStream);
Contract.Ensures(Contract.Result<IOutputStream>() != null);
Contract.EndContractBlock();
Object adapter = AsWindowsRuntimeStreamInternal(stream);
IOutputStream winRtStream = adapter as IOutputStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
[CLSCompliant(false)]
public static IRandomAccessStream AsRandomAccessStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanSeek)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotSeekableToRandomAccessStream);
Contract.Ensures(Contract.Result<IRandomAccessStream>() != null);
Contract.EndContractBlock();
Object adapter = AsWindowsRuntimeStreamInternal(stream);
IRandomAccessStream winRtStream = adapter as IRandomAccessStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
private static Object AsWindowsRuntimeStreamInternal(Stream stream)
{
Contract.Ensures(Contract.Result<Object>() != null);
Contract.EndContractBlock();
// Check to see if the managed stream is actually a wrapper of a WinRT stream:
// (This can be either an adapter directly, or an adapter wrapped in a BufferedStream.)
WinRtToNetFxStreamAdapter sAdptr = stream as WinRtToNetFxStreamAdapter;
if (sAdptr == null)
{
BufferedStream buffAdptr = stream as BufferedStream;
if (buffAdptr != null)
sAdptr = buffAdptr.UnderlyingStream as WinRtToNetFxStreamAdapter;
}
// If the managed stream us actually a WinRT stream, we will unwrap it and return the original.
// In that case we do not need to put the wrapper into the map.
if (sAdptr != null)
{
Object wrappedWinRtStream = sAdptr.GetWindowsRuntimeStream<Object>();
if (wrappedWinRtStream == null)
throw new ObjectDisposedException("stream", SR.ObjectDisposed_CannotPerformOperation);
#if DEBUG // In Chk builds, verify that the original WinRT stream is correctly entered into the WinRT->NetFx map:
AssertMapContains(s_winRtToNetFxAdapterMap, wrappedWinRtStream, sAdptr, valueMayBeWrappedInBufferedStream: true);
#endif // DEBUG
return wrappedWinRtStream;
}
// We have a real managed Stream.
// See if the managed stream already has an adapter:
NetFxToWinRtStreamAdapter adapter;
bool adapterExists = s_netFxToWinRtAdapterMap.TryGetValue(stream, out adapter);
// There is already an adapter:
if (adapterExists)
return adapter;
// We do not have an adapter for this managed stream yet and we need to create one.
// Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating
// the required closure if this code path is hit:
return AsWindowsRuntimeStreamInternalFactoryHelper(stream);
}
private static NetFxToWinRtStreamAdapter AsWindowsRuntimeStreamInternalFactoryHelper(Stream stream)
{
Contract.Requires(stream != null);
Contract.Ensures(Contract.Result<NetFxToWinRtStreamAdapter>() != null);
Contract.EndContractBlock();
// Get the adapter for managed stream again (it may have been created concurrently).
// If none exists yet, create a new one:
NetFxToWinRtStreamAdapter adapter = s_netFxToWinRtAdapterMap.GetValue(stream, (str) => NetFxToWinRtStreamAdapter.Create(str));
Debug.Assert(adapter != null);
adapter.SetWonInitializationRace();
return adapter;
}
#endregion NetFx-to-WinRt conversion
} // class WindowsRuntimeStreamExtensions
} // namespace
// WindowsRuntimeStreamExtensions.cs
| |
//-----------------------------------------------------------------------
// <copyright file="GraphMatValueSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using System.Threading.Tasks;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
using Akka.Actor;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class GraphMatValueSpec : AkkaSpec
{
public GraphMatValueSpec(ITestOutputHelper helper) : base(helper) { }
private static Sink<int, Task<int>> FoldSink => Sink.Aggregate<int,int>(0, (sum, i) => sum + i);
private IMaterializer CreateMaterializer(bool autoFusing)
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 16).WithAutoFusing(autoFusing);
return Sys.Materializer(settings);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_expose_the_materialized_value_as_source(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var sub = this.CreateManualSubscriberProbe<int>();
var f = RunnableGraph.FromGraph(GraphDsl.Create(FoldSink, (b, fold) =>
{
var source = Source.From(Enumerable.Range(1, 10)).MapMaterializedValue(_ => Task.FromResult(0));
b.From(source).To(fold);
b.From(b.MaterializedValue)
.Via(Flow.Create<Task<int>>().SelectAsync(4, x => x))
.To(Sink.FromSubscriber(sub).MapMaterializedValue(_ => Task.FromResult(0)));
return ClosedShape.Instance;
})).Run(materializer);
f.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
var r1 = f.Result;
sub.ExpectSubscription().Request(1);
var r2 = sub.ExpectNext();
r1.Should().Be(r2);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_expose_the_materialized_value_as_source_multiple_times(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var sub = this.CreateManualSubscriberProbe<int>();
var f = RunnableGraph.FromGraph(GraphDsl.Create(FoldSink, (b, fold) =>
{
var zip = b.Add(new ZipWith<int, int, int>((i, i1) => i + i1));
var source = Source.From(Enumerable.Range(1, 10)).MapMaterializedValue(_ => Task.FromResult(0));
b.From(source).To(fold);
b.From(b.MaterializedValue)
.Via(Flow.Create<Task<int>>().SelectAsync(4, x => x))
.To(zip.In0);
b.From(b.MaterializedValue)
.Via(Flow.Create<Task<int>>().SelectAsync(4, x => x))
.To(zip.In1);
b.From(zip.Out).To(Sink.FromSubscriber(sub).MapMaterializedValue(_ => Task.FromResult(0)));
return ClosedShape.Instance;
})).Run(materializer);
f.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
var r1 = f.Result;
sub.ExpectSubscription().Request(1);
var r2 = sub.ExpectNext();
r1.Should().Be(r2/2);
}
// Exposes the materialized value as a stream value
private static Source<Task<int>, Task<int>> FoldFeedbackSource => Source.FromGraph(GraphDsl.Create(FoldSink,
(b, fold) =>
{
var source = Source.From(Enumerable.Range(1, 10));
var shape = b.Add(source);
b.From(shape).To(fold);
return new SourceShape<Task<int>>(b.MaterializedValue);
}));
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_allow_exposing_the_materialized_value_as_port(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var t =
FoldFeedbackSource.SelectAsync(4, x => x)
.Select(x => x + 100)
.ToMaterialized(Sink.First<int>(), Keep.Both)
.Run(materializer);
var f1 = t.Item1;
var f2 = t.Item2;
f1.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
f1.Result.Should().Be(55);
f2.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
f2.Result.Should().Be(155);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_allow_exposing_the_materialized_values_as_port_even_if_wrapped_and_the_final_materialized_value_is_unit(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var noMatSource =
FoldFeedbackSource.SelectAsync(4, x => x).Select(x => x + 100).MapMaterializedValue(_ => NotUsed.Instance);
var t = noMatSource.RunWith(Sink.First<int>(), materializer);
t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
t.Result.Should().Be(155);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_work_properly_with_nesting_and_reusing(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var compositeSource1 = Source.FromGraph(GraphDsl.Create(FoldFeedbackSource, FoldFeedbackSource, Keep.Both,
(b, s1, s2) =>
{
var zip = b.Add(new ZipWith<int, int, int>((i, i1) => i + i1));
b.From(s1.Outlet).Via(Flow.Create<Task<int>>().SelectAsync(4, x => x)).To(zip.In0);
b.From(s2.Outlet).Via(Flow.Create<Task<int>>().SelectAsync(4, x => x).Select(x => x*100)).To(zip.In1);
return new SourceShape<int>(zip.Out);
}));
var compositeSource2 = Source.FromGraph(GraphDsl.Create(compositeSource1, compositeSource1, Keep.Both,
(b, s1, s2) =>
{
var zip = b.Add(new ZipWith<int, int, int>((i, i1) => i + i1));
b.From(s1.Outlet).To(zip.In0);
b.From(s2.Outlet).Via(Flow.Create<int>().Select(x => x*10000)).To(zip.In1);
return new SourceShape<int>(zip.Out);
}));
var t = compositeSource2.ToMaterialized(Sink.First<int>(), Keep.Both).Run(materializer);
var task = Task.WhenAll(t.Item1.Item1.Item1, t.Item1.Item1.Item2, t.Item1.Item2.Item1, t.Item1.Item2.Item2, t.Item2);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result[0].Should().Be(55);
task.Result[1].Should().Be(55);
task.Result[2].Should().Be(55);
task.Result[3].Should().Be(55);
task.Result[4].Should().Be(55555555);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_work_also_when_the_sources_module_is_copied(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var foldFlow = Flow.FromGraph(GraphDsl.Create(Sink.Aggregate<int, int>(0, (sum, i) => sum + i), (b, fold) =>
{
var o = b.From(b.MaterializedValue).Via(Flow.Create<Task<int>>().SelectAsync(4, x => x));
return new FlowShape<int,int>(fold.Inlet, o.Out);
}));
var t = Source.From(Enumerable.Range(1, 10)).Via(foldFlow).RunWith(Sink.First<int>(), materializer);
t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
t.Result.Should().Be(55);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_perform_side_effecting_transformations_even_when_not_used_as_source(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var done = false;
var g = GraphDsl.Create(b =>
{
b.From(Source.Empty<int>().MapMaterializedValue(_ =>
{
done = true;
return _;
})).To(Sink.Ignore<int>().MapMaterializedValue(_ => NotUsed.Instance));
return ClosedShape.Instance;
});
var r = RunnableGraph.FromGraph(GraphDsl.Create(Sink.Ignore<int>(), (b, sink) =>
{
var source = Source.From(Enumerable.Range(1, 10)).MapMaterializedValue(_ => Task.FromResult(0));
b.Add(g);
b.From(source).To(sink);
return ClosedShape.Instance;
}));
var task = r.Run(materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
done.Should().BeTrue();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_produce_NotUsed_when_not_importing_materialized_value(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var source = Source.FromGraph(GraphDsl.Create(b => new SourceShape<NotUsed>(b.MaterializedValue)));
var task = source.RunWith(Sink.Seq<NotUsed>(), materializer);
task.Wait(TimeSpan.FromSeconds(3));
task.Result.ShouldAllBeEquivalentTo(NotUsed.Instance);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_produce_NotUsed_when_starting_from_Flow_Via_with_transformation(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var done = false;
Source.Empty<int>().ViaMaterialized(Flow.Create<int>().Via(Flow.Create<int>().MapMaterializedValue(_ =>
{
done = true;
return _;
})), Keep.Right).To(Sink.Ignore<int>()).Run(materializer).Should().Be(NotUsed.Instance);
done.Should().BeTrue();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_ignore_materialized_values_for_a_graph_with_no_materialized_values_exposed(bool autoFusing)
{
// The bug here was that the default behavior for "compose" in Module is Keep.left, but
// EmptyModule.compose broke this by always returning the other module intact, which means
// that the materialized value was that of the other module (which is inconsistent with Keep.left behavior).
var sink = Sink.Ignore<int>();
var g = RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var s = b.Add(sink);
var source = b.Add(Source.From(Enumerable.Range(1, 3)));
var flow = b.Add(Flow.Create<int>());
b.From(source).Via(flow).To(s);
return ClosedShape.Instance;
}));
var result = g.Run(CreateMaterializer(autoFusing));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_ignore_materialized_values_for_a_graph_with_no_materialized_values_exposed_but_keep_side_effects(bool autoFusing)
{
// The bug here was that the default behavior for "compose" in Module is Keep.left, but
// EmptyModule.compose broke this by always returning the other module intact, which means
// that the materialized value was that of the other module (which is inconsistent with Keep.left behavior).
var sink = Sink.Ignore<int>().MapMaterializedValue(_=>
{
TestActor.Tell("side effect!");
return _;
});
var g = RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var s = b.Add(sink);
var source = b.Add(Source.From(Enumerable.Range(1, 3)));
var flow = b.Add(Flow.Create<int>());
b.From(source).Via(flow).To(s);
return ClosedShape.Instance;
}));
var result = g.Run(CreateMaterializer(autoFusing));
ExpectMsg("side effect!");
}
[Fact]
public void A_Graph_with_Identity_Flow_optimization_even_if_port_are_wired_in_an_arbitrary_higher_nesting_level()
{
var mat2 = Sys.Materializer(ActorMaterializerSettings.Create(Sys).WithAutoFusing(false));
var subFlow = GraphDsl.Create(b =>
{
var zip = b.Add(new Zip<string, string>());
var bc = b.Add(new Broadcast<string>(2));
b.From(bc.Out(0)).To(zip.In0);
b.From(bc.Out(1)).To(zip.In1);
return new FlowShape<string, Tuple<string, string>>(bc.In, zip.Out);
}).Named("NestedFlow");
var nest1 = Flow.Create<string>().Via(subFlow);
var nest2 = Flow.Create<string>().Via(nest1);
var nest3 = Flow.Create<string>().Via(nest2);
var nest4 = Flow.Create<string>().Via(nest3);
//fails
var matValue = Source.Single("").Via(nest4).To(Sink.Ignore<Tuple<string, string>>()).Run(mat2);
matValue.Should().Be(NotUsed.Instance);
}
[Fact]
public void A_Graph_must_not_ignore_materialized_value_of_identity_flow_which_is_optimized_away()
{
var mat = Sys.Materializer(ActorMaterializerSettings.Create(Sys).WithAutoFusing(false));
var t = Source.Single(1)
.ViaMaterialized(Flow.Identity<int>(), Keep.Both)
.To(Sink.Ignore<int>())
.Run(mat);
t.Item1.ShouldBe(NotUsed.Instance);
t.Item2.ShouldBe(NotUsed.Instance);
var m1 = Source.Maybe<int>()
.ViaMaterialized(Flow.Identity<int>(), Keep.Left)
.To(Sink.Ignore<int>())
.Run(mat);
m1.SetResult(0);
var m2 = Source.Single(1)
.ViaMaterialized(Flow.Identity<int>(), Keep.Right)
.To(Sink.Ignore<int>())
.Run(mat);
m2.ShouldBe(NotUsed.Instance);
}
}
}
| |
// 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.IO;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class is a representation of a possible remote work item processing subsystem.
/// Currently wrapped by LocalNode.
/// Owns the Engine on a child node.
/// </summary>
internal class Node
{
#region Constructors
/// <summary>
/// Initialize the node with the id and the callback object
/// </summary>
internal Node
(
int nodeId,
LoggerDescription[] nodeLoggers,
IEngineCallback parentCallback,
BuildPropertyGroup parentGlobalProperties,
ToolsetDefinitionLocations toolsetSearchLocations,
string parentStartupDirectory
)
{
this.nodeId = nodeId;
this.parentCallback = parentCallback;
this.exitNodeEvent = new ManualResetEvent(false);
this.buildRequests = new Queue<BuildRequest>();
this.requestToLocalIdMapping = new Hashtable();
this.lastRequestIdUsed = 0;
this.centralizedLogging = false;
this.nodeLoggers = nodeLoggers;
this.localEngine = null;
this.launchedEngineLoopThread = false;
this.nodeShutdown = false;
this.parentGlobalProperties = parentGlobalProperties;
this.toolsetSearchLocations = toolsetSearchLocations;
this.parentStartupDirectory = parentStartupDirectory;
}
#endregion
#region Properties
internal Introspector Introspector
{
get
{
if (localEngine != null)
{
return localEngine.Introspector;
}
return null;
}
}
/// <summary>
/// This property returns 0 if profiling is not enabled and otherwise returns the
/// total time spent inside user task code
/// </summary>
internal int TotalTaskTime
{
get
{
return totalTaskTime;
}
}
internal int NodeId
{
get { return nodeId; }
}
#endregion
#region Method used to call from local engine to the host (and parent engine)
/// <summary>
/// This method posts outputs of a build to the node that made the request
/// </summary>
/// <param name="buildResult"></param>
internal void PostBuildResultToHost(BuildResult buildResult)
{
try
{
outProcLoggingService.ProcessPostedLoggingEvents();
parentCallback.PostBuildResultToHost(buildResult);
}
catch (Exception e)
{
ReportUnhandledError(e);
}
}
internal void PostBuildRequestToHost(BuildRequest currentRequest)
{
// Since this request is going back to the host the local node should not have a project object for it
ErrorUtilities.VerifyThrow(currentRequest.ProjectToBuild == null, "Should not have a project object");
// Add the request to the mapping hashtable so that we can recognize the outputs
CacheScope cacheScope = localEngine.CacheManager.GetCacheScope(currentRequest.ProjectFileName, currentRequest.GlobalProperties, currentRequest.ToolsetVersion, CacheContentType.BuildResults);
NodeRequestMapping nodeRequestMapping =
new NodeRequestMapping(currentRequest.HandleId, currentRequest.RequestId, cacheScope );
lock (requestToLocalIdMapping)
{
requestToLocalIdMapping.Add(lastRequestIdUsed, nodeRequestMapping);
// Keep the request id local for this node
currentRequest.RequestId = lastRequestIdUsed;
lastRequestIdUsed++;
}
// Find the original external request that caused us to run this task
TaskExecutionContext taskExecutionContext = localEngine.EngineCallback.GetTaskContextFromHandleId(currentRequest.HandleId);
while (!taskExecutionContext.BuildContext.BuildRequest.IsExternalRequest)
{
ErrorUtilities.VerifyThrow(taskExecutionContext.BuildContext.BuildRequest.IsGeneratedRequest,
"Must be a generated request");
taskExecutionContext =
localEngine.EngineCallback.GetTaskContextFromHandleId(taskExecutionContext.BuildContext.BuildRequest.HandleId);
}
//Modify the request with the data that is expected by the parent engine
currentRequest.HandleId = taskExecutionContext.BuildContext.BuildRequest.HandleId;
currentRequest.NodeIndex = taskExecutionContext.BuildContext.BuildRequest.NodeIndex;
try
{
outProcLoggingService.ProcessPostedLoggingEvents();
parentCallback.PostBuildRequestsToHost(new BuildRequest[] { currentRequest });
}
catch (Exception e)
{
ReportUnhandledError(e);
}
}
/// <summary>
/// Posts the given set of cache entries to the parent engine.
/// </summary>
/// <param name="entries"></param>
/// <param name="scopeName"></param>
/// <param name="scopeProperties"></param>
internal Exception PostCacheEntriesToHost(CacheEntry[] entries, string scopeName, BuildPropertyGroup scopeProperties, string scopeToolsVersion, CacheContentType cacheContentType)
{
try
{
return parentCallback.PostCacheEntriesToHost(this.nodeId /* ignored */, entries, scopeName, scopeProperties, scopeToolsVersion, cacheContentType);
}
catch (Exception e)
{
ReportUnhandledError(e);
return null;
}
}
/// <summary>
/// Retrieves the requested set of cache entries from the engine.
/// </summary>
/// <param name="names"></param>
/// <param name="scopeName"></param>
/// <param name="scopeProperties"></param>
/// <returns></returns>
internal CacheEntry[] GetCachedEntriesFromHost(string[] names, string scopeName, BuildPropertyGroup scopeProperties, string scopeToolsVersion, CacheContentType cacheContentType)
{
try
{
return parentCallback.GetCachedEntriesFromHost(this.nodeId /* ignored */, names, scopeName, scopeProperties, scopeToolsVersion, cacheContentType);
}
catch (Exception e)
{
ReportUnhandledError(e);
return new CacheEntry[0];
}
}
internal void PostLoggingMessagesToHost(NodeLoggingEvent[] nodeLoggingEvents)
{
try
{
parentCallback.PostLoggingMessagesToHost(nodeId, nodeLoggingEvents);
}
catch (Exception e)
{
ReportUnhandledError(e);
}
}
internal void PostStatus(NodeStatus nodeStatus, bool blockUntilSent)
{
try
{
PostStatusThrow(nodeStatus, blockUntilSent);
}
catch (Exception e)
{
ReportUnhandledError(e);
}
}
/// <summary>
/// A variation of PostStatus that throws instead of calling ReportUnhandledError
/// if there's a problem. This allows ReportUnhandledError itself to post status
/// without the possibility of a loop.
/// </summary>
internal void PostStatusThrow(NodeStatus nodeStatus, bool blockUntilSent)
{
parentCallback.PostStatus(nodeId, nodeStatus, blockUntilSent);
}
#endregion
#region Methods called from the host (and parent engine)
/// <summary>
/// This method lets the host request an evaluation of a build request. A local engine
/// will be created if necessary.
/// </summary>
internal void PostBuildRequest
(
BuildRequest buildRequest
)
{
buildRequest.RestoreNonSerializedDefaults();
buildRequest.NodeIndex = EngineCallback.inProcNode;
// A request has come from the parent engine, so mark it as external
buildRequest.IsExternalRequest = true;
if (localEngine == null)
{
// Check if an an engine has been allocated and if not start the thread that will do that
lock (buildRequests)
{
if (localEngine == null)
{
if (!launchedEngineLoopThread)
{
launchedEngineLoopThread = true;
ThreadStart threadState = new ThreadStart(this.NodeLocalEngineLoop);
Thread taskThread = new Thread(threadState);
taskThread.Name = "MSBuild Child Engine";
taskThread.SetApartmentState(ApartmentState.STA);
taskThread.Start();
}
buildRequests.Enqueue(buildRequest);
}
else
{
localEngine.PostBuildRequest(buildRequest);
}
}
}
else
{
if (!buildInProgress)
{
buildInProgress = true;
// If there are forwarding loggers registered - generate a custom build started
if (nodeLoggers.Length > 0)
{
localEngine.LoggingServices.LogBuildStarted(EngineLoggingServicesInProc.CENTRAL_ENGINE_EVENTSOURCE);
localEngine.LoggingServices.ProcessPostedLoggingEvents();
}
}
localEngine.PostBuildRequest(buildRequest);
}
}
/// <summary>
/// This method lets the engine provide node with results of an evaluation it was waiting on.
/// </summary>
internal void PostBuildResult(BuildResult buildResult)
{
ErrorUtilities.VerifyThrow(localEngine != null, "Local engine should be initialized");
// Figure out the local handle id
NodeRequestMapping nodeRequestMapping = null;
try
{
lock (requestToLocalIdMapping)
{
nodeRequestMapping = (NodeRequestMapping)requestToLocalIdMapping[buildResult.RequestId];
requestToLocalIdMapping.Remove(buildResult.RequestId);
}
if (Engine.debugMode)
{
Console.WriteLine(nodeId + ": Got result for Request Id " + buildResult.RequestId);
Console.WriteLine(nodeId + ": Received result for HandleId " + buildResult.HandleId + ":" + buildResult.RequestId + " mapped to " + nodeRequestMapping.HandleId + ":" + nodeRequestMapping.RequestId);
}
buildResult.HandleId = nodeRequestMapping.HandleId;
buildResult.RequestId = nodeRequestMapping.RequestId;
nodeRequestMapping.AddResultToCache(buildResult);
// posts the result to the inproc node
localEngine.Router.PostDoneNotice(0, buildResult);
}
catch (Exception ex)
{
ReportUnhandledError(ex);
}
}
/// <summary>
/// Causes the node to safely shutdown and exit
/// </summary>
internal void ShutdownNode(NodeShutdownLevel shutdownLevel)
{
if (shutdownLevel == NodeShutdownLevel.BuildCompleteSuccess ||
shutdownLevel == NodeShutdownLevel.BuildCompleteFailure )
{
if (Engine.debugMode)
{
Console.WriteLine("Node.Shutdown: NodeId " + nodeId + ": Clearing engine state and intern table ready for node re-use.");
}
if (localEngine != null)
{
localEngine.EndingEngineExecution
(shutdownLevel == NodeShutdownLevel.BuildCompleteSuccess ? true : false, false);
localEngine.ResetPerBuildDataStructures();
outProcLoggingService.ProcessPostedLoggingEvents();
buildInProgress = false;
}
// Clear the static table of interned strings
BuildProperty.ClearInternTable();
}
else
{
if (Engine.debugMode)
{
Console.WriteLine("Node.Shutdown: NodeId " + nodeId + ": Shutting down node due to error.");
}
// The thread starting the build loop will acquire this lock before starting the loop
// in order to read the build requests. Acquiring it here ensures that build loop doesn't
// get started between the check for null and setting of the flag
lock (buildRequests)
{
if (localEngine == null)
{
nodeShutdown = true;
}
}
if (localEngine != null)
{
// Indicate to the child engine that we need to exit
localEngine.SetEngineAbortTo(true);
// Wait for the exit event which will be raised once the child engine exits
exitNodeEvent.WaitOne();
}
}
}
/// <summary>
/// This function is used to update the settings of the engine running on the node
/// </summary>
internal void UpdateNodeSettings
(
bool shouldLogOnlyCriticalEvents,
bool enableCentralizedLogging,
bool useBreadthFirstTraversal
)
{
this.logOnlyCriticalEvents = shouldLogOnlyCriticalEvents;
this.centralizedLogging = enableCentralizedLogging;
this.useBreadthFirstTraversal = useBreadthFirstTraversal;
if (localEngine != null)
{
localEngine.LoggingServices.OnlyLogCriticalEvents = this.logOnlyCriticalEvents;
localEngine.PostEngineCommand( new ChangeTraversalTypeCommand( useBreadthFirstTraversal, true ));
}
}
/// <summary>
/// The coordinating engine is requesting status
/// </summary>
internal void RequestStatus(int requestId)
{
// Check if the status has been requested before the local
// engine has been started.
if (localEngine == null)
{
NodeStatus nodeStatus = null;
lock (buildRequests)
{
nodeStatus = new NodeStatus(requestId, true, buildRequests.Count, 0, 0, false);
}
parentCallback.PostStatus(nodeId, nodeStatus, false);
}
else
{
// Since the local engine has been started - ask it for status
RequestStatusEngineCommand requestStatus = new RequestStatusEngineCommand(requestId);
localEngine.PostEngineCommand(requestStatus);
}
}
/// <summary>
/// This function can be used by the node provider to report a failure which doesn't prevent further
/// communication with the parent node. The node will attempt to notify the parent of the failure,
/// send all outstanding logging events and shutdown.
/// </summary>
/// <param name="originalException"></param>
/// <exception cref="Exception">Throws exception (with nested original exception) if reporting to parent fails.</exception>
internal void ReportUnhandledError(Exception originalException)
{
NodeStatus nodeStatus = new NodeStatus(originalException);
if (Engine.debugMode)
{
Console.WriteLine("Node.ReportUnhandledError: " + originalException.Message);
}
try
{
try
{
PostStatusThrow(nodeStatus, true /* wait for the message to be sent before returning */);
}
catch (Exception ex)
{
// If an error occurred while trying to send the original exception to the parent
// rethrow the original exception
string message = ResourceUtilities.FormatResourceString("FatalErrorOnChildNode", nodeId, ex.Message);
ErrorUtilities.LaunchMsBuildDebuggerOnFatalError();
throw new Exception(message, originalException);
}
}
finally
{
// Makesure we write the exception to a file so even if something goes wrong with the logging or transfer to the parent
// then we will atleast get the message on disk.
LocalNode.DumpExceptionToFile(originalException);
}
localEngine?.Shutdown();
}
/// <summary>
/// This method can be used by the node provider to report a fatal communication error, after
/// which further communication with the parent node is no longer possible. The node provider
/// can optionally provide a stream to which the current node state will be logged in order
/// to assist with debugging of the problem.
/// </summary>
/// <param name="originalException"></param>
/// <param name="loggingStream"></param>
/// <exception cref="Exception">Re-throws exception passed in</exception>
internal void ReportFatalCommunicationError(Exception originalException, TextWriter loggingStream)
{
loggingStream?.WriteLine(originalException.ToString());
string message = ResourceUtilities.FormatResourceString("FatalErrorOnChildNode", nodeId, originalException.Message);
ErrorUtilities.LaunchMsBuildDebuggerOnFatalError();
throw new Exception(message, originalException);
}
#endregion
#region Thread procedure for Engine BuildLoop
private void NodeLocalEngineLoop()
{
buildInProgress = true;
// Create a logging service for this build request
localEngine =
new Engine(parentGlobalProperties, toolsetSearchLocations, 1 /* cpus */, true /* child node */, this.nodeId, parentStartupDirectory, null);
localEngine.Router.ChildMode = true;
localEngine.Router.ParentNode = this;
this.outProcLoggingService = new EngineLoggingServicesOutProc(this, localEngine.FlushRequestEvent);
if (nodeLoggers.Length != 0)
{
foreach (LoggerDescription loggerDescription in nodeLoggers)
{
IForwardingLogger newLogger = null;
bool exitedDueToError = true;
try
{
newLogger = loggerDescription.CreateForwardingLogger();
// Check if the class was not found in the assembly
if (newLogger == null)
{
InternalLoggerException.Throw(null, null, "FatalErrorWhileInitializingLogger", true, loggerDescription.Name);
}
newLogger.Verbosity = loggerDescription.Verbosity;
newLogger.Parameters = loggerDescription.LoggerSwitchParameters;
newLogger.NodeId = nodeId;
EventRedirector newRedirector = new EventRedirector(loggerDescription.LoggerId, outProcLoggingService);
newLogger.BuildEventRedirector = newRedirector;
exitedDueToError = false;
}
// Polite logger failure
catch (LoggerException e)
{
ReportUnhandledError(e);
}
// Logger class was not found
catch (InternalLoggerException e)
{
ReportUnhandledError(e);
}
catch (Exception e)
{
// Wrap the exception in a InternalLoggerException and send it to the parent node
string errorCode;
string helpKeyword;
string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "FatalErrorWhileInitializingLogger", loggerDescription.Name);
ReportUnhandledError(new InternalLoggerException(message, e, null, errorCode, helpKeyword, true));
}
// If there was a failure registering loggers, null out the engine pointer
if (exitedDueToError)
{
localEngine = null;
return;
}
localEngine.RegisterLogger(newLogger);
}
localEngine.ExternalLoggingServices = outProcLoggingService;
}
// Hook up logging service to forward all events to the central engine if necessary
if (centralizedLogging)
{
if (nodeLoggers.Length != 0)
{
localEngine.LoggingServices.ForwardingService = outProcLoggingService;
localEngine.ExternalLoggingServices = outProcLoggingService;
}
else
{
localEngine.LoggingServices = outProcLoggingService;
}
}
localEngine.LoggingServices.OnlyLogCriticalEvents = this.logOnlyCriticalEvents;
if (!useBreadthFirstTraversal)
{
localEngine.PostEngineCommand(new ChangeTraversalTypeCommand(useBreadthFirstTraversal, true));
}
// Post all the requests that passed in while the engine was being constructed
// into the engine queue
lock (buildRequests)
{
while (buildRequests.Count != 0)
{
BuildRequest buildRequest = buildRequests.Dequeue();
localEngine.PostBuildRequest(buildRequest);
}
}
try
{
// If there are forwarding loggers registered - generate a custom build started
if (nodeLoggers.Length > 0)
{
localEngine.LoggingServices.LogBuildStarted(EngineLoggingServicesInProc.CENTRAL_ENGINE_EVENTSOURCE);
localEngine.LoggingServices.ProcessPostedLoggingEvents();
}
// Trigger the actual build if shutdown was not called while the engine was being initialized
if (!nodeShutdown)
{
localEngine.EngineBuildLoop(null);
}
}
catch (Exception e)
{
// Unhandled exception during execution. The node has to be shutdown.
ReportUnhandledError(e);
}
finally
{
if (localEngine != null)
{
// Flush all the messages associated before shutting down
localEngine.LoggingServices.ProcessPostedLoggingEvents();
NodeManager nodeManager = localEngine.NodeManager;
// If the local engine is already shutting down, the TEM will be nulled out
if (nodeManager.TaskExecutionModule != null && nodeManager.TaskExecutionModule.TaskExecutionTime != 0)
{
TimeSpan taskTimeSpan = new TimeSpan(localEngine.NodeManager.TaskExecutionModule.TaskExecutionTime);
totalTaskTime = (int)taskTimeSpan.TotalMilliseconds;
}
localEngine.Shutdown();
}
// Flush all the events to the parent engine
outProcLoggingService.ProcessPostedLoggingEvents();
// Indicate that the node logger thread should exit
exitNodeEvent.Set();
}
}
#endregion
#region Member data
// Interface provided by the host that is used to communicate with the parent engine
private IEngineCallback parentCallback;
// Id of this node
private int nodeId;
// This event is used to communicate between the thread calling shutdown method and the thread running the Engine.BuildLoop.
private ManualResetEvent exitNodeEvent;
// The engine being used to process build requests
private Engine localEngine;
// The queue of build requests arriving from the parent. The queue is needed to buffer the requests while the local engine is
// being created and initialized
private Queue<BuildRequest> buildRequests;
// This flag is true if the thread that will be running the Engine.BuildLoop has been launched
private bool launchedEngineLoopThread;
// The logging service that is used to send the event to the parent engine. It maybe hooked up directly to the local engine or cascaded with
// another logging service depending on configuration
private EngineLoggingServicesOutProc outProcLoggingService;
private Hashtable requestToLocalIdMapping;
private int lastRequestIdUsed;
// Initializes to false by default
private bool logOnlyCriticalEvents;
private bool centralizedLogging;
private bool useBreadthFirstTraversal;
private LoggerDescription[] nodeLoggers;
private bool buildInProgress;
private bool nodeShutdown;
private BuildPropertyGroup parentGlobalProperties;
private ToolsetDefinitionLocations toolsetSearchLocations;
private string parentStartupDirectory;
private int totalTaskTime;
#endregion
#region Enums
internal enum NodeShutdownLevel
{
/// <summary>
/// Notify the engine that a build has completed an reset all data structures
/// that should be reset between builds
/// </summary>
BuildCompleteSuccess = 0,
BuildCompleteFailure = 1,
/// <summary>
/// Wait for in progress operations to finish before returning
/// </summary>
PoliteShutdown = 2,
/// <summary>
/// Cancel all in progress operations and return
/// </summary>
ErrorShutdown = 3
}
#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.
////////////////////////////////////////////////////////////////////////////
//
// DateTimeFormatInfoScanner
//
// Scan a specified DateTimeFormatInfo to search for data used in DateTime.Parse()
//
// The data includes:
//
// DateWords: such as "de" used in es-ES (Spanish) LongDatePattern.
// Postfix: such as "ta" used in fi-FI after the month name.
//
// This class is shared among mscorlib.dll and sysglobl.dll.
// Use conditional CULTURE_AND_REGIONINFO_BUILDER_ONLY to differentiate between
// methods for mscorlib.dll and sysglobl.dll.
//
////////////////////////////////////////////////////////////////////////////
using System.Collections.Generic;
using System.Text;
namespace System.Globalization
{
//
// from LocaleEx.txt header
//
//; IFORMATFLAGS
//; Parsing/formatting flags.
internal enum FORMATFLAGS
{
None = 0x00000000,
UseGenitiveMonth = 0x00000001,
UseLeapYearMonth = 0x00000002,
UseSpacesInMonthNames = 0x00000004,
UseHebrewParsing = 0x00000008,
UseSpacesInDayNames = 0x00000010, // Has spaces or non-breaking space in the day names.
UseDigitPrefixInTokens = 0x00000020, // Has token starting with numbers.
}
internal enum CalendarId : ushort
{
UNINITIALIZED_VALUE = 0,
GREGORIAN = 1, // Gregorian (localized) calendar
GREGORIAN_US = 2, // Gregorian (U.S.) calendar
JAPAN = 3, // Japanese Emperor Era calendar
/* SSS_WARNINGS_OFF */
TAIWAN = 4, // Taiwan Era calendar /* SSS_WARNINGS_ON */
KOREA = 5, // Korean Tangun Era calendar
HIJRI = 6, // Hijri (Arabic Lunar) calendar
THAI = 7, // Thai calendar
HEBREW = 8, // Hebrew (Lunar) calendar
GREGORIAN_ME_FRENCH = 9, // Gregorian Middle East French calendar
GREGORIAN_ARABIC = 10, // Gregorian Arabic calendar
GREGORIAN_XLIT_ENGLISH = 11, // Gregorian Transliterated English calendar
GREGORIAN_XLIT_FRENCH = 12,
// Note that all calendars after this point are MANAGED ONLY for now.
JULIAN = 13,
JAPANESELUNISOLAR = 14,
CHINESELUNISOLAR = 15,
SAKA = 16, // reserved to match Office but not implemented in our code
LUNAR_ETO_CHN = 17, // reserved to match Office but not implemented in our code
LUNAR_ETO_KOR = 18, // reserved to match Office but not implemented in our code
LUNAR_ETO_ROKUYOU = 19, // reserved to match Office but not implemented in our code
KOREANLUNISOLAR = 20,
TAIWANLUNISOLAR = 21,
PERSIAN = 22,
UMALQURA = 23,
LAST_CALENDAR = 23 // Last calendar ID
}
internal class DateTimeFormatInfoScanner
{
// Special prefix-like flag char in DateWord array.
// Use char in PUA area since we won't be using them in real data.
// The char used to tell a read date word or a month postfix. A month postfix
// is "ta" in the long date pattern like "d. MMMM'ta 'yyyy" for fi-FI.
// In this case, it will be stored as "\xfffeta" in the date word array.
internal const char MonthPostfixChar = '\xe000';
// Add ignorable symbol in a DateWord array.
// hu-HU has:
// shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd
// long date pattern: yyyy. MMMM d.
// Here, "." is the date separator (derived from short date pattern). However,
// "." also appear at the end of long date pattern. In this case, we just
// "." as ignorable symbol so that the DateTime.Parse() state machine will not
// treat the additional date separator at the end of y,m,d pattern as an error
// condition.
internal const char IgnorableSymbolChar = '\xe001';
// Known CJK suffix
internal const string CJKYearSuff = "\u5e74";
internal const string CJKMonthSuff = "\u6708";
internal const string CJKDaySuff = "\u65e5";
internal const string KoreanYearSuff = "\ub144";
internal const string KoreanMonthSuff = "\uc6d4";
internal const string KoreanDaySuff = "\uc77c";
internal const string KoreanHourSuff = "\uc2dc";
internal const string KoreanMinuteSuff = "\ubd84";
internal const string KoreanSecondSuff = "\ucd08";
internal const string CJKHourSuff = "\u6642";
internal const string ChineseHourSuff = "\u65f6";
internal const string CJKMinuteSuff = "\u5206";
internal const string CJKSecondSuff = "\u79d2";
// The collection fo date words & postfix.
internal List<string> m_dateWords = new List<string>();
// Hashtable for the known words.
private static volatile Dictionary<string, string>? s_knownWords;
static Dictionary<string, string> KnownWords
{
get
{
if (s_knownWords == null)
{
Dictionary<string, string> temp = new Dictionary<string, string>();
// Add known words into the hash table.
// Skip these special symbols.
temp.Add("/", string.Empty);
temp.Add("-", string.Empty);
temp.Add(".", string.Empty);
// Skip known CJK suffixes.
temp.Add(CJKYearSuff, string.Empty);
temp.Add(CJKMonthSuff, string.Empty);
temp.Add(CJKDaySuff, string.Empty);
temp.Add(KoreanYearSuff, string.Empty);
temp.Add(KoreanMonthSuff, string.Empty);
temp.Add(KoreanDaySuff, string.Empty);
temp.Add(KoreanHourSuff, string.Empty);
temp.Add(KoreanMinuteSuff, string.Empty);
temp.Add(KoreanSecondSuff, string.Empty);
temp.Add(CJKHourSuff, string.Empty);
temp.Add(ChineseHourSuff, string.Empty);
temp.Add(CJKMinuteSuff, string.Empty);
temp.Add(CJKSecondSuff, string.Empty);
s_knownWords = temp;
}
return s_knownWords;
}
}
////////////////////////////////////////////////////////////////////////////
//
// Parameters:
// pattern: The pattern to be scanned.
// currentIndex: the current index to start the scan.
//
// Returns:
// Return the index with the first character that is a letter, which will
// be the start of a date word.
// Note that the index can be pattern.Length if we reach the end of the string.
//
////////////////////////////////////////////////////////////////////////////
internal static int SkipWhiteSpacesAndNonLetter(string pattern, int currentIndex)
{
while (currentIndex < pattern.Length)
{
char ch = pattern[currentIndex];
if (ch == '\\')
{
// Escaped character. Look ahead one character.
currentIndex++;
if (currentIndex < pattern.Length)
{
ch = pattern[currentIndex];
if (ch == '\'')
{
// Skip the leading single quote. We will
// stop at the first letter.
continue;
}
// Fall thru to check if this is a letter.
}
else
{
// End of string
break;
}
}
if (char.IsLetter(ch) || ch == '\'' || ch == '.')
{
break;
}
// Skip the current char since it is not a letter.
currentIndex++;
}
return (currentIndex);
}
////////////////////////////////////////////////////////////////////////////
//
// A helper to add the found date word or month postfix into ArrayList for date words.
//
// Parameters:
// formatPostfix: What kind of postfix this is.
// Possible values:
// null: This is a regular date word
// "MMMM": month postfix
// word: The date word or postfix to be added.
//
////////////////////////////////////////////////////////////////////////////
internal void AddDateWordOrPostfix(string? formatPostfix, string str)
{
if (str.Length > 0)
{
// Some cultures use . like an abbreviation
if (str.Equals("."))
{
AddIgnorableSymbols(".");
return;
}
if (KnownWords.TryGetValue(str, out _) == false)
{
if (m_dateWords == null)
{
m_dateWords = new List<string>();
}
if (formatPostfix == "MMMM")
{
// Add the word into the ArrayList as "\xfffe" + real month postfix.
string temp = MonthPostfixChar + str;
if (!m_dateWords.Contains(temp))
{
m_dateWords.Add(temp);
}
}
else
{
if (!m_dateWords.Contains(str))
{
m_dateWords.Add(str);
}
if (str[str.Length - 1] == '.')
{
// Old version ignore the trailing dot in the date words. Support this as well.
string strWithoutDot = str.Substring(0, str.Length - 1);
if (!m_dateWords.Contains(strWithoutDot))
{
m_dateWords.Add(strWithoutDot);
}
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the pattern from the specified index and add the date word/postfix
// when appropriate.
//
// Parameters:
// pattern: The pattern to be scanned.
// index: The starting index to be scanned.
// formatPostfix: The kind of postfix to be scanned.
// Possible values:
// null: This is a regular date word
// "MMMM": month postfix
//
//
////////////////////////////////////////////////////////////////////////////
internal int AddDateWords(string pattern, int index, string? formatPostfix)
{
// Skip any whitespaces so we will start from a letter.
int newIndex = SkipWhiteSpacesAndNonLetter(pattern, index);
if (newIndex != index && formatPostfix != null)
{
// There are whitespaces. This will not be a postfix.
formatPostfix = null;
}
index = newIndex;
// This is the first char added into dateWord.
// Skip all non-letter character. We will add the first letter into DateWord.
StringBuilder dateWord = new StringBuilder();
// We assume that date words should start with a letter.
// Skip anything until we see a letter.
while (index < pattern.Length)
{
char ch = pattern[index];
if (ch == '\'')
{
// We have seen the end of quote. Add the word if we do not see it before,
// and break the while loop.
AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
index++;
break;
}
else if (ch == '\\')
{
//
// Escaped character. Look ahead one character
//
// Skip escaped backslash.
index++;
if (index < pattern.Length)
{
dateWord.Append(pattern[index]);
index++;
}
}
else if (char.IsWhiteSpace(ch))
{
// Found a whitespace. We have to add the current date word/postfix.
AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
if (formatPostfix != null)
{
// Done with postfix. The rest will be regular date word.
formatPostfix = null;
}
// Reset the dateWord.
dateWord.Length = 0;
index++;
}
else
{
dateWord.Append(ch);
index++;
}
}
return (index);
}
////////////////////////////////////////////////////////////////////////////
//
// A simple helper to find the repeat count for a specified char.
//
////////////////////////////////////////////////////////////////////////////
internal static int ScanRepeatChar(string pattern, char ch, int index, out int count)
{
count = 1;
while (++index < pattern.Length && pattern[index] == ch)
{
count++;
}
// Return the updated position.
return (index);
}
////////////////////////////////////////////////////////////////////////////
//
// Add the text that is a date separator but is treated like ignorable symbol.
// E.g.
// hu-HU has:
// short date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd
// long date pattern: yyyy. MMMM d.
// Here, "." is the date separator (derived from short date pattern). However,
// "." also appear at the end of long date pattern. In this case, we just
// "." as ignorable symbol so that the DateTime.Parse() state machine will not
// treat the additional date separator at the end of y,m,d pattern as an error
// condition.
//
////////////////////////////////////////////////////////////////////////////
internal void AddIgnorableSymbols(string? text)
{
if (m_dateWords == null)
{
// Create the date word array.
m_dateWords = new List<string>();
}
// Add the ignorable symbol into the ArrayList.
string temp = IgnorableSymbolChar + text;
if (!m_dateWords.Contains(temp))
{
m_dateWords.Add(temp);
}
}
//
// Flag used to trace the date patterns (yy/yyyyy/M/MM/MMM/MMM/d/dd) that we have seen.
//
private enum FoundDatePattern
{
None = 0x0000,
FoundYearPatternFlag = 0x0001,
FoundMonthPatternFlag = 0x0002,
FoundDayPatternFlag = 0x0004,
FoundYMDPatternFlag = 0x0007, // FoundYearPatternFlag | FoundMonthPatternFlag | FoundDayPatternFlag;
}
// Check if we have found all of the year/month/day pattern.
private FoundDatePattern _ymdFlags = FoundDatePattern.None;
////////////////////////////////////////////////////////////////////////////
//
// Given a date format pattern, scan for date word or postfix.
//
// A date word should be always put in a single quoted string. And it will
// start from a letter, so whitespace and symbols will be ignored before
// the first letter.
//
// Examples of date word:
// 'de' in es-SP: dddd, dd' de 'MMMM' de 'yyyy
// "\x0443." in bg-BG: dd.M.yyyy '\x0433.'
//
// Example of postfix:
// month postfix:
// "ta" in fi-FI: d. MMMM'ta 'yyyy
// Currently, only month postfix is supported.
//
// Usage:
// Always call this with Framework-style pattern, instead of Windows style pattern.
// Windows style pattern uses '' for single quote, while .NET uses \'
//
////////////////////////////////////////////////////////////////////////////
internal void ScanDateWord(string pattern)
{
// Check if we have found all of the year/month/day pattern.
_ymdFlags = FoundDatePattern.None;
int i = 0;
while (i < pattern.Length)
{
char ch = pattern[i];
int chCount;
switch (ch)
{
case '\'':
// Find a beginning quote. Search until the end quote.
i = AddDateWords(pattern, i + 1, null);
break;
case 'M':
i = ScanRepeatChar(pattern, 'M', i, out chCount);
if (chCount >= 4)
{
if (i < pattern.Length && pattern[i] == '\'')
{
i = AddDateWords(pattern, i + 1, "MMMM");
}
}
_ymdFlags |= FoundDatePattern.FoundMonthPatternFlag;
break;
case 'y':
i = ScanRepeatChar(pattern, 'y', i, out chCount);
_ymdFlags |= FoundDatePattern.FoundYearPatternFlag;
break;
case 'd':
i = ScanRepeatChar(pattern, 'd', i, out chCount);
if (chCount <= 2)
{
// Only count "d" & "dd".
// ddd, dddd are day names. Do not count them.
_ymdFlags |= FoundDatePattern.FoundDayPatternFlag;
}
break;
case '\\':
// Found a escaped char not in a quoted string. Skip the current backslash
// and its next character.
i += 2;
break;
case '.':
if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag)
{
// If we find a dot immediately after the we have seen all of the y, m, d pattern.
// treat it as a ignroable symbol. Check for comments in AddIgnorableSymbols for
// more details.
AddIgnorableSymbols(".");
_ymdFlags = FoundDatePattern.None;
}
i++;
break;
default:
if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !char.IsWhiteSpace(ch))
{
// We are not seeing "." after YMD. Clear the flag.
_ymdFlags = FoundDatePattern.None;
}
// We are not in quote. Skip the current character.
i++;
break;
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Given a DTFI, get all of the date words from date patterns and time patterns.
//
////////////////////////////////////////////////////////////////////////////
internal string[]? GetDateWordsOfDTFI(DateTimeFormatInfo dtfi)
{
// Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix.
string[] datePatterns = dtfi.GetAllDateTimePatterns('D');
int i;
// Scan the long date patterns
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the short date patterns
datePatterns = dtfi.GetAllDateTimePatterns('d');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the YearMonth patterns.
datePatterns = dtfi.GetAllDateTimePatterns('y');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the month/day pattern
ScanDateWord(dtfi.MonthDayPattern);
// Scan the long time patterns.
datePatterns = dtfi.GetAllDateTimePatterns('T');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the short time patterns.
datePatterns = dtfi.GetAllDateTimePatterns('t');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
string[]? result = null;
if (m_dateWords != null && m_dateWords.Count > 0)
{
result = new string[m_dateWords.Count];
for (i = 0; i < m_dateWords.Count; i++)
{
result[i] = m_dateWords[i];
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the month names to see if genitive month names are used, and return
// the format flag.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagGenitiveMonth(string[] monthNames, string[] genitveMonthNames, string[] abbrevMonthNames, string[] genetiveAbbrevMonthNames)
{
// If we have different names in regular and genitive month names, use genitive month flag.
return ((!EqualStringArrays(monthNames, genitveMonthNames) || !EqualStringArrays(abbrevMonthNames, genetiveAbbrevMonthNames))
? FORMATFLAGS.UseGenitiveMonth : 0);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the month names to see if spaces are used or start with a digit, and return the format flag
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseSpaceInMonthNames(string[] monthNames, string[] genitveMonthNames, string[] abbrevMonthNames, string[] genetiveAbbrevMonthNames)
{
FORMATFLAGS formatFlags = 0;
formatFlags |= (ArrayElementsBeginWithDigit(monthNames) ||
ArrayElementsBeginWithDigit(genitveMonthNames) ||
ArrayElementsBeginWithDigit(abbrevMonthNames) ||
ArrayElementsBeginWithDigit(genetiveAbbrevMonthNames)
? FORMATFLAGS.UseDigitPrefixInTokens : 0);
formatFlags |= (ArrayElementsHaveSpace(monthNames) ||
ArrayElementsHaveSpace(genitveMonthNames) ||
ArrayElementsHaveSpace(abbrevMonthNames) ||
ArrayElementsHaveSpace(genetiveAbbrevMonthNames)
? FORMATFLAGS.UseSpacesInMonthNames : 0);
return (formatFlags);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the day names and set the correct format flag.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(string[] dayNames, string[] abbrevDayNames)
{
return ((ArrayElementsHaveSpace(dayNames) ||
ArrayElementsHaveSpace(abbrevDayNames))
? FORMATFLAGS.UseSpacesInDayNames : 0);
}
////////////////////////////////////////////////////////////////////////////
//
// Check the calendar to see if it is HebrewCalendar and set the Hebrew format flag if necessary.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseHebrewCalendar(int calID)
{
return (calID == (int)CalendarId.HEBREW ?
FORMATFLAGS.UseHebrewParsing | FORMATFLAGS.UseLeapYearMonth : 0);
}
//-----------------------------------------------------------------------------
// EqualStringArrays
// compares two string arrays and return true if all elements of the first
// array equals to all elements of the second array.
// otherwise it returns false.
//-----------------------------------------------------------------------------
private static bool EqualStringArrays(string[] array1, string[] array2)
{
// Shortcut if they're the same array
if (array1 == array2)
{
return true;
}
// This is effectively impossible
if (array1.Length != array2.Length)
{
return false;
}
// Check each string
for (int i = 0; i < array1.Length; i++)
{
if (array1[i] != array2[i])
{
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// ArrayElementsHaveSpace
// It checks all input array elements if any of them has space character
// returns true if found space character in one of the array elements.
// otherwise returns false.
//-----------------------------------------------------------------------------
private static bool ArrayElementsHaveSpace(string[] array)
{
for (int i = 0; i < array.Length; i++)
{
// it is faster to check for space character manually instead of calling IndexOf
// so we don't have to go to native code side.
for (int j = 0; j < array[i].Length; j++)
{
if (char.IsWhiteSpace(array[i][j]))
{
return true;
}
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////
//
// Check if any element of the array start with a digit.
//
////////////////////////////////////////////////////////////////////////////
private static bool ArrayElementsBeginWithDigit(string[] array)
{
for (int i = 0; i < array.Length; i++)
{
// it is faster to check for space character manually instead of calling IndexOf
// so we don't have to go to native code side.
if (array[i].Length > 0 &&
array[i][0] >= '0' && array[i][0] <= '9')
{
int index = 1;
while (index < array[i].Length && array[i][index] >= '0' && array[i][index] <= '9')
{
// Skip other digits.
index++;
}
if (index == array[i].Length)
{
return (false);
}
if (index == array[i].Length - 1)
{
// Skip known CJK month suffix.
// CJK uses month name like "1\x6708", since \x6708 is a known month suffix,
// we don't need the UseDigitPrefixInTokens since it is slower.
switch (array[i][index])
{
case '\x6708': // CJKMonthSuff
case '\xc6d4': // KoreanMonthSuff
return (false);
}
}
if (index == array[i].Length - 4)
{
// Skip known CJK month suffix.
// Starting with Windows 8, the CJK months for some cultures looks like: "1' \x6708'"
// instead of just "1\x6708"
if (array[i][index] == '\'' && array[i][index + 1] == ' ' &&
array[i][index + 2] == '\x6708' && array[i][index + 3] == '\'')
{
return (false);
}
}
return (true);
}
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Models;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.cache;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.web;
using umbraco.cms.helpers;
using umbraco.DataLayer;
using umbraco.interfaces;
using DataTypeDefinition = umbraco.cms.businesslogic.datatype.DataTypeDefinition;
using Language = umbraco.cms.businesslogic.language.Language;
namespace umbraco.cms.businesslogic.propertytype
{
/// <summary>
/// Summary description for propertytype.
/// </summary>
[Obsolete("Use the ContentTypeService instead")]
public class PropertyType
{
#region Declarations
private readonly int _contenttypeid;
private readonly int _id;
private int _DataTypeId;
private string _alias;
private string _description = "";
private bool _mandatory;
private string _name;
private int _sortOrder;
private int _tabId;
private int _propertyTypeGroup;
private string _validationRegExp = "";
#endregion
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
#region Constructors
public PropertyType(int id)
{
using (IRecordsReader dr = SqlHelper.ExecuteReader(
"Select mandatory, DataTypeId, propertyTypeGroupId, ContentTypeId, sortOrder, alias, name, validationRegExp, description from cmsPropertyType where id=@id",
SqlHelper.CreateParameter("@id", id)))
{
if (!dr.Read())
throw new ArgumentException("Propertytype with id: " + id + " doesnt exist!");
_mandatory = dr.GetBoolean("mandatory");
_id = id;
if (!dr.IsNull("propertyTypeGroupId"))
{
_propertyTypeGroup = dr.GetInt("propertyTypeGroupId");
//TODO: Remove after refactoring!
_tabId = _propertyTypeGroup;
}
_sortOrder = dr.GetInt("sortOrder");
_alias = dr.GetString("alias");
_name = dr.GetString("Name");
_validationRegExp = dr.GetString("validationRegExp");
_DataTypeId = dr.GetInt("DataTypeId");
_contenttypeid = dr.GetInt("contentTypeId");
_description = dr.GetString("description");
}
}
#endregion
#region Properties
public DataTypeDefinition DataTypeDefinition
{
get { return DataTypeDefinition.GetDataTypeDefinition(_DataTypeId); }
set
{
_DataTypeId = value.Id;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set DataTypeId = " + value.Id + " where id=" + Id);
}
}
public int Id
{
get { return _id; }
}
/// <summary>
/// Setting the tab id is not meant to be used directly in code. Use the ContentType SetTabOnPropertyType method instead
/// as that will handle all of the caching properly, this will not.
/// </summary>
/// <remarks>
/// Setting the tab id to a negative value will actually set the value to NULL in the database
/// </remarks>
[Obsolete("Use the new PropertyTypeGroup parameter", false)]
public int TabId
{
get { return _tabId; }
set
{
_tabId = value;
PropertyTypeGroup = value;
InvalidateCache();
}
}
public int PropertyTypeGroup
{
get { return _propertyTypeGroup; }
set
{
_propertyTypeGroup = value;
object dbPropertyTypeGroup = value;
if (value < 1)
{
dbPropertyTypeGroup = DBNull.Value;
}
SqlHelper.ExecuteNonQuery("Update cmsPropertyType set propertyTypeGroupId = @propertyTypeGroupId where id = @id",
SqlHelper.CreateParameter("@propertyTypeGroupId", dbPropertyTypeGroup),
SqlHelper.CreateParameter("@id", Id));
}
}
public bool Mandatory
{
get { return _mandatory; }
set
{
_mandatory = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set mandatory = @mandatory where id = @id",
SqlHelper.CreateParameter("@mandatory", value),
SqlHelper.CreateParameter("@id", Id));
}
}
public string ValidationRegExp
{
get { return _validationRegExp; }
set
{
_validationRegExp = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set validationRegExp = @validationRegExp where id = @id",
SqlHelper.CreateParameter("@validationRegExp", value), SqlHelper.CreateParameter("@id", Id));
}
}
public string Description
{
get
{
if (_description != null)
{
if (!_description.StartsWith("#"))
return _description;
else
{
Language lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name);
if (lang != null)
{
if (Dictionary.DictionaryItem.hasKey(_description.Substring(1, _description.Length - 1)))
{
var di =
new Dictionary.DictionaryItem(_description.Substring(1, _description.Length - 1));
return di.Value(lang.id);
}
}
}
return "[" + _description + "]";
}
return _description;
}
set
{
_description = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set description = @description where id = @id",
SqlHelper.CreateParameter("@description", value),
SqlHelper.CreateParameter("@id", Id));
}
}
public int SortOrder
{
get { return _sortOrder; }
set
{
_sortOrder = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set sortOrder = @sortOrder where id = @id",
SqlHelper.CreateParameter("@sortOrder", value),
SqlHelper.CreateParameter("@id", Id));
}
}
public string Alias
{
get { return _alias; }
set
{
_alias = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery("Update cmsPropertyType set alias = @alias where id= @id",
SqlHelper.CreateParameter("@alias", Casing.SafeAliasWithForcingCheck(_alias)),
SqlHelper.CreateParameter("@id", Id));
}
}
public int ContentTypeId
{
get { return _contenttypeid; }
}
public string Name
{
get
{
if (!_name.StartsWith("#"))
return _name;
else
{
Language lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name);
if (lang != null)
{
if (Dictionary.DictionaryItem.hasKey(_name.Substring(1, _name.Length - 1)))
{
var di = new Dictionary.DictionaryItem(_name.Substring(1, _name.Length - 1));
return di.Value(lang.id);
}
}
return "[" + _name + "]";
}
}
set
{
_name = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"UPDATE cmsPropertyType SET name=@name WHERE id=@id",
SqlHelper.CreateParameter("@name", _name),
SqlHelper.CreateParameter("@id", Id));
}
}
#endregion
#region Methods
public string GetRawName()
{
return _name;
}
public string GetRawDescription()
{
return _description;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static PropertyType MakeNew(DataTypeDefinition dt, ContentType ct, string name, string alias)
{
//make sure that the alias starts with a letter
if (string.IsNullOrEmpty(alias))
throw new ArgumentNullException("alias");
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (!Char.IsLetter(alias[0]))
throw new ArgumentException("alias must start with a letter", "alias");
PropertyType pt;
try
{
// The method is synchronized, but we'll still look it up with an additional parameter (alias)
SqlHelper.ExecuteNonQuery(
"INSERT INTO cmsPropertyType (DataTypeId, ContentTypeId, alias, name) VALUES (@DataTypeId, @ContentTypeId, @alias, @name)",
SqlHelper.CreateParameter("@DataTypeId", dt.Id),
SqlHelper.CreateParameter("@ContentTypeId", ct.Id),
SqlHelper.CreateParameter("@alias", alias),
SqlHelper.CreateParameter("@name", name));
pt =
new PropertyType(
SqlHelper.ExecuteScalar<int>("SELECT MAX(id) FROM cmsPropertyType WHERE alias=@alias",
SqlHelper.CreateParameter("@alias", alias)));
}
finally
{
// Clear cached items
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(CacheKeys.PropertyTypeCacheKey);
}
return pt;
}
public static PropertyType[] GetAll()
{
var result = GetPropertyTypes();
return result.ToArray();
}
public static IEnumerable<PropertyType> GetPropertyTypes()
{
var result = new List<PropertyType>();
using (IRecordsReader dr =
SqlHelper.ExecuteReader("select id from cmsPropertyType order by Name"))
{
while (dr.Read())
{
PropertyType pt = GetPropertyType(dr.GetInt("id"));
if (pt != null)
result.Add(pt);
}
}
return result;
}
public static IEnumerable<PropertyType> GetPropertyTypesByGroup(int groupId, List<int> contentTypeIds)
{
return GetPropertyTypesByGroup(groupId).Where(x => contentTypeIds.Contains(x.ContentTypeId));
}
public static IEnumerable<PropertyType> GetPropertyTypesByGroup(int groupId)
{
var result = new List<PropertyType>();
using (IRecordsReader dr =
SqlHelper.ExecuteReader("SELECT id FROM cmsPropertyType WHERE propertyTypeGroupId = @groupId order by SortOrder",
SqlHelper.CreateParameter("@groupId", groupId)))
{
while (dr.Read())
{
PropertyType pt = GetPropertyType(dr.GetInt("id"));
if (pt != null)
result.Add(pt);
}
}
return result;
}
/// <summary>
/// Returns all property types based on the data type definition
/// </summary>
/// <param name="dataTypeDefId"></param>
/// <returns></returns>
public static IEnumerable<PropertyType> GetByDataTypeDefinition(int dataTypeDefId)
{
var result = new List<PropertyType>();
using (IRecordsReader dr =
SqlHelper.ExecuteReader(
"select id, Name from cmsPropertyType where dataTypeId=@dataTypeId order by Name",
SqlHelper.CreateParameter("@dataTypeId", dataTypeDefId)))
{
while (dr.Read())
{
PropertyType pt = GetPropertyType(dr.GetInt("id"));
if (pt != null)
result.Add(pt);
}
}
return result.ToList();
}
public void delete()
{
// flush cache
FlushCache();
// Delete all properties of propertytype
CleanPropertiesOnDeletion(_contenttypeid);
//delete tag refs
SqlHelper.ExecuteNonQuery("Delete from cmsTagRelationship where propertyTypeId = " + Id);
// Delete PropertyType ..
SqlHelper.ExecuteNonQuery("Delete from cmsPropertyType where id = " + Id);
// delete cache from either master (via tabid) or current contentype
FlushCacheBasedOnTab();
InvalidateCache();
}
public void FlushCacheBasedOnTab()
{
if (TabId != 0)
{
ContentType.FlushFromCache(ContentType.Tab.GetTab(TabId).ContentType);
}
else
{
ContentType.FlushFromCache(ContentTypeId);
}
}
private void CleanPropertiesOnDeletion(int contentTypeId)
{
// first delete from all master document types
//TODO: Verify no endless loops with mixins
DocumentType.GetAllAsList().FindAll(dt => dt.MasterContentTypes.Contains(contentTypeId)).ForEach(
dt => CleanPropertiesOnDeletion(dt.Id));
//Initially Content.getContentOfContentType() was called, but because this doesn't include members we resort to sql lookups and deletes
var tmp = new List<int>();
IRecordsReader dr = SqlHelper.ExecuteReader("SELECT nodeId FROM cmsContent INNER JOIN umbracoNode ON cmsContent.nodeId = umbracoNode.id WHERE ContentType = " + contentTypeId + " ORDER BY umbracoNode.text ");
while (dr.Read()) tmp.Add(dr.GetInt("nodeId"));
dr.Close();
foreach (var contentId in tmp)
{
SqlHelper.ExecuteNonQuery("DELETE FROM cmsPropertyData WHERE PropertyTypeId =" + this.Id + " AND contentNodeId = " + contentId);
}
// invalidate content type cache
ContentType.FlushFromCache(contentTypeId);
}
public IDataType GetEditControl(object value, bool isPostBack)
{
IDataType dt = DataTypeDefinition.DataType;
dt.DataEditor.Editor.ID = Alias;
IData df = DataTypeDefinition.DataType.Data;
(dt.DataEditor.Editor).ID = Alias;
if (!isPostBack)
{
if (value != null)
dt.Data.Value = value;
else
dt.Data.Value = "";
}
return dt;
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public virtual void Save()
{
FlushCache();
}
protected virtual void FlushCache()
{
// clear local cache
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(GetCacheKey(Id));
// clear cache in contentype
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(CacheKeys.ContentTypePropertiesCacheKey + _contenttypeid);
//Ensure that DocumentTypes are reloaded from db by clearing cache - this similar to the Save method on DocumentType.
//NOTE Would be nice if we could clear cache by type instead of emptying the entire cache.
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IContent>();
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IContentType>();
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IMedia>();
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IMediaType>();
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IMember>();
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IMemberType>();
}
public static PropertyType GetPropertyType(int id)
{
return ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem<PropertyType>(
GetCacheKey(id),
timeout: TimeSpan.FromMinutes(30),
getCacheItem: () =>
{
try
{
return new PropertyType(id);
}
catch
{
return null;
}
});
}
private void InvalidateCache()
{
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(GetCacheKey(Id));
}
private static string GetCacheKey(int id)
{
return CacheKeys.PropertyTypeCacheKey + id;
}
#endregion
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections;
using NUnit.Framework;
namespace NUnit.Core.Tests
{
/// <summary>
/// Summary description for PlatformHelperTests.
/// </summary>
[TestFixture]
public class PlatformDetectionTests
{
private static readonly PlatformHelper win95Helper = new PlatformHelper(
new OSPlatform( PlatformID.Win32Windows , new Version( 4, 0 ) ),
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) );
private static readonly PlatformHelper winXPHelper = new PlatformHelper(
new OSPlatform( PlatformID.Win32NT , new Version( 5,1 ) ),
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) );
private void CheckOSPlatforms( OSPlatform os,
string expectedPlatforms )
{
CheckPlatforms(
new PlatformHelper( os, RuntimeFramework.CurrentFramework ),
expectedPlatforms,
PlatformHelper.OSPlatforms );
}
private void CheckRuntimePlatforms( RuntimeFramework runtimeFramework,
string expectedPlatforms )
{
CheckPlatforms(
new PlatformHelper( OSPlatform.CurrentPlatform, runtimeFramework ),
expectedPlatforms,
PlatformHelper.RuntimePlatforms + ",NET-1.0,NET-1.1,NET-2.0,MONO-1.0,MONO-2.0" );
}
private void CheckPlatforms( PlatformHelper helper,
string expectedPlatforms, string checkPlatforms )
{
string[] expected = expectedPlatforms.Split( new char[] { ',' } );
string[] check = checkPlatforms.Split( new char[] { ',' } );
foreach( string testPlatform in check )
{
bool shouldPass = false;
foreach( string platform in expected )
if ( shouldPass = platform.ToLower() == testPlatform.ToLower() )
break;
bool didPass = helper.IsPlatformSupported( testPlatform );
if ( shouldPass && !didPass )
Assert.Fail( "Failed to detect {0}", testPlatform );
else if ( didPass && !shouldPass )
Assert.Fail( "False positive on {0}", testPlatform );
else if ( !shouldPass && !didPass )
Assert.AreEqual( "Only supported on " + testPlatform, helper.Reason );
}
}
[Test]
public void DetectWin95()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 0 ) ),
"Win95,Win32Windows,Win32,Win" );
}
[Test]
public void DetectWin98()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 10 ) ),
"Win98,Win32Windows,Win32,Win" );
}
[Test]
public void DetectWinMe()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 90 ) ),
"WinMe,Win32Windows,Win32,Win" );
}
// WinCE isn't defined in .NET 1.0.
[Test, Platform(Exclude="Net-1.0")]
public void DetectWinCE()
{
PlatformID winCE = (PlatformID)Enum.Parse(typeof(PlatformID), "WinCE");
CheckOSPlatforms(
new OSPlatform(winCE, new Version(1, 0)),
"WinCE,Win32,Win" );
}
[Test]
public void DetectNT3()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 3, 51 ) ),
"NT3,Win32NT,Win32,Win" );
}
[Test]
public void DetectNT4()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 4, 0 ) ),
"NT4,Win32NT,Win32,Win,Win-4.0" );
}
[Test]
public void DetectWin2K()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 0 ) ),
"Win2K,NT5,Win32NT,Win32,Win,Win-5.0" );
}
[Test]
public void DetectWinXP()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 1 ) ),
"WinXP,NT5,Win32NT,Win32,Win,Win-5.1" );
}
[Test]
public void DetectWinXPProfessionalX64()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 2 ), OSPlatform.ProductType.WorkStation ),
"WinXP,NT5,Win32NT,Win32,Win,Win-5.1" );
}
[Test]
public void DetectWin2003Server()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(5, 2), OSPlatform.ProductType.Server),
"Win2003Server,NT5,Win32NT,Win32,Win,Win-5.2");
}
[Test]
public void DetectVista()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.WorkStation),
"Vista,NT6,Win32NT,Win32,Win,Win-6.0");
}
[Test]
public void DetectWin2008ServerOriginal()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.Server),
"Win2008Server,NT6,Win32NT,Win32,Win,Win-6.0");
}
[Test]
public void DetectWin2008ServerR2()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.Server),
"Win2008Server,Win2008ServerR2,NT6,Win32NT,Win32,Win,Win-6.1");
}
[Test]
public void DetectWindows7()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.WorkStation),
"Windows7,NT6,Win32NT,Win32,Win,Win-6.1");
}
[Test]
public void DetectUnixUnderMicrosoftDotNet()
{
CheckOSPlatforms(
new OSPlatform(OSPlatform.UnixPlatformID_Microsoft, new Version()),
"UNIX,Linux");
}
// This throws under Microsoft .Net due to the invlaid enumeration value of 128
[Test, Platform(Exclude="Net")]
public void DetectUnixUnderMono()
{
CheckOSPlatforms(
new OSPlatform(OSPlatform.UnixPlatformID_Mono, new Version()),
"UNIX,Linux");
}
[Test]
public void DetectNet10()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 1, 0, 3705, 0 ) ),
"NET,NET-1.0" );
}
[Test]
public void DetectNet11()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ),
"NET,NET-1.1" );
}
[Test]
public void DetectNet20()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 2, 0, 40607, 0 ) ),
"Net,Net-2.0" );
}
[Test]
public void DetectNet40()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Net, new Version(4, 0, 20506, 0)),
"Net,Net-4.0");
}
[Test]
public void DetectNetCF()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.NetCF, new Version( 1, 1, 4322, 0 ) ),
"NetCF" );
}
[Test]
public void DetectSSCLI()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.SSCLI, new Version( 1, 0, 3, 0 ) ),
"SSCLI,Rotor" );
}
[Test]
public void DetectMono10()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Mono, new Version( 1, 1, 4322, 0 ) ),
"Mono,Mono-1.0" );
}
[Test]
public void DetectMono20()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Mono, new Version( 2, 0, 40607, 0 ) ),
"Mono,Mono-2.0" );
}
[Test]
public void DetectExactVersion()
{
Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322" ) );
Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322.0" ) );
Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4323.0" ) );
Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4322.1" ) );
}
[Test]
public void ArrayOfPlatforms()
{
string[] platforms = new string[] { "NT4", "Win2K", "WinXP" };
Assert.IsTrue( winXPHelper.IsPlatformSupported( platforms ) );
Assert.IsFalse( win95Helper.IsPlatformSupported( platforms ) );
}
[Test]
public void PlatformAttribute_Include()
{
PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual("Only supported on Win2K,WinXP,NT4", win95Helper.Reason);
}
[Test]
public void PlatformAttribute_Exclude()
{
PlatformAttribute attr = new PlatformAttribute();
attr.Exclude = "Win2K,WinXP,NT4";
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Not supported on Win2K,WinXP,NT4", winXPHelper.Reason );
Assert.IsTrue( win95Helper.IsPlatformSupported( attr ) );
}
[Test]
public void PlatformAttribute_IncludeAndExclude()
{
PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
attr.Exclude = "Mono";
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
attr.Exclude = "Net";
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Not supported on Net", winXPHelper.Reason );
}
[Test]
public void PlatformAttribute_InvalidPlatform()
{
PlatformAttribute attr = new PlatformAttribute( "Net-1.0,Net11,Mono" );
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Invalid platform name: Net11", winXPHelper.Reason );
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Xml.Serialization;
using Gallio.Common;
using Gallio.Common.Media;
using Gallio.Common.Normalization;
namespace Gallio.Common.Markup
{
/// <summary>
/// An attachment is an embedded object in a markup document. An attachment must specify a
/// content type (a MIME type), and some contents.
/// </summary>
[Serializable]
public abstract class Attachment : INormalizable<Attachment>
{
private readonly string name;
private readonly string contentType;
/// <summary>
/// Creates an attachment.
/// </summary>
/// <param name="name">The name of attachment, or null to automatically assign one. The attachment
/// name must be unique within the scope of the currently executing test step.</param>
/// <param name="contentType">The content type, not null.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="contentType"/> is null.</exception>
internal /*to prevent subclassing outside of the framework*/ Attachment(string name, string contentType)
{
if (name != null && name.Length > 100)
throw new ArgumentException("name must be 100 chars or less", "name");
if (contentType == null)
throw new ArgumentNullException("contentType");
this.name = name ?? Hash64.CreateUniqueHash().ToString();
this.contentType = contentType;
}
/// <summary>
/// Gets the name of the attachment, not null.
/// </summary>
public string Name
{
get { return name; }
}
/// <summary>
/// Gets the content type of the attachment specified as a MIME type, not null.
/// <seealso cref="MimeTypes"/> for definitions of common supported MIME types.
/// </summary>
public string ContentType
{
get { return contentType; }
}
/// <summary>
/// Creates a plain text attachment.
/// </summary>
/// <param name="name">The attachment name, or null to automatically assign one.</param>
/// <param name="text">The text string, not null.</param>
/// <returns>The attachment.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="text"/> is null.</exception>
public static TextAttachment CreatePlainTextAttachment(string name, string text)
{
return new TextAttachment(name, MimeTypes.PlainText, text);
}
/// <summary>
/// Creates an HTML attachment.
/// </summary>
/// <param name="name">The attachment name, or null to automatically assign one.</param>
/// <param name="html">The html string, not null.</param>
/// <returns>The attachment.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="html"/> is null.</exception>
public static TextAttachment CreateHtmlAttachment(string name, string html)
{
return new TextAttachment(name, MimeTypes.Html, html);
}
/// <summary>
/// Creates an XHTML attachment.
/// </summary>
/// <param name="name">The attachment name, or null to automatically assign one.</param>
/// <param name="xhtml">The xhtml string, not null.</param>
/// <returns>The attachment.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="xhtml"/> is null.</exception>
public static TextAttachment CreateXHtmlAttachment(string name, string xhtml)
{
return new TextAttachment(name, MimeTypes.XHtml, xhtml);
}
/// <summary>
/// Creates an XML attachment.
/// </summary>
/// <param name="name">The attachment name, or null to automatically assign one.</param>
/// <param name="xml">The XML string, not null.</param>
/// <returns>The attachment.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="xml"/> is null.</exception>
public static TextAttachment CreateXmlAttachment(string name, string xml)
{
return new TextAttachment(name, MimeTypes.Xml, xml);
}
/// <summary>
/// Creates an image attachment with a mime-type compatible with its internal representation.
/// </summary>
/// <param name="name">The attachment name, or null to automatically assign one.</param>
/// <param name="image">The image to attach.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="image"/> is null.</exception>
public static BinaryAttachment CreateImageAttachment(string name, Image image)
{
if (image == null)
throw new ArgumentNullException("image");
// TODO: Choose a better mime-type based on the image format.
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, ImageFormat.Png);
return new BinaryAttachment(name, MimeTypes.Png, stream.ToArray());
}
}
/// <summary>
/// Creates an video attachment with a mime-type compatible with its internal representation.
/// </summary>
/// <param name="name">The attachment name, or null to automatically assign one.</param>
/// <param name="video">The video to attach.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="video"/> is null.</exception>
public static BinaryAttachment CreateVideoAttachment(string name, Video video)
{
if (video == null)
throw new ArgumentNullException("video");
using (MemoryStream stream = new MemoryStream())
{
video.Save(stream);
return new BinaryAttachment(name, video.MimeType, stream.ToArray());
}
}
/// <summary>
/// Creates XML attachment with mime-type <see cref="MimeTypes.Xml" /> by serializing an object.
/// </summary>
/// <param name="name">The attachment name, or null to automatically assign one.</param>
/// <param name="obj">The object to serialize and embed, must not be null.</param>
/// <param name="xmlSerializer">The xml serializer to use, or null to use the default based on the object's type.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="obj"/> is null.</exception>
/// <seealso cref="XmlSerializer"/>
public static TextAttachment CreateObjectAsXmlAttachment(string name, object obj, XmlSerializer xmlSerializer)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (xmlSerializer == null)
xmlSerializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
xmlSerializer.Serialize(writer, obj);
return CreateXmlAttachment(name, writer.ToString());
}
}
/// <summary>
/// Generates serializable attachment data from an attachment.
/// </summary>
/// <returns>The attachment data.</returns>
public abstract AttachmentData ToAttachmentData();
/// <summary>
/// Recovers the attachment information from serializable attachment data.
/// </summary>
/// <param name="data">The attachment data.</param>
/// <returns>The attachment.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="data"/> is null.</exception>
public static Attachment FromAttachmentData(AttachmentData data)
{
if (data == null)
throw new ArgumentNullException("data");
return (data.Type == AttachmentType.Text)
? (Attachment)new TextAttachment(data.Name, data.ContentType, data.GetText())
: (Attachment)new BinaryAttachment(data.Name, data.ContentType, data.GetBytes());
}
/// <inheritdoc />
public abstract Attachment Normalize();
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel; // need this for the properties metadata
using System.Xml;
using System.Text.RegularExpressions;
using fyiReporting.RDL;
namespace fyiReporting.CRI
{
/// <summary>
/// BarCodeBookland: create Bookland compatible BarCode images.
/// See http://www.barcodeisland.com/bookland.phtml for description of how to
/// construct a Bookland compatible barcode. In essence, Bookland is simply
/// EAN-13 barcode with a number system of 978.
/// </summary>
public class BarCodeBookland: ICustomReportItem
{
string _ISBN; // ISBN number
BarCodeEAN13 _Ean13; // the EAN-13 barcode object
public BarCodeBookland() // Need to be able to create an instance
{
_Ean13 = new BarCodeEAN13();
}
#region ICustomReportItem Members
/// <summary>
/// Runtime: Draw the BarCode
/// </summary>
/// <param name="bm">Bitmap to draw the barcode in.</param>
public void DrawImage(ref System.Drawing.Bitmap bm)
{
_Ean13.DrawImage(ref bm);
}
/// <summary>
/// Design time: Draw a hard coded BarCode for design time; Parameters can't be
/// relied on since they aren't available.
/// </summary>
/// <param name="bm"></param>
public void DrawDesignerImage(ref System.Drawing.Bitmap bm)
{
_Ean13.DrawImage(bm, "978015602732"); // Yann Martel-Life of Pi
}
/// <summary>
/// BarCode isn't a DataRegion
/// </summary>
/// <returns></returns>
public bool IsDataRegion()
{
return false;
}
/// <summary>
/// Set the properties; No validation is done at this time.
/// </summary>
/// <param name="props"></param>
public void SetProperties(IDictionary<string, object> props)
{
try
{
string p = props["ISBN"] as string;
if (p == null)
throw new Exception("ISBN property must be a string.");
// remove any dashes
p = p.Replace("-", "");
if (p.Length > 9) // get rid of the ISBN checksum digit
p = p.Substring(0, 9);
if (!Regex.IsMatch(p, "^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$"))
throw new Exception("ISBN must have at least nine digits.");
_ISBN = p;
// Now set the properties of the EAN-13
IDictionary<string, object> ean13_props = new Dictionary<string, object>();
ean13_props.Add("NumberSystem", "97");
ean13_props.Add("ManufacturerCode", "8" + _ISBN.Substring(0, 4));
ean13_props.Add("ProductCode", _ISBN.Substring(4,5));
_Ean13.SetProperties(ean13_props);
}
catch (KeyNotFoundException )
{
throw new Exception("ISBN property must be specified");
}
return;
}
/// <summary>
/// Design time call: return string with <CustomReportItem> ... </CustomReportItem> syntax for
/// the insert. The string contains a variable {0} which will be substituted with the
/// configuration name. This allows the name to be completely controlled by
/// the configuration file.
/// </summary>
/// <returns></returns>
public string GetCustomReportItemXml()
{
return "<CustomReportItem><Type>{0}</Type>" +
string.Format("<Height>{0}mm</Height><Width>{1}mm</Width>", BarCodeEAN13.OptimalHeight, BarCodeEAN13.OptimalWidth) +
"<CustomProperties>" +
"<CustomProperty>" +
"<Name>ISBN</Name>" +
"<Value>0-15-602732-1</Value>" + // Yann Martel- Life of Pi
"</CustomProperty>" +
"</CustomProperties>" +
"</CustomReportItem>";
}
/// <summary>
/// Return an instance of the class representing the properties.
/// This method is called at design time;
/// </summary>
/// <returns></returns>
public object GetPropertiesInstance(XmlNode iNode)
{
BarCodeBooklandProperties bcp = new BarCodeBooklandProperties(this, iNode);
foreach (XmlNode n in iNode.ChildNodes)
{
if (n.Name != "CustomProperty")
continue;
string pname = this.GetNamedElementValue(n, "Name", "");
switch (pname)
{
case "ISBN":
bcp.SetISBN(GetNamedElementValue(n, "Value", "0-15-602732-1"));
break;
default:
break;
}
}
return bcp;
}
/// <summary>
/// Set the custom properties given the properties object
/// </summary>
/// <param name="node"></param>
/// <param name="inst"></param>
public void SetPropertiesInstance(XmlNode node, object inst)
{
node.RemoveAll(); // Get rid of all properties
BarCodeBooklandProperties bcp = inst as BarCodeBooklandProperties;
if (bcp == null)
return;
// ISBN
CreateChild(node, "ISBN", bcp.ISBN);
}
void CreateChild(XmlNode node, string nm, string val)
{
XmlDocument xd = node.OwnerDocument;
XmlNode cp = xd.CreateElement("CustomProperty");
node.AppendChild(cp);
XmlNode name = xd.CreateElement("Name");
name.InnerText = nm;
cp.AppendChild(name);
XmlNode v = xd.CreateElement("Value");
v.InnerText = val;
cp.AppendChild(v);
}
public void Dispose()
{
_Ean13.Dispose();
return;
}
#endregion
/// <summary>
/// Get the child element with the specified name. Return the InnerText
/// value if found otherwise return the passed default.
/// </summary>
/// <param name="xNode">Parent node</param>
/// <param name="name">Name of child node to look for</param>
/// <param name="def">Default value to use if not found</param>
/// <returns>Value the named child node</returns>
string GetNamedElementValue(XmlNode xNode, string name, string def)
{
if (xNode == null)
return def;
foreach (XmlNode cNode in xNode.ChildNodes)
{
if (cNode.NodeType == XmlNodeType.Element &&
cNode.Name == name)
return cNode.InnerText;
}
return def;
}
/// <summary>
/// BarCodeProperties- All properties are type string to allow for definition of
/// a runtime expression.
/// </summary>
public class BarCodeBooklandProperties
{
BarCodeBookland _bcbl;
XmlNode _node;
string _ISBN;
internal BarCodeBooklandProperties(BarCodeBookland bcbl, XmlNode node)
{
_bcbl = bcbl;
_node = node;
}
internal void SetISBN(string isbn)
{
_ISBN = isbn;
}
[Category("BarCode"),
Description("ISBN is the book's ISBN number.")]
public string ISBN
{
get { return _ISBN; }
set
{
_ISBN = value;
_bcbl.SetPropertiesInstance(_node, this);
}
}
}
}
}
| |
// -------------------------------------------------------------------------------------------------------------------
// Generated code, do not edit
// Command Line: DomGen "level_editor.xsd" "Schema.cs" "gap" "LevelEditor"
// -------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Sce.Atf.Dom;
namespace LevelEditor
{
public static class Schema
{
public const string NS = "gap";
public static void Initialize(XmlSchemaTypeCollection typeCollection)
{
Initialize((ns,name)=>typeCollection.GetNodeType(ns,name),
(ns,name)=>typeCollection.GetRootElement(ns,name));
}
public static void Initialize(IDictionary<string, XmlSchemaTypeCollection> typeCollections)
{
Initialize((ns,name)=>typeCollections[ns].GetNodeType(name),
(ns,name)=>typeCollections[ns].GetRootElement(name));
}
private static void Initialize(Func<string, string, DomNodeType> getNodeType, Func<string, string, ChildInfo> getRootElement)
{
gameType.Type = getNodeType("gap", "gameType");
gameType.nameAttribute = gameType.Type.GetAttributeInfo("name");
gameType.gameObjectFolderChild = gameType.Type.GetChildInfo("gameObjectFolder");
gameType.layersChild = gameType.Type.GetChildInfo("layers");
gameType.bookmarksChild = gameType.Type.GetChildInfo("bookmarks");
gameType.gameReferenceChild = gameType.Type.GetChildInfo("gameReference");
gameType.gridChild = gameType.Type.GetChildInfo("grid");
gameObjectFolderType.Type = getNodeType("gap", "gameObjectFolderType");
gameObjectFolderType.nameAttribute = gameObjectFolderType.Type.GetAttributeInfo("name");
gameObjectFolderType.visibleAttribute = gameObjectFolderType.Type.GetAttributeInfo("visible");
gameObjectFolderType.lockedAttribute = gameObjectFolderType.Type.GetAttributeInfo("locked");
gameObjectFolderType.gameObjectChild = gameObjectFolderType.Type.GetChildInfo("gameObject");
gameObjectFolderType.folderChild = gameObjectFolderType.Type.GetChildInfo("folder");
gameObjectType.Type = getNodeType("gap", "gameObjectType");
gameObjectType.transformAttribute = gameObjectType.Type.GetAttributeInfo("transform");
gameObjectType.translateAttribute = gameObjectType.Type.GetAttributeInfo("translate");
gameObjectType.rotateAttribute = gameObjectType.Type.GetAttributeInfo("rotate");
gameObjectType.scaleAttribute = gameObjectType.Type.GetAttributeInfo("scale");
gameObjectType.pivotAttribute = gameObjectType.Type.GetAttributeInfo("pivot");
gameObjectType.transformationTypeAttribute = gameObjectType.Type.GetAttributeInfo("transformationType");
gameObjectType.nameAttribute = gameObjectType.Type.GetAttributeInfo("name");
gameObjectType.visibleAttribute = gameObjectType.Type.GetAttributeInfo("visible");
gameObjectType.lockedAttribute = gameObjectType.Type.GetAttributeInfo("locked");
transformObjectType.Type = getNodeType("gap", "transformObjectType");
transformObjectType.transformAttribute = transformObjectType.Type.GetAttributeInfo("transform");
transformObjectType.translateAttribute = transformObjectType.Type.GetAttributeInfo("translate");
transformObjectType.rotateAttribute = transformObjectType.Type.GetAttributeInfo("rotate");
transformObjectType.scaleAttribute = transformObjectType.Type.GetAttributeInfo("scale");
transformObjectType.pivotAttribute = transformObjectType.Type.GetAttributeInfo("pivot");
transformObjectType.transformationTypeAttribute = transformObjectType.Type.GetAttributeInfo("transformationType");
layersType.Type = getNodeType("gap", "layersType");
layersType.layerChild = layersType.Type.GetChildInfo("layer");
layerType.Type = getNodeType("gap", "layerType");
layerType.nameAttribute = layerType.Type.GetAttributeInfo("name");
layerType.gameObjectReferenceChild = layerType.Type.GetChildInfo("gameObjectReference");
layerType.layerChild = layerType.Type.GetChildInfo("layer");
gameObjectReferenceType.Type = getNodeType("gap", "gameObjectReferenceType");
gameObjectReferenceType.refAttribute = gameObjectReferenceType.Type.GetAttributeInfo("ref");
bookmarksType.Type = getNodeType("gap", "bookmarksType");
bookmarksType.bookmarkChild = bookmarksType.Type.GetChildInfo("bookmark");
bookmarkType.Type = getNodeType("gap", "bookmarkType");
bookmarkType.nameAttribute = bookmarkType.Type.GetAttributeInfo("name");
bookmarkType.cameraChild = bookmarkType.Type.GetChildInfo("camera");
bookmarkType.bookmarkChild = bookmarkType.Type.GetChildInfo("bookmark");
cameraType.Type = getNodeType("gap", "cameraType");
cameraType.eyeAttribute = cameraType.Type.GetAttributeInfo("eye");
cameraType.lookAtPointAttribute = cameraType.Type.GetAttributeInfo("lookAtPoint");
cameraType.upVectorAttribute = cameraType.Type.GetAttributeInfo("upVector");
cameraType.viewTypeAttribute = cameraType.Type.GetAttributeInfo("viewType");
cameraType.yFovAttribute = cameraType.Type.GetAttributeInfo("yFov");
cameraType.nearZAttribute = cameraType.Type.GetAttributeInfo("nearZ");
cameraType.farZAttribute = cameraType.Type.GetAttributeInfo("farZ");
cameraType.focusRadiusAttribute = cameraType.Type.GetAttributeInfo("focusRadius");
gameReferenceType.Type = getNodeType("gap", "gameReferenceType");
gameReferenceType.nameAttribute = gameReferenceType.Type.GetAttributeInfo("name");
gameReferenceType.refAttribute = gameReferenceType.Type.GetAttributeInfo("ref");
gameReferenceType.tagsAttribute = gameReferenceType.Type.GetAttributeInfo("tags");
gridType.Type = getNodeType("gap", "gridType");
gridType.sizeAttribute = gridType.Type.GetAttributeInfo("size");
gridType.subdivisionsAttribute = gridType.Type.GetAttributeInfo("subdivisions");
gridType.heightAttribute = gridType.Type.GetAttributeInfo("height");
gridType.snapAttribute = gridType.Type.GetAttributeInfo("snap");
gridType.visibleAttribute = gridType.Type.GetAttributeInfo("visible");
prototypeType.Type = getNodeType("gap", "prototypeType");
prototypeType.gameObjectChild = prototypeType.Type.GetChildInfo("gameObject");
prefabType.Type = getNodeType("gap", "prefabType");
prefabType.gameObjectChild = prefabType.Type.GetChildInfo("gameObject");
textureMetadataType.Type = getNodeType("gap", "textureMetadataType");
textureMetadataType.uriAttribute = textureMetadataType.Type.GetAttributeInfo("uri");
textureMetadataType.keywordsAttribute = textureMetadataType.Type.GetAttributeInfo("keywords");
textureMetadataType.compressionSettingAttribute = textureMetadataType.Type.GetAttributeInfo("compressionSetting");
textureMetadataType.memoryLayoutAttribute = textureMetadataType.Type.GetAttributeInfo("memoryLayout");
textureMetadataType.mipMapAttribute = textureMetadataType.Type.GetAttributeInfo("mipMap");
textureMetadataType.colorSpaceAttribute = textureMetadataType.Type.GetAttributeInfo("colorSpace");
resourceMetadataType.Type = getNodeType("gap", "resourceMetadataType");
resourceMetadataType.uriAttribute = resourceMetadataType.Type.GetAttributeInfo("uri");
resourceMetadataType.keywordsAttribute = resourceMetadataType.Type.GetAttributeInfo("keywords");
resourceReferenceType.Type = getNodeType("gap", "resourceReferenceType");
resourceReferenceType.uriAttribute = resourceReferenceType.Type.GetAttributeInfo("uri");
visibleTransformObjectType.Type = getNodeType("gap", "visibleTransformObjectType");
visibleTransformObjectType.transformAttribute = visibleTransformObjectType.Type.GetAttributeInfo("transform");
visibleTransformObjectType.translateAttribute = visibleTransformObjectType.Type.GetAttributeInfo("translate");
visibleTransformObjectType.rotateAttribute = visibleTransformObjectType.Type.GetAttributeInfo("rotate");
visibleTransformObjectType.scaleAttribute = visibleTransformObjectType.Type.GetAttributeInfo("scale");
visibleTransformObjectType.pivotAttribute = visibleTransformObjectType.Type.GetAttributeInfo("pivot");
visibleTransformObjectType.transformationTypeAttribute = visibleTransformObjectType.Type.GetAttributeInfo("transformationType");
visibleTransformObjectType.visibleAttribute = visibleTransformObjectType.Type.GetAttributeInfo("visible");
visibleTransformObjectType.lockedAttribute = visibleTransformObjectType.Type.GetAttributeInfo("locked");
transformObjectGroupType.Type = getNodeType("gap", "transformObjectGroupType");
transformObjectGroupType.transformAttribute = transformObjectGroupType.Type.GetAttributeInfo("transform");
transformObjectGroupType.translateAttribute = transformObjectGroupType.Type.GetAttributeInfo("translate");
transformObjectGroupType.rotateAttribute = transformObjectGroupType.Type.GetAttributeInfo("rotate");
transformObjectGroupType.scaleAttribute = transformObjectGroupType.Type.GetAttributeInfo("scale");
transformObjectGroupType.pivotAttribute = transformObjectGroupType.Type.GetAttributeInfo("pivot");
transformObjectGroupType.transformationTypeAttribute = transformObjectGroupType.Type.GetAttributeInfo("transformationType");
transformObjectGroupType.visibleAttribute = transformObjectGroupType.Type.GetAttributeInfo("visible");
transformObjectGroupType.lockedAttribute = transformObjectGroupType.Type.GetAttributeInfo("locked");
transformObjectGroupType.objectChild = transformObjectGroupType.Type.GetChildInfo("object");
gameObjectComponentType.Type = getNodeType("gap", "gameObjectComponentType");
gameObjectComponentType.nameAttribute = gameObjectComponentType.Type.GetAttributeInfo("name");
gameObjectComponentType.activeAttribute = gameObjectComponentType.Type.GetAttributeInfo("active");
transformComponentType.Type = getNodeType("gap", "transformComponentType");
transformComponentType.nameAttribute = transformComponentType.Type.GetAttributeInfo("name");
transformComponentType.activeAttribute = transformComponentType.Type.GetAttributeInfo("active");
transformComponentType.translationAttribute = transformComponentType.Type.GetAttributeInfo("translation");
transformComponentType.rotationAttribute = transformComponentType.Type.GetAttributeInfo("rotation");
transformComponentType.scaleAttribute = transformComponentType.Type.GetAttributeInfo("scale");
gameObjectWithComponentType.Type = getNodeType("gap", "gameObjectWithComponentType");
gameObjectWithComponentType.transformAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("transform");
gameObjectWithComponentType.translateAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("translate");
gameObjectWithComponentType.rotateAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("rotate");
gameObjectWithComponentType.scaleAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("scale");
gameObjectWithComponentType.pivotAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("pivot");
gameObjectWithComponentType.transformationTypeAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("transformationType");
gameObjectWithComponentType.nameAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("name");
gameObjectWithComponentType.visibleAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("visible");
gameObjectWithComponentType.lockedAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("locked");
gameObjectWithComponentType.componentChild = gameObjectWithComponentType.Type.GetChildInfo("component");
objectOverrideType.Type = getNodeType("gap", "objectOverrideType");
objectOverrideType.objectNameAttribute = objectOverrideType.Type.GetAttributeInfo("objectName");
objectOverrideType.attributeOverrideChild = objectOverrideType.Type.GetChildInfo("attributeOverride");
attributeOverrideType.Type = getNodeType("gap", "attributeOverrideType");
attributeOverrideType.nameAttribute = attributeOverrideType.Type.GetAttributeInfo("name");
attributeOverrideType.valueAttribute = attributeOverrideType.Type.GetAttributeInfo("value");
prefabInstanceType.Type = getNodeType("gap", "prefabInstanceType");
prefabInstanceType.transformAttribute = prefabInstanceType.Type.GetAttributeInfo("transform");
prefabInstanceType.translateAttribute = prefabInstanceType.Type.GetAttributeInfo("translate");
prefabInstanceType.rotateAttribute = prefabInstanceType.Type.GetAttributeInfo("rotate");
prefabInstanceType.scaleAttribute = prefabInstanceType.Type.GetAttributeInfo("scale");
prefabInstanceType.pivotAttribute = prefabInstanceType.Type.GetAttributeInfo("pivot");
prefabInstanceType.transformationTypeAttribute = prefabInstanceType.Type.GetAttributeInfo("transformationType");
prefabInstanceType.visibleAttribute = prefabInstanceType.Type.GetAttributeInfo("visible");
prefabInstanceType.lockedAttribute = prefabInstanceType.Type.GetAttributeInfo("locked");
prefabInstanceType.prefabRefAttribute = prefabInstanceType.Type.GetAttributeInfo("prefabRef");
prefabInstanceType.objectChild = prefabInstanceType.Type.GetChildInfo("object");
prefabInstanceType.objectOverrideChild = prefabInstanceType.Type.GetChildInfo("objectOverride");
renderComponentType.Type = getNodeType("gap", "renderComponentType");
renderComponentType.nameAttribute = renderComponentType.Type.GetAttributeInfo("name");
renderComponentType.activeAttribute = renderComponentType.Type.GetAttributeInfo("active");
renderComponentType.translationAttribute = renderComponentType.Type.GetAttributeInfo("translation");
renderComponentType.rotationAttribute = renderComponentType.Type.GetAttributeInfo("rotation");
renderComponentType.scaleAttribute = renderComponentType.Type.GetAttributeInfo("scale");
renderComponentType.visibleAttribute = renderComponentType.Type.GetAttributeInfo("visible");
renderComponentType.castShadowAttribute = renderComponentType.Type.GetAttributeInfo("castShadow");
renderComponentType.receiveShadowAttribute = renderComponentType.Type.GetAttributeInfo("receiveShadow");
renderComponentType.drawDistanceAttribute = renderComponentType.Type.GetAttributeInfo("drawDistance");
meshComponentType.Type = getNodeType("gap", "meshComponentType");
meshComponentType.nameAttribute = meshComponentType.Type.GetAttributeInfo("name");
meshComponentType.activeAttribute = meshComponentType.Type.GetAttributeInfo("active");
meshComponentType.translationAttribute = meshComponentType.Type.GetAttributeInfo("translation");
meshComponentType.rotationAttribute = meshComponentType.Type.GetAttributeInfo("rotation");
meshComponentType.scaleAttribute = meshComponentType.Type.GetAttributeInfo("scale");
meshComponentType.visibleAttribute = meshComponentType.Type.GetAttributeInfo("visible");
meshComponentType.castShadowAttribute = meshComponentType.Type.GetAttributeInfo("castShadow");
meshComponentType.receiveShadowAttribute = meshComponentType.Type.GetAttributeInfo("receiveShadow");
meshComponentType.drawDistanceAttribute = meshComponentType.Type.GetAttributeInfo("drawDistance");
meshComponentType.refAttribute = meshComponentType.Type.GetAttributeInfo("ref");
spinnerComponentType.Type = getNodeType("gap", "spinnerComponentType");
spinnerComponentType.nameAttribute = spinnerComponentType.Type.GetAttributeInfo("name");
spinnerComponentType.activeAttribute = spinnerComponentType.Type.GetAttributeInfo("active");
spinnerComponentType.rpsAttribute = spinnerComponentType.Type.GetAttributeInfo("rps");
modelReferenceType.Type = getNodeType("gap", "modelReferenceType");
modelReferenceType.uriAttribute = modelReferenceType.Type.GetAttributeInfo("uri");
modelReferenceType.tagAttribute = modelReferenceType.Type.GetAttributeInfo("tag");
locatorType.Type = getNodeType("gap", "locatorType");
locatorType.transformAttribute = locatorType.Type.GetAttributeInfo("transform");
locatorType.translateAttribute = locatorType.Type.GetAttributeInfo("translate");
locatorType.rotateAttribute = locatorType.Type.GetAttributeInfo("rotate");
locatorType.scaleAttribute = locatorType.Type.GetAttributeInfo("scale");
locatorType.pivotAttribute = locatorType.Type.GetAttributeInfo("pivot");
locatorType.transformationTypeAttribute = locatorType.Type.GetAttributeInfo("transformationType");
locatorType.nameAttribute = locatorType.Type.GetAttributeInfo("name");
locatorType.visibleAttribute = locatorType.Type.GetAttributeInfo("visible");
locatorType.lockedAttribute = locatorType.Type.GetAttributeInfo("locked");
locatorType.resourceChild = locatorType.Type.GetChildInfo("resource");
locatorType.stmRefChild = locatorType.Type.GetChildInfo("stmRef");
stateMachineRefType.Type = getNodeType("gap", "stateMachineRefType");
stateMachineRefType.uriAttribute = stateMachineRefType.Type.GetAttributeInfo("uri");
stateMachineRefType.flatPropertyTableChild = stateMachineRefType.Type.GetChildInfo("flatPropertyTable");
flatPropertyTableType.Type = getNodeType("gap", "flatPropertyTableType");
flatPropertyTableType.propertyChild = flatPropertyTableType.Type.GetChildInfo("property");
propertyType.Type = getNodeType("gap", "propertyType");
propertyType.scopeAttribute = propertyType.Type.GetAttributeInfo("scope");
propertyType.typeAttribute = propertyType.Type.GetAttributeInfo("type");
propertyType.absolutePathAttribute = propertyType.Type.GetAttributeInfo("absolutePath");
propertyType.propertyNameAttribute = propertyType.Type.GetAttributeInfo("propertyName");
propertyType.defaultValueAttribute = propertyType.Type.GetAttributeInfo("defaultValue");
propertyType.valueAttribute = propertyType.Type.GetAttributeInfo("value");
propertyType.minValueAttribute = propertyType.Type.GetAttributeInfo("minValue");
propertyType.maxValueAttribute = propertyType.Type.GetAttributeInfo("maxValue");
propertyType.descriptionAttribute = propertyType.Type.GetAttributeInfo("description");
propertyType.categoryAttribute = propertyType.Type.GetAttributeInfo("category");
propertyType.warningAttribute = propertyType.Type.GetAttributeInfo("warning");
controlPointType.Type = getNodeType("gap", "controlPointType");
controlPointType.transformAttribute = controlPointType.Type.GetAttributeInfo("transform");
controlPointType.translateAttribute = controlPointType.Type.GetAttributeInfo("translate");
controlPointType.rotateAttribute = controlPointType.Type.GetAttributeInfo("rotate");
controlPointType.scaleAttribute = controlPointType.Type.GetAttributeInfo("scale");
controlPointType.pivotAttribute = controlPointType.Type.GetAttributeInfo("pivot");
controlPointType.transformationTypeAttribute = controlPointType.Type.GetAttributeInfo("transformationType");
controlPointType.nameAttribute = controlPointType.Type.GetAttributeInfo("name");
controlPointType.visibleAttribute = controlPointType.Type.GetAttributeInfo("visible");
controlPointType.lockedAttribute = controlPointType.Type.GetAttributeInfo("locked");
curveType.Type = getNodeType("gap", "curveType");
curveType.transformAttribute = curveType.Type.GetAttributeInfo("transform");
curveType.translateAttribute = curveType.Type.GetAttributeInfo("translate");
curveType.rotateAttribute = curveType.Type.GetAttributeInfo("rotate");
curveType.scaleAttribute = curveType.Type.GetAttributeInfo("scale");
curveType.pivotAttribute = curveType.Type.GetAttributeInfo("pivot");
curveType.transformationTypeAttribute = curveType.Type.GetAttributeInfo("transformationType");
curveType.nameAttribute = curveType.Type.GetAttributeInfo("name");
curveType.visibleAttribute = curveType.Type.GetAttributeInfo("visible");
curveType.lockedAttribute = curveType.Type.GetAttributeInfo("locked");
curveType.colorAttribute = curveType.Type.GetAttributeInfo("color");
curveType.isClosedAttribute = curveType.Type.GetAttributeInfo("isClosed");
curveType.stepsAttribute = curveType.Type.GetAttributeInfo("steps");
curveType.interpolationTypeAttribute = curveType.Type.GetAttributeInfo("interpolationType");
curveType.pointChild = curveType.Type.GetChildInfo("point");
catmullRomType.Type = getNodeType("gap", "catmullRomType");
catmullRomType.transformAttribute = catmullRomType.Type.GetAttributeInfo("transform");
catmullRomType.translateAttribute = catmullRomType.Type.GetAttributeInfo("translate");
catmullRomType.rotateAttribute = catmullRomType.Type.GetAttributeInfo("rotate");
catmullRomType.scaleAttribute = catmullRomType.Type.GetAttributeInfo("scale");
catmullRomType.pivotAttribute = catmullRomType.Type.GetAttributeInfo("pivot");
catmullRomType.transformationTypeAttribute = catmullRomType.Type.GetAttributeInfo("transformationType");
catmullRomType.nameAttribute = catmullRomType.Type.GetAttributeInfo("name");
catmullRomType.visibleAttribute = catmullRomType.Type.GetAttributeInfo("visible");
catmullRomType.lockedAttribute = catmullRomType.Type.GetAttributeInfo("locked");
catmullRomType.colorAttribute = catmullRomType.Type.GetAttributeInfo("color");
catmullRomType.isClosedAttribute = catmullRomType.Type.GetAttributeInfo("isClosed");
catmullRomType.stepsAttribute = catmullRomType.Type.GetAttributeInfo("steps");
catmullRomType.interpolationTypeAttribute = catmullRomType.Type.GetAttributeInfo("interpolationType");
catmullRomType.pointChild = catmullRomType.Type.GetChildInfo("point");
bezierType.Type = getNodeType("gap", "bezierType");
bezierType.transformAttribute = bezierType.Type.GetAttributeInfo("transform");
bezierType.translateAttribute = bezierType.Type.GetAttributeInfo("translate");
bezierType.rotateAttribute = bezierType.Type.GetAttributeInfo("rotate");
bezierType.scaleAttribute = bezierType.Type.GetAttributeInfo("scale");
bezierType.pivotAttribute = bezierType.Type.GetAttributeInfo("pivot");
bezierType.transformationTypeAttribute = bezierType.Type.GetAttributeInfo("transformationType");
bezierType.nameAttribute = bezierType.Type.GetAttributeInfo("name");
bezierType.visibleAttribute = bezierType.Type.GetAttributeInfo("visible");
bezierType.lockedAttribute = bezierType.Type.GetAttributeInfo("locked");
bezierType.colorAttribute = bezierType.Type.GetAttributeInfo("color");
bezierType.isClosedAttribute = bezierType.Type.GetAttributeInfo("isClosed");
bezierType.stepsAttribute = bezierType.Type.GetAttributeInfo("steps");
bezierType.interpolationTypeAttribute = bezierType.Type.GetAttributeInfo("interpolationType");
bezierType.pointChild = bezierType.Type.GetChildInfo("point");
gameRootElement = getRootElement(NS, "game");
prototypeRootElement = getRootElement(NS, "prototype");
prefabRootElement = getRootElement(NS, "prefab");
textureMetadataRootElement = getRootElement(NS, "textureMetadata");
resourceMetadataRootElement = getRootElement(NS, "resourceMetadata");
}
public static class gameType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static ChildInfo gameObjectFolderChild;
public static ChildInfo layersChild;
public static ChildInfo bookmarksChild;
public static ChildInfo gameReferenceChild;
public static ChildInfo gridChild;
}
public static class gameObjectFolderType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
public static ChildInfo gameObjectChild;
public static ChildInfo folderChild;
}
public static class gameObjectType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
}
public static class transformObjectType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
}
public static class layersType
{
public static DomNodeType Type;
public static ChildInfo layerChild;
}
public static class layerType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static ChildInfo gameObjectReferenceChild;
public static ChildInfo layerChild;
}
public static class gameObjectReferenceType
{
public static DomNodeType Type;
public static AttributeInfo refAttribute;
}
public static class bookmarksType
{
public static DomNodeType Type;
public static ChildInfo bookmarkChild;
}
public static class bookmarkType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static ChildInfo cameraChild;
public static ChildInfo bookmarkChild;
}
public static class cameraType
{
public static DomNodeType Type;
public static AttributeInfo eyeAttribute;
public static AttributeInfo lookAtPointAttribute;
public static AttributeInfo upVectorAttribute;
public static AttributeInfo viewTypeAttribute;
public static AttributeInfo yFovAttribute;
public static AttributeInfo nearZAttribute;
public static AttributeInfo farZAttribute;
public static AttributeInfo focusRadiusAttribute;
}
public static class gameReferenceType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo refAttribute;
public static AttributeInfo tagsAttribute;
}
public static class gridType
{
public static DomNodeType Type;
public static AttributeInfo sizeAttribute;
public static AttributeInfo subdivisionsAttribute;
public static AttributeInfo heightAttribute;
public static AttributeInfo snapAttribute;
public static AttributeInfo visibleAttribute;
}
public static class prototypeType
{
public static DomNodeType Type;
public static ChildInfo gameObjectChild;
}
public static class prefabType
{
public static DomNodeType Type;
public static ChildInfo gameObjectChild;
}
public static class textureMetadataType
{
public static DomNodeType Type;
public static AttributeInfo uriAttribute;
public static AttributeInfo keywordsAttribute;
public static AttributeInfo compressionSettingAttribute;
public static AttributeInfo memoryLayoutAttribute;
public static AttributeInfo mipMapAttribute;
public static AttributeInfo colorSpaceAttribute;
}
public static class resourceMetadataType
{
public static DomNodeType Type;
public static AttributeInfo uriAttribute;
public static AttributeInfo keywordsAttribute;
}
public static class resourceReferenceType
{
public static DomNodeType Type;
public static AttributeInfo uriAttribute;
}
public static class visibleTransformObjectType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
}
public static class transformObjectGroupType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
public static ChildInfo objectChild;
}
public static class gameObjectComponentType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo activeAttribute;
}
public static class transformComponentType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo activeAttribute;
public static AttributeInfo translationAttribute;
public static AttributeInfo rotationAttribute;
public static AttributeInfo scaleAttribute;
}
public static class gameObjectWithComponentType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
public static ChildInfo componentChild;
}
public static class objectOverrideType
{
public static DomNodeType Type;
public static AttributeInfo objectNameAttribute;
public static ChildInfo attributeOverrideChild;
}
public static class attributeOverrideType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo valueAttribute;
}
public static class prefabInstanceType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
public static AttributeInfo prefabRefAttribute;
public static ChildInfo objectChild;
public static ChildInfo objectOverrideChild;
}
public static class renderComponentType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo activeAttribute;
public static AttributeInfo translationAttribute;
public static AttributeInfo rotationAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo castShadowAttribute;
public static AttributeInfo receiveShadowAttribute;
public static AttributeInfo drawDistanceAttribute;
}
public static class meshComponentType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo activeAttribute;
public static AttributeInfo translationAttribute;
public static AttributeInfo rotationAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo castShadowAttribute;
public static AttributeInfo receiveShadowAttribute;
public static AttributeInfo drawDistanceAttribute;
public static AttributeInfo refAttribute;
}
public static class spinnerComponentType
{
public static DomNodeType Type;
public static AttributeInfo nameAttribute;
public static AttributeInfo activeAttribute;
public static AttributeInfo rpsAttribute;
}
public static class modelReferenceType
{
public static DomNodeType Type;
public static AttributeInfo uriAttribute;
public static AttributeInfo tagAttribute;
}
public static class locatorType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
public static ChildInfo resourceChild;
public static ChildInfo stmRefChild;
}
public static class stateMachineRefType
{
public static DomNodeType Type;
public static AttributeInfo uriAttribute;
public static ChildInfo flatPropertyTableChild;
}
public static class flatPropertyTableType
{
public static DomNodeType Type;
public static ChildInfo propertyChild;
}
public static class propertyType
{
public static DomNodeType Type;
public static AttributeInfo scopeAttribute;
public static AttributeInfo typeAttribute;
public static AttributeInfo absolutePathAttribute;
public static AttributeInfo propertyNameAttribute;
public static AttributeInfo defaultValueAttribute;
public static AttributeInfo valueAttribute;
public static AttributeInfo minValueAttribute;
public static AttributeInfo maxValueAttribute;
public static AttributeInfo descriptionAttribute;
public static AttributeInfo categoryAttribute;
public static AttributeInfo warningAttribute;
}
public static class controlPointType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
}
public static class curveType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo isClosedAttribute;
public static AttributeInfo stepsAttribute;
public static AttributeInfo interpolationTypeAttribute;
public static ChildInfo pointChild;
}
public static class catmullRomType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo isClosedAttribute;
public static AttributeInfo stepsAttribute;
public static AttributeInfo interpolationTypeAttribute;
public static ChildInfo pointChild;
}
public static class bezierType
{
public static DomNodeType Type;
public static AttributeInfo transformAttribute;
public static AttributeInfo translateAttribute;
public static AttributeInfo rotateAttribute;
public static AttributeInfo scaleAttribute;
public static AttributeInfo pivotAttribute;
public static AttributeInfo transformationTypeAttribute;
public static AttributeInfo nameAttribute;
public static AttributeInfo visibleAttribute;
public static AttributeInfo lockedAttribute;
public static AttributeInfo colorAttribute;
public static AttributeInfo isClosedAttribute;
public static AttributeInfo stepsAttribute;
public static AttributeInfo interpolationTypeAttribute;
public static ChildInfo pointChild;
}
public static ChildInfo gameRootElement;
public static ChildInfo prototypeRootElement;
public static ChildInfo prefabRootElement;
public static ChildInfo textureMetadataRootElement;
public static ChildInfo resourceMetadataRootElement;
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Tests
{
/// <summary>
/// Allows setting up a mock service in the client-server tests easily.
/// </summary>
public class MockServiceHelper
{
public const string ServiceName = "tests.Test";
readonly string host;
readonly ServerServiceDefinition serviceDefinition;
readonly Method<string, string> unaryMethod;
readonly Method<string, string> clientStreamingMethod;
readonly Method<string, string> serverStreamingMethod;
readonly Method<string, string> duplexStreamingMethod;
UnaryServerMethod<string, string> unaryHandler;
ClientStreamingServerMethod<string, string> clientStreamingHandler;
ServerStreamingServerMethod<string, string> serverStreamingHandler;
DuplexStreamingServerMethod<string, string> duplexStreamingHandler;
Server server;
Channel channel;
public MockServiceHelper(string host = null, Marshaller<string> marshaller = null)
{
this.host = host ?? "localhost";
marshaller = marshaller ?? Marshallers.StringMarshaller;
unaryMethod = new Method<string, string>(
MethodType.Unary,
ServiceName,
"Unary",
marshaller,
marshaller);
clientStreamingMethod = new Method<string, string>(
MethodType.ClientStreaming,
ServiceName,
"ClientStreaming",
marshaller,
marshaller);
serverStreamingMethod = new Method<string, string>(
MethodType.ServerStreaming,
ServiceName,
"ServerStreaming",
marshaller,
marshaller);
duplexStreamingMethod = new Method<string, string>(
MethodType.DuplexStreaming,
ServiceName,
"DuplexStreaming",
marshaller,
marshaller);
serviceDefinition = ServerServiceDefinition.CreateBuilder(ServiceName)
.AddMethod(unaryMethod, (request, context) => unaryHandler(request, context))
.AddMethod(clientStreamingMethod, (requestStream, context) => clientStreamingHandler(requestStream, context))
.AddMethod(serverStreamingMethod, (request, responseStream, context) => serverStreamingHandler(request, responseStream, context))
.AddMethod(duplexStreamingMethod, (requestStream, responseStream, context) => duplexStreamingHandler(requestStream, responseStream, context))
.Build();
var defaultStatus = new Status(StatusCode.Unknown, "Default mock implementation. Please provide your own.");
unaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
{
context.Status = defaultStatus;
return "";
});
clientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
{
context.Status = defaultStatus;
return "";
});
serverStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) =>
{
context.Status = defaultStatus;
});
duplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) =>
{
context.Status = defaultStatus;
});
}
/// <summary>
/// Returns the default server for this service and creates one if not yet created.
/// </summary>
public Server GetServer()
{
if (server == null)
{
server = new Server
{
Services = { serviceDefinition },
Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
};
}
return server;
}
/// <summary>
/// Returns the default channel for this service and creates one if not yet created.
/// </summary>
public Channel GetChannel()
{
if (channel == null)
{
channel = new Channel(Host, GetServer().Ports.Single().BoundPort, ChannelCredentials.Insecure);
}
return channel;
}
public CallInvocationDetails<string, string> CreateUnaryCall(CallOptions options = default(CallOptions))
{
return new CallInvocationDetails<string, string>(channel, unaryMethod, options);
}
public CallInvocationDetails<string, string> CreateClientStreamingCall(CallOptions options = default(CallOptions))
{
return new CallInvocationDetails<string, string>(channel, clientStreamingMethod, options);
}
public CallInvocationDetails<string, string> CreateServerStreamingCall(CallOptions options = default(CallOptions))
{
return new CallInvocationDetails<string, string>(channel, serverStreamingMethod, options);
}
public CallInvocationDetails<string, string> CreateDuplexStreamingCall(CallOptions options = default(CallOptions))
{
return new CallInvocationDetails<string, string>(channel, duplexStreamingMethod, options);
}
public string Host
{
get
{
return this.host;
}
}
public ServerServiceDefinition ServiceDefinition
{
get
{
return this.serviceDefinition;
}
}
public UnaryServerMethod<string, string> UnaryHandler
{
get
{
return this.unaryHandler;
}
set
{
unaryHandler = value;
}
}
public ClientStreamingServerMethod<string, string> ClientStreamingHandler
{
get
{
return this.clientStreamingHandler;
}
set
{
clientStreamingHandler = value;
}
}
public ServerStreamingServerMethod<string, string> ServerStreamingHandler
{
get
{
return this.serverStreamingHandler;
}
set
{
serverStreamingHandler = value;
}
}
public DuplexStreamingServerMethod<string, string> DuplexStreamingHandler
{
get
{
return this.duplexStreamingHandler;
}
set
{
duplexStreamingHandler = value;
}
}
}
}
| |
using System;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Reflection;
using System.ServiceProcess;
using CommandLine;
using DCS.Core.WebConfig;
using log4net;
using DCS.Core;
using DCS.Core.Configuration;
using DCS.Core.DataCollectors;
using DCS.Core.DataReaders;
using DCS.Core.Helpers;
using OSIsoft.AF;
using OSIsoft.AF.Asset;
using OSIsoft.AF.Data;
using OSIsoft.AF.Time;
namespace DCS.Service
{
internal static class Program
{
private static readonly ILog _logger = LogManager.GetLogger(typeof(Program));
/// <summary>
/// Service Main Entry Point
/// </summary>
private static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
if (Environment.UserInteractive)
{
_logger.Info("Starting service interractively");
var options = new CommandLineOptions();
if (Parser.Default.ParseArguments(args, options))
{
if (options.Run)
{
if (!Config.IsLoaded())
Environment.Exit(-1);
WebHost.Instance.Start();
Core.Program.RunScheduler();
Console.WriteLine("press a key to stop the data collection");
Console.ReadKey();
Core.Program.StopScheduler();
WebHost.Instance.Dispose();
Console.WriteLine("Stopped");
}
if (options.Test)
{
var dataWriter = new DataWriter();
// Here are added the configured data collectors
foreach (DataCollectorSettings collectorSettings in Config.Settings.DataCollectorsSettings.Where(c => c.LoadPlugin == 1))
{
try
{
if (!string.IsNullOrEmpty(collectorSettings.PluginFileName))
{
var applicationDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) ?? "";
Assembly pluginAssembly = Assembly.LoadFrom(Path.Combine(applicationDirectory, "plugins", collectorSettings.PluginFileName));
foreach (var type in pluginAssembly.GetTypes())
{
if (type.GetInterface(typeof(IDataCollector).Name) != null)
{
var newCollector = Activator.CreateInstance(type) as IDataCollector;
var isValidDataCollector = true;
// performs an additional test, when a plugin class name is provided
if (collectorSettings.PluginClassName != null && newCollector != null)
{
isValidDataCollector = collectorSettings.PluginClassName == newCollector.GetType().Name;
}
if (newCollector != null && isValidDataCollector)
{
_logger.InfoFormat("Loading task of type: {0}. Task description: {1}", type.Name, collectorSettings.ReaderTaskDescription);
newCollector.SetSettings(collectorSettings);
newCollector.Inititialize();
newCollector.CollectData();
}
}
}
}
}
catch (Exception ex)
{
_logger.Error(ex);
}
dataWriter.FlushData();
}
Console.WriteLine("Test completed, press a key to exit");
Console.ReadKey();
}
if (options.Install)
{
ManagedInstallerClass.InstallHelper(new[] { Assembly.GetExecutingAssembly().Location });
}
if (options.Uninstall)
{
ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location });
}
// this code should be taken elsewhere... leaving it here for now. unrelevant to this app
if(options.Stats)
{
AFDatabase afdb = null;
var conn=AFConnectionHelper.ConnectAndGetDatabase("Optimus", "GitHub", out afdb);
Console.WriteLine("repoName,views avg, views min, views max, views std dev, clones avg, clones min, clones max, clones std dev");
foreach (var element in afdb.Elements["OSIsoft"].Elements)
{
var viewsCount = element.Elements["Traffic"].Attributes["views-count"];
var clonesCount = element.Elements["Traffic"].Attributes["clones-count"];
var timeRange=new AFTimeRange(AFTime.Parse("T-8d"), AFTime.Parse("T"));
var views = viewsCount.Data.Summary(timeRange, AFSummaryTypes.All,
AFCalculationBasis.EventWeighted, AFTimestampCalculation.Auto);
var clones = clonesCount.Data.Summary(timeRange, AFSummaryTypes.All,
AFCalculationBasis.EventWeighted, AFTimestampCalculation.Auto);
Console.Write(element.Name + ",");
Console.Write(val(views[AFSummaryTypes.Average]) + ",");
Console.Write(val(views[AFSummaryTypes.Minimum]) + ",");
Console.Write(val(views[AFSummaryTypes.Maximum]) + ",");
Console.Write(val(views[AFSummaryTypes.StdDev]) + ",");
Console.Write(val(clones[AFSummaryTypes.Average]) + ",");
Console.Write(val(clones[AFSummaryTypes.Minimum]) + ",");
Console.Write(val(clones[AFSummaryTypes.Maximum]) + ",");
Console.Write(val(clones[AFSummaryTypes.StdDev]) );
Console.Write(Environment.NewLine);
}
Console.ReadKey();
}
// exit ok
Environment.Exit(0);
}
}
else
{
ServiceBase[] ServicesToRun =
{
new Service()
};
ServiceBase.Run(ServicesToRun);
}
}
private static string val(AFValue value)
{
string res="";
Type t = value.Value.GetType();
if (t== typeof(int) || t==typeof(double))
{
res = string.Format("{0:0}", value.Value);
}
return res;
}
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
_logger.Error(e.ExceptionObject);
}
}
}
| |
//
// MenuItemBackend.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 Xwt.Drawing;
using System.Collections.Generic;
namespace Xwt.GtkBackend
{
public class MenuItemBackend: IMenuItemBackend
{
IMenuItemEventSink eventSink;
Gtk.MenuItem item;
Gtk.Label label;
List<MenuItemEvent> enabledEvents;
bool changingCheck;
ApplicationContext context;
public MenuItemBackend ()
: this (new Gtk.ImageMenuItem (""))
{
}
public MenuItemBackend (Gtk.MenuItem item)
{
this.item = item;
label = (Gtk.Label) item.Child;
item.ShowAll ();
}
public Gtk.MenuItem MenuItem {
get { return item; }
}
public void Initialize (IMenuItemEventSink eventSink)
{
this.eventSink = eventSink;
}
public void SetSubmenu (IMenuBackend menu)
{
if (menu == null)
item.Submenu = null;
else {
Gtk.Menu m = ((MenuBackend)menu).Menu;
item.Submenu = m;
}
}
ImageDescription? defImage, selImage;
public void SetImage (ImageDescription image)
{
Gtk.ImageMenuItem it = item as Gtk.ImageMenuItem;
if (it == null)
return;
if (!image.IsNull) {
if (defImage == null)
item.StateChanged += ImageMenuItemStateChanged;
defImage = image;
selImage = new ImageDescription {
Backend = image.Backend,
Size = image.Size,
Alpha = image.Alpha,
Styles = image.Styles.Add ("sel")
};
var img = new ImageBox (context, image);
img.ShowAll ();
it.Image = img;
GtkWorkarounds.ForceImageOnMenuItem (it);
} else {
if (defImage.HasValue) {
item.StateChanged -= ImageMenuItemStateChanged;
defImage = selImage = null;
}
it.Image = null;
}
}
void ImageMenuItemStateChanged (object o, Gtk.StateChangedArgs args)
{
var it = item as Gtk.ImageMenuItem;
var image = it?.Image as ImageBox;
if (image == null || selImage == null || defImage == null)
return;
if (it.State == Gtk.StateType.Prelight)
image.Image = selImage.Value;
else if (args.PreviousState == Gtk.StateType.Prelight)
image.Image = defImage.Value;
}
public string Label {
get {
return label != null ? (label.UseUnderline ? label.LabelProp : label.Text) : "";
}
set {
if (formattedText != null) {
formattedText = null;
label.ApplyFormattedText (null);
}
if (label.UseUnderline)
label.TextWithMnemonic = value;
else
label.Text = value;
}
}
public string TooltipText {
get {
return item.TooltipText;
}
set {
item.TooltipText = value;
}
}
public bool UseMnemonic {
get { return label.UseUnderline; }
set { label.UseUnderline = value; }
}
public bool Sensitive {
get {
return item.Sensitive;
}
set {
item.Sensitive = value;
}
}
public bool Visible {
get {
return item.Visible;
}
set {
item.Visible = value;
}
}
public bool Checked {
get { return (item is Gtk.CheckMenuItem) && ((Gtk.CheckMenuItem)item).Active; }
set {
if (item is Gtk.CheckMenuItem) {
changingCheck = true;
((Gtk.CheckMenuItem)item).Active = value;
changingCheck = false;
}
}
}
FormattedText formattedText;
public void SetFormattedText (FormattedText text)
{
label.Text = text?.Text;
formattedText = text;
label.Realized -= HandleStyleUpdate;
label.StyleSet -= HandleStyleUpdate;
label.ApplyFormattedText(text);
label.Realized += HandleStyleUpdate;
label.StyleSet += HandleStyleUpdate;
}
void HandleStyleUpdate (object sender, EventArgs e)
{
// force text update with updated link color
if (label.IsRealized && formattedText != null) {
label.ApplyFormattedText (formattedText);
}
}
/* public void SetType (MenuItemType type)
{
string text = label.Text;
Gtk.MenuItem newItem = null;
switch (type) {
case MenuItemType.Normal:
if (!(item is Gtk.ImageMenuItem))
newItem = new Gtk.ImageMenuItem (text);
break;
case MenuItemType.CheckBox:
if (item.GetType () != typeof(Gtk.CheckMenuItem))
newItem = new Gtk.CheckMenuItem (text);
break;
case MenuItemType.RadioButton:
if (!(item is Gtk.RadioMenuItem))
newItem = new Gtk.RadioMenuItem (text);
break;
}
if (newItem != null) {
if ((newItem is Gtk.CheckMenuItem) && (item is Gtk.CheckMenuItem))
((Gtk.CheckMenuItem)item).Active = ((Gtk.CheckMenuItem)newItem).Active;
newItem.Sensitive = item.Sensitive;
if (item.Parent != null) {
Gtk.Menu m = (Gtk.Menu)item.Parent;
int pos = Array.IndexOf (m.Children, item);
m.Insert (newItem, pos);
m.Remove (item);
}
newItem.ShowAll ();
if (!item.Visible)
newItem.Hide ();
if (enabledEvents != null) {
foreach (var ob in enabledEvents)
DisableEvent (ob);
}
item = newItem;
label = (Gtk.Label) item.Child;
if (enabledEvents != null) {
foreach (var ob in enabledEvents)
EnableEvent (ob);
}
}
}*/
public void InitializeBackend (object frontend, ApplicationContext context)
{
this.context = context;
}
public void EnableEvent (object eventId)
{
if (eventId is MenuItemEvent) {
if (enabledEvents == null)
enabledEvents = new List<MenuItemEvent> ();
enabledEvents.Add ((MenuItemEvent)eventId);
if ((MenuItemEvent)eventId == MenuItemEvent.Clicked)
item.Activated += HandleItemActivated;
}
}
public void DisableEvent (object eventId)
{
if (eventId is MenuItemEvent) {
enabledEvents.Remove ((MenuItemEvent)eventId);
if ((MenuItemEvent)eventId == MenuItemEvent.Clicked)
item.Activated -= HandleItemActivated;
}
}
void HandleItemActivated (object sender, EventArgs e)
{
if (!changingCheck) {
context.InvokeUserCode (eventSink.OnClicked);
}
}
public void Dispose ()
{
if (label != null) {
label.Realized -= HandleStyleUpdate;
label.StyleSet -= HandleStyleUpdate;
label = null;
}
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
using VSLangProj;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
namespace Microsoft.VisualStudio.Project.Automation
{
/// <summary>
/// Represents the automation object for the equivalent ReferenceContainerNode object
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[ComVisible(true)]
public class OAReferences : ConnectionPointContainer,
IEventSource<_dispReferencesEvents>,
References,
ReferencesEvents
{
private ReferenceContainerNode container;
public OAReferences(ReferenceContainerNode containerNode)
{
container = containerNode;
AddEventSource<_dispReferencesEvents>(this as IEventSource<_dispReferencesEvents>);
container.OnChildAdded += new EventHandler<HierarchyNodeEventArgs>(OnReferenceAdded);
container.OnChildRemoved += new EventHandler<HierarchyNodeEventArgs>(OnReferenceRemoved);
}
#region Private Members
private Reference AddFromSelectorData(VSCOMPONENTSELECTORDATA selector)
{
ReferenceNode refNode = container.AddReferenceFromSelectorData(selector);
if(null == refNode)
{
return null;
}
return refNode.Object as Reference;
}
private Reference FindByName(string stringIndex)
{
foreach(Reference refNode in this)
{
if(0 == string.Compare(refNode.Name, stringIndex, StringComparison.Ordinal))
{
return refNode;
}
}
return null;
}
#endregion
#region References Members
public Reference Add(string bstrPath)
{
if(string.IsNullOrEmpty(bstrPath))
{
return null;
}
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_File;
selector.bstrFile = bstrPath;
return AddFromSelectorData(selector);
}
public Reference AddActiveX(string bstrTypeLibGuid, int lMajorVer, int lMinorVer, int lLocaleId, string bstrWrapperTool)
{
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Com2;
selector.guidTypeLibrary = new Guid(bstrTypeLibGuid);
selector.lcidTypeLibrary = (uint)lLocaleId;
selector.wTypeLibraryMajorVersion = (ushort)lMajorVer;
selector.wTypeLibraryMinorVersion = (ushort)lMinorVer;
return AddFromSelectorData(selector);
}
public Reference AddProject(EnvDTE.Project project)
{
if(null == project)
{
return null;
}
// Get the soulution.
IVsSolution solution = container.ProjectMgr.Site.GetService(typeof(SVsSolution)) as IVsSolution;
if(null == solution)
{
return null;
}
// Get the hierarchy for this project.
IVsHierarchy projectHierarchy;
ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(project.UniqueName, out projectHierarchy));
// Create the selector data.
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project;
// Get the project reference string.
ErrorHandler.ThrowOnFailure(solution.GetProjrefOfProject(projectHierarchy, out selector.bstrProjRef));
selector.bstrTitle = project.Name;
selector.bstrFile = System.IO.Path.GetDirectoryName(project.FullName);
return AddFromSelectorData(selector);
}
public EnvDTE.Project ContainingProject
{
get
{
return container.ProjectMgr.GetAutomationObject() as EnvDTE.Project;
}
}
public int Count
{
get
{
return container.EnumReferences().Count;
}
}
public EnvDTE.DTE DTE
{
get
{
return container.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
}
}
public Reference Find(string bstrIdentity)
{
if(string.IsNullOrEmpty(bstrIdentity))
{
return null;
}
foreach(Reference refNode in this)
{
if(null != refNode)
{
if(0 == string.Compare(bstrIdentity, refNode.Identity, StringComparison.Ordinal))
{
return refNode;
}
}
}
return null;
}
public IEnumerator GetEnumerator()
{
List<Reference> references = new List<Reference>();
IEnumerator baseEnum = container.EnumReferences().GetEnumerator();
if(null == baseEnum)
{
return references.GetEnumerator();
}
while(baseEnum.MoveNext())
{
ReferenceNode refNode = baseEnum.Current as ReferenceNode;
if(null == refNode)
{
continue;
}
Reference reference = refNode.Object as Reference;
if(null != reference)
{
references.Add(reference);
}
}
return references.GetEnumerator();
}
public Reference Item(object index)
{
string stringIndex = index as string;
if(null != stringIndex)
{
return FindByName(stringIndex);
}
// Note that this cast will throw if the index is not convertible to int.
int intIndex = (int)index;
IList<ReferenceNode> refs = container.EnumReferences();
if(null == refs)
{
throw new ArgumentOutOfRangeException("index");
}
if((intIndex <= 0) || (intIndex > refs.Count))
{
throw new ArgumentOutOfRangeException("index");
}
// Let the implementation of IList<> throw in case of index not correct.
return refs[intIndex - 1].Object as Reference;
}
public object Parent
{
get
{
return container.Parent.Object;
}
}
#endregion
#region _dispReferencesEvents_Event Members
public event _dispReferencesEvents_ReferenceAddedEventHandler ReferenceAdded;
public event _dispReferencesEvents_ReferenceChangedEventHandler ReferenceChanged;
public event _dispReferencesEvents_ReferenceRemovedEventHandler ReferenceRemoved;
#endregion
#region Callbacks for the HierarchyNode events
private void OnReferenceAdded(object sender, HierarchyNodeEventArgs args)
{
// Validate the parameters.
if((container != sender as ReferenceContainerNode) ||
(null == args) || (null == args.Child))
{
return;
}
// Check if there is any sink for this event.
if(null == ReferenceAdded)
{
return;
}
// Check that the removed item implements the Reference interface.
Reference reference = args.Child.Object as Reference;
if(null != reference)
{
ReferenceAdded(reference);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode",
Justification="Support for this has not yet been added")]
private void OnReferenceChanged(object sender, HierarchyNodeEventArgs args)
{
// Validate the parameters.
if ((container != sender as ReferenceContainerNode) ||
(null == args) || (null == args.Child))
{
return;
}
// Check if there is any sink for this event.
if (null == ReferenceChanged)
{
return;
}
// Check that the removed item implements the Reference interface.
Reference reference = args.Child.Object as Reference;
if (null != reference)
{
ReferenceChanged(reference);
}
}
private void OnReferenceRemoved(object sender, HierarchyNodeEventArgs args)
{
// Validate the parameters.
if((container != sender as ReferenceContainerNode) ||
(null == args) || (null == args.Child))
{
return;
}
// Check if there is any sink for this event.
if(null == ReferenceRemoved)
{
return;
}
// Check that the removed item implements the Reference interface.
Reference reference = args.Child.Object as Reference;
if(null != reference)
{
ReferenceRemoved(reference);
}
}
#endregion
#region IEventSource<_dispReferencesEvents> Members
void IEventSource<_dispReferencesEvents>.OnSinkAdded(_dispReferencesEvents sink)
{
ReferenceAdded += new _dispReferencesEvents_ReferenceAddedEventHandler(sink.ReferenceAdded);
ReferenceChanged += new _dispReferencesEvents_ReferenceChangedEventHandler(sink.ReferenceChanged);
ReferenceRemoved += new _dispReferencesEvents_ReferenceRemovedEventHandler(sink.ReferenceRemoved);
}
void IEventSource<_dispReferencesEvents>.OnSinkRemoved(_dispReferencesEvents sink)
{
ReferenceAdded -= new _dispReferencesEvents_ReferenceAddedEventHandler(sink.ReferenceAdded);
ReferenceChanged -= new _dispReferencesEvents_ReferenceChangedEventHandler(sink.ReferenceChanged);
ReferenceRemoved -= new _dispReferencesEvents_ReferenceRemovedEventHandler(sink.ReferenceRemoved);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using System.Xml;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Data;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Design;
using Rainbow.Framework.Helpers;
using Rainbow.Framework.Web.UI.WebControls;
using Label=Rainbow.Framework.Web.UI.WebControls.Label;
using Path=Rainbow.Framework.Settings.Path;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Rainbow Portal Pictures module
/// (c)2002 by Ender Malkoc
/// </summary>
[History("Mario Hartmann", "mario@hartmann.net", "2.3 beta", "2003/10/08", "moved to seperate folder")]
public class Pictures : PortalModuleControl
{
/// <summary>
/// Datalist for pictures
/// </summary>
protected DataList dlPictures;
/// <summary>
/// Error label
/// </summary>
protected Label lblError;
/// <summary>
/// Paging for the pictures
/// </summary>
protected Paging pgPictures;
/// <summary>
/// Resize Options
/// NoResize : Do not resize the picture
/// FixedWidthHeight : Use the width and height specified.
/// MaintainAspectWidth : Use the specified height and calculate height using the original aspect ratio
/// MaintainAspectHeight : Use the specified width and calculate width using the original aspect ration
/// </summary>
public enum ResizeOption
{
/// <summary>
/// No resizing
/// </summary>
NoResize,
/// <summary>
/// FixedWidthHeight : Use the width and height specified.
/// </summary>
FixedWidthHeight,
/// <summary>
/// MaintainAspectWidth : Use the specified height and calculate height using the original aspect ratio
/// </summary>
MaintainAspectWidth,
/// <summary>
/// MaintainAspectHeight : Use the specified width and calculate width using the original aspect ration
/// </summary>
MaintainAspectHeight
}
/// <summary>
/// The Page_Load event on this page calls the BindData() method
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Page_Load(object sender, EventArgs e)
{
dlPictures.RepeatDirection = (Settings["RepeatDirectionSetting"] == null
? RepeatDirection.Horizontal
:
(RepeatDirection)
Int32.Parse(((SettingItem) _baseSettings["RepeatDirectionSetting"])));
dlPictures.RepeatColumns = Int32.Parse(((SettingItem) Settings["RepeatColumns"]));
dlPictures.ItemDataBound += new DataListItemEventHandler(Pictures_ItemDataBound);
pgPictures.RecordsPerPage = Int32.Parse(Settings["PicturesPerPage"].ToString());
BindData(pgPictures.PageNumber);
}
private void Page_Changed(object sender, EventArgs e)
{
BindData(pgPictures.PageNumber);
}
private void Pictures_ItemDataBound(object sender, DataListItemEventArgs e)
{
PictureItem pictureItem;
try
{
pictureItem =
(PictureItem)
Page.LoadControl(Path.ApplicationRoot + "/Design/PictureLayouts/" + Settings["ThumbnailLayout"]);
}
catch
{
lblError.Visible = true;
dlPictures.Visible = false;
pgPictures.Visible = false;
return;
}
DataRowView di = (DataRowView) e.Item.DataItem;
XmlDocument metadata = new XmlDocument();
metadata.LoadXml((string) di["MetadataXml"]);
XmlAttribute albumPath = metadata.CreateAttribute("AlbumPath");
albumPath.Value = ((SettingItem) Settings["AlbumPath"]).FullPath;
XmlAttribute itemID = metadata.CreateAttribute("ItemID");
itemID.Value = ((int) di["ItemID"]).ToString();
XmlAttribute moduleID = metadata.CreateAttribute("ModuleID");
moduleID.Value = ModuleID.ToString();
XmlAttribute wVersion = metadata.CreateAttribute("WVersion");
wVersion.Value = Version.ToString();
XmlAttribute isEditable = metadata.CreateAttribute("IsEditable");
isEditable.Value = IsEditable.ToString();
metadata.DocumentElement.Attributes.Append(albumPath);
metadata.DocumentElement.Attributes.Append(itemID);
metadata.DocumentElement.Attributes.Append(moduleID);
metadata.DocumentElement.Attributes.Append(isEditable);
metadata.DocumentElement.Attributes.Append(wVersion);
if (Version == WorkFlowVersion.Production)
{
XmlNode modifiedFilenameNode = metadata.DocumentElement.SelectSingleNode("@ModifiedFilename");
XmlNode thumbnailFilenameNode = metadata.DocumentElement.SelectSingleNode("@ThumbnailFilename");
modifiedFilenameNode.Value = modifiedFilenameNode.Value.Replace(".jpg", ".Production.jpg");
thumbnailFilenameNode.Value = thumbnailFilenameNode.Value.Replace(".jpg", ".Production.jpg");
}
pictureItem.Metadata = metadata;
pictureItem.DataBind();
e.Item.Controls.Add(pictureItem);
}
/// <summary>
/// The Binddata method on this User Control is used to
/// obtain a DataReader of picture information from the Pictures
/// table, and then databind the results to a templated DataList
/// server control. It uses the Rainbow.PictureDB()
/// data component to encapsulate all data functionality.
/// </summary>
private void BindData(int page)
{
PicturesDB pictures = new PicturesDB();
DataSet dsPictures =
pictures.GetPicturesPaged(ModuleID, page, Int32.Parse(Settings["PicturesPerPage"].ToString()), Version);
if (dsPictures.Tables.Count > 0 && dsPictures.Tables[0].Rows.Count > 0)
{
pgPictures.RecordCount = (int) (dsPictures.Tables[0].Rows[0]["RecordCount"]);
}
dlPictures.DataSource = dsPictures;
dlPictures.DataBind();
}
/// <summary>
/// Overriden from PortalModuleControl, this override deletes unnecessary picture files from the system
/// </summary>
protected override void Publish()
{
string pathToDelete = Server.MapPath(((SettingItem) Settings["AlbumPath"]).FullPath) + "\\";
DirectoryInfo albumDirectory = new DirectoryInfo(pathToDelete);
foreach (FileInfo fi in albumDirectory.GetFiles(ModuleID.ToString() + "m*.Production.jpg"))
{
try
{
File.Delete(fi.FullName);
}
catch
{
}
}
foreach (FileInfo fi in albumDirectory.GetFiles(ModuleID.ToString() + "m*"))
{
try
{
File.Copy(fi.FullName, fi.FullName.Replace(".jpg", ".Production.jpg"), true);
}
catch
{
}
}
base.Publish();
}
/// <summary>
/// Given a key returns the value
/// </summary>
/// <param name="MetadataXml">XmlDocument containing key value pairs in attributes</param>
/// <param name="key">key of the pair</param>
/// <returns>value</returns>
protected string GetMetadata(object MetadataXml, string key)
{
XmlDocument Metadata = new XmlDocument();
Metadata.LoadXml((string) MetadataXml);
XmlNode targetNode = Metadata.SelectSingleNode("/Metadata/@" + key);
if (targetNode == null)
{
return null;
}
else
{
return targetNode.Value;
}
}
/// <summary>
/// Default constructor
/// </summary>
[
History("Tim Capps", "tim@cappsnet.com", "2.4 beta", "2004/02/18",
"fixed order on settings and added ShowBulkLoad")]
public Pictures()
{
// Add support for workflow
SupportsWorkflow = true;
// Album Path Setting
SettingItem AlbumPath = new SettingItem(new PortalUrlDataType());
AlbumPath.Required = true;
AlbumPath.Value = "Album";
AlbumPath.Order = 3;
_baseSettings.Add("AlbumPath", AlbumPath);
// Thumbnail Resize Options
ArrayList thumbnailResizeOptions = new ArrayList();
thumbnailResizeOptions.Add(
new Option((int) ResizeOption.FixedWidthHeight,
General.GetString("PICTURES_FIXED_WIDTH_AND_HEIGHT", "Fixed width and height", this)));
thumbnailResizeOptions.Add(
new Option((int) ResizeOption.MaintainAspectWidth,
General.GetString("PICTURES_MAINTAIN_ASPECT_FIXED_WIDTH", "Maintain aspect fixed width", this)));
thumbnailResizeOptions.Add(
new Option((int) ResizeOption.MaintainAspectHeight,
General.GetString("PICTURES_MAINTAIN_ASPECT_FIXED_HEIGHT", "Maintain aspect fixed height",
this)));
// Thumbnail Resize Settings
SettingItem ThumbnailResize = new SettingItem(new CustomListDataType(thumbnailResizeOptions, "Name", "Val"));
ThumbnailResize.Required = true;
ThumbnailResize.Value = ((int) ResizeOption.FixedWidthHeight).ToString();
ThumbnailResize.Order = 4;
_baseSettings.Add("ThumbnailResize", ThumbnailResize);
// Thumbnail Width Setting
SettingItem ThumbnailWidth = new SettingItem(new IntegerDataType());
ThumbnailWidth.Required = true;
ThumbnailWidth.Value = "100";
ThumbnailWidth.Order = 5;
ThumbnailWidth.MinValue = 2;
ThumbnailWidth.MaxValue = 9999;
_baseSettings.Add("ThumbnailWidth", ThumbnailWidth);
// Thumbnail Height Setting
SettingItem ThumbnailHeight = new SettingItem(new IntegerDataType());
ThumbnailHeight.Required = true;
ThumbnailHeight.Value = "75";
ThumbnailHeight.Order = 6;
ThumbnailHeight.MinValue = 2;
ThumbnailHeight.MaxValue = 9999;
_baseSettings.Add("ThumbnailHeight", ThumbnailHeight);
// Original Resize Options
ArrayList originalResizeOptions = new ArrayList();
originalResizeOptions.Add(
new Option((int) ResizeOption.NoResize, General.GetString("PICTURES_DONT_RESIZE", "Don't Resize", this)));
originalResizeOptions.Add(
new Option((int) ResizeOption.FixedWidthHeight,
General.GetString("PICTURES_FIXED_WIDTH_AND_HEIGHT", "Fixed width and height", this)));
originalResizeOptions.Add(
new Option((int) ResizeOption.MaintainAspectWidth,
General.GetString("PICTURES_MAINTAIN_ASPECT_FIXED_WIDTH", "Maintain aspect fixed width", this)));
originalResizeOptions.Add(
new Option((int) ResizeOption.MaintainAspectHeight,
General.GetString("PICTURES_MAINTAIN_ASPECT_FIXED_HEIGHT", "Maintain aspect fixed height",
this)));
// Original Resize Settings
SettingItem OriginalResize = new SettingItem(new CustomListDataType(originalResizeOptions, "Name", "Val"));
OriginalResize.Required = true;
OriginalResize.Value = ((int) ResizeOption.MaintainAspectWidth).ToString();
OriginalResize.Order = 7;
_baseSettings.Add("OriginalResize", OriginalResize);
// Original Width Settings
SettingItem OriginalWidth = new SettingItem(new IntegerDataType());
OriginalWidth.Required = true;
OriginalWidth.Value = "800";
OriginalWidth.Order = 8;
OriginalWidth.MinValue = 2;
OriginalWidth.MaxValue = 9999;
_baseSettings.Add("OriginalWidth", OriginalWidth);
// Original Width Settings
SettingItem OriginalHeight = new SettingItem(new IntegerDataType());
OriginalHeight.Required = true;
OriginalHeight.Value = "600";
OriginalHeight.Order = 9;
OriginalHeight.MinValue = 2;
OriginalHeight.MaxValue = 9999;
_baseSettings.Add("OriginalHeight", OriginalHeight);
// Repeat Direction Options
ArrayList repeatDirectionOptions = new ArrayList();
repeatDirectionOptions.Add(
new Option((int) RepeatDirection.Horizontal,
General.GetString("PICTURES_HORIZONTAL", "Horizontal", this)));
repeatDirectionOptions.Add(
new Option((int) RepeatDirection.Vertical, General.GetString("PICTURES_VERTICAL", "Vertical", this)));
// Repeat Direction Setting
SettingItem RepeatDirectionSetting =
new SettingItem(new CustomListDataType(repeatDirectionOptions, "Name", "Val"));
RepeatDirectionSetting.Required = true;
RepeatDirectionSetting.Value = ((int) RepeatDirection.Horizontal).ToString();
RepeatDirectionSetting.Order = 10;
_baseSettings.Add("RepeatDirection", RepeatDirectionSetting);
// Repeat Columns Setting
SettingItem RepeatColumns = new SettingItem(new IntegerDataType());
RepeatColumns.Required = true;
RepeatColumns.Value = "6";
RepeatColumns.Order = 11;
RepeatColumns.MinValue = 1;
RepeatColumns.MaxValue = 200;
_baseSettings.Add("RepeatColumns", RepeatColumns);
// Layouts
Hashtable layouts = new Hashtable();
foreach (
string layoutControl in
Directory.GetFiles(
HttpContext.Current.Server.MapPath(Path.ApplicationRoot + "/Design/PictureLayouts"), "*.ascx"))
{
string layoutControlDisplayName =
layoutControl.Substring(layoutControl.LastIndexOf("\\") + 1,
layoutControl.LastIndexOf(".") - layoutControl.LastIndexOf("\\") - 1);
string layoutControlName = layoutControl.Substring(layoutControl.LastIndexOf("\\") + 1);
layouts.Add(layoutControlDisplayName, layoutControlName);
}
// Thumbnail Layout Setting
SettingItem ThumbnailLayoutSetting = new SettingItem(new CustomListDataType(layouts, "Key", "Value"));
ThumbnailLayoutSetting.Required = true;
ThumbnailLayoutSetting.Value = "DefaultThumbnailView.ascx";
ThumbnailLayoutSetting.Order = 12;
_baseSettings.Add("ThumbnailLayout", ThumbnailLayoutSetting);
// Thumbnail Layout Setting
SettingItem ImageLayoutSetting = new SettingItem(new CustomListDataType(layouts, "Key", "Value"));
ImageLayoutSetting.Required = true;
ImageLayoutSetting.Value = "DefaultImageView.ascx";
ImageLayoutSetting.Order = 13;
_baseSettings.Add("ImageLayout", ImageLayoutSetting);
// PicturesPerPage
SettingItem PicturesPerPage = new SettingItem(new IntegerDataType());
PicturesPerPage.Required = true;
PicturesPerPage.Value = "9999";
PicturesPerPage.Order = 14;
PicturesPerPage.MinValue = 1;
PicturesPerPage.MaxValue = 9999;
_baseSettings.Add("PicturesPerPage", PicturesPerPage);
//If false the input box for bulk loads will be hidden
SettingItem AllowBulkLoad = new SettingItem(new BooleanDataType());
AllowBulkLoad.Value = "false";
AllowBulkLoad.Order = 15;
_baseSettings.Add("AllowBulkLoad", AllowBulkLoad);
}
#region Global Implementation
/// <summary>
/// GuidID
/// </summary>
public override Guid GuidID
{
get { return new Guid("{B29CB86B-AEA1-4E94-8B77-B4E4239258B0}"); }
}
#region Search Implementation
/// <summary>
/// Searchable module
/// </summary>
public override bool Searchable
{
get { return true; }
}
/// <summary>
/// Searchable module implementation
/// </summary>
/// <param name="portalID">The portal ID</param>
/// <param name="userID">ID of the user is searching</param>
/// <param name="searchString">The text to search</param>
/// <param name="searchField">The fields where perfoming the search</param>
/// <returns>The SELECT sql to perform a search on the current module</returns>
public override string SearchSqlSelect(int portalID, int userID, string searchString, string searchField)
{
// Parameters:
// Table Name: the table that holds the data
// Title field: the field that contains the title for result, must be a field in the table
// Abstract field: the field that contains the text for result, must be a field in the table
// Search field: pass the searchField parameter you recieve.
SearchDefinition s =
new SearchDefinition("rb_Pictures", "ShortDescription", "Keywords", "CreatedByUser", "CreatedDate",
"Keywords");
//Add here extra search fields, this way
s.ArrSearchFields.Add("itm.ShortDescription");
// Builds and returns the SELECT query
return s.SearchSqlSelect(portalID, userID, searchString);
}
#endregion
#region Install / Uninstall Implementation
/// <summary>
///
/// </summary>
/// <param name="stateSaver"></param>
public override void Install(IDictionary stateSaver)
{
string currentScriptName = System.IO.Path.Combine(Server.MapPath(TemplateSourceDirectory), "install.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
/// <summary>
///
/// </summary>
/// <param name="stateSaver"></param>
public override void Uninstall(IDictionary stateSaver)
{
string currentScriptName = System.IO.Path.Combine(Server.MapPath(TemplateSourceDirectory), "uninstall.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
#endregion
#endregion
#region Web Form Designer generated code
/// <summary>
/// Raises Init event
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
InitializeComponent();
this.dlPictures.EnableViewState = false;
pgPictures.OnMove += new EventHandler(Page_Changed);
this.AddText = "ADD"; //"Add New Picture"
this.AddUrl = "~/DesktopModules/Pictures/PicturesEdit.aspx";
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new EventHandler(this.Page_Load);
}
#endregion
/// <summary>
/// Structure used for list settings
/// </summary>
public struct Option
{
private int val;
private string name;
/// <summary>
///
/// </summary>
public int Val
{
get { return this.val; }
set { this.val = value; }
}
/// <summary>
///
/// </summary>
public string Name
{
get { return this.name; }
set { this.name = value; }
}
/// <summary>
///
/// </summary>
/// <param name="aVal"></param>
/// <param name="aName"></param>
public Option(int aVal, string aName)
{
val = aVal;
name = aName;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Windows.Forms;
using System.IO;
namespace ReplayEditor2
{
public class Canvas : Game
{
public static Color[] Color_Cursor = new Color[7] { Color.Red, Color.Cyan, Color.Lime, Color.Yellow, Color.Magenta, new Color(128, 128, 255, 255), Color.Honeydew };
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
public Vector2 Size { get; set; }
public int FirstHitObjectTime { get; set; }
public int MaxSongTime { get; set; }
public byte ShowHelp { get; set; }
private SongPlayer songPlayer = null;
public Form ParentForm { get; set; }
public Control XNAForm { get; set; }
public IntPtr DrawingSurface { get; set; }
private List<List<ReplayAPI.ReplayFrame>> replayFrames;
private List<List<ReplayAPI.ReplayFrame>> nearbyFrames;
private List<ReplayAPI.ReplayFrame> selectedFrames;
private List<BMAPI.v1.HitObjects.CircleObject> nearbyHitObjects;
public BMAPI.v1.Beatmap Beatmap { get; set; }
private Rectangle ToolRect;
private MouseState LastMouseState;
private MouseState CurrentMouseState;
private int approachRate = 0;
private int circleDiameter = 0;
public int State_TimeRange { get; set; }
public int State_CurveSmoothness { get; set; }
public float State_PlaybackSpeed
{
get { return this.state_PlaybackSpeed; }
set
{
this.state_PlaybackSpeed = value;
MainForm.self.UpdateSpeedRadio(value);
this.songPlayer.SetPlaybackSpeed(value);
}
}
public byte State_ReplaySelected
{
get { return this.state_ReplaySelected; }
set
{
this.state_ReplaySelected = value;
MainForm.self.UpdateReplayRadio(value);
MainForm.self.MetadataForm.LoadReplay(value);
}
}
public float State_Volume
{
get
{
return this.state_volume;
}
set
{
this.state_volume = value;
this.songPlayer.SetVolume(value);
}
}
public byte State_PlaybackMode { get; set; }
public byte State_PlaybackFlow { get; set; }
public int State_FadeTime { get; set; }
public Color State_BackgroundColor { get; set; }
public byte State_ToolSelected { get; set; }
public float Visual_BeatmapAR { get; set; }
public bool Visual_HardRockAR { get; set; }
public bool Visual_EasyAR { get; set; }
public float Visual_BeatmapCS { get; set; }
public bool Visual_HardRockCS { get; set; }
public bool Visual_EasyCS { get; set; }
public bool Visual_MapInvert { get; set; }
private float state_PlaybackSpeed;
private byte state_ReplaySelected;
private float state_volume;
private Texture2D nodeTexture;
private Texture2D cursorTexture;
private Texture2D lineTexture;
private Texture2D hitCircleTexture;
private Texture2D sliderFollowCircleTexture;
private Texture2D spinnerTexture;
private Texture2D approachCircleTexture;
private Texture2D helpTexture;
private Texture2D sliderEdgeTexture;
private Texture2D sliderBodyTexture;
private Texture2D reverseArrowTexture;
public Canvas(IntPtr surface, Form form)
{
this.DrawingSurface = surface;
this.ParentForm = form;
this.MaxSongTime = 0;
this.FirstHitObjectTime = 0;
this.ShowHelp = 2;
this.songPlayer = new SongPlayer();
this.graphics = new GraphicsDeviceManager(this);
this.graphics.PreferredBackBufferWidth = 832;
this.graphics.PreferredBackBufferHeight = 624;
this.Size = new Vector2(this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight);
this.Content.RootDirectory = "Content";
this.nearbyHitObjects = new List<BMAPI.v1.HitObjects.CircleObject>();
this.replayFrames = new List<List<ReplayAPI.ReplayFrame>>();
this.nearbyFrames = new List<List<ReplayAPI.ReplayFrame>>();
for (int i = 0; i < 7; i++)
{
this.replayFrames.Add(null);
this.nearbyFrames.Add(new List<ReplayAPI.ReplayFrame>());
}
this.ToolRect = new Rectangle(0, 0, 0, 0);
this.CurrentMouseState = Mouse.GetState();
this.Beatmap = null;
this.IsFixedTimeStep = false;
this.graphics.PreparingDeviceSettings += graphics_PreparingDeviceSettings;
this.XNAForm = Control.FromHandle(this.Window.Handle);
Mouse.WindowHandle = this.DrawingSurface;
this.XNAForm.VisibleChanged += XNAForm_VisibleChanged;
this.ParentForm.FormClosing += ParentForm_FormClosing;
this.State_TimeRange = 1000;
this.State_CurveSmoothness = 50;
this.State_PlaybackSpeed = 1.0f;
this.State_ReplaySelected = 0;
this.State_PlaybackMode = 0;
this.State_PlaybackFlow = 0;
this.State_FadeTime = 200;
this.State_BackgroundColor = Color.Black;
this.State_ToolSelected = 0;
this.Visual_BeatmapAR = 0.0f;
this.Visual_HardRockAR = false;
this.Visual_HardRockCS = false;
this.Visual_EasyAR = false;
this.Visual_EasyCS = false;
this.Visual_MapInvert = false;
}
private void ParentForm_FormClosing(object sender, FormClosingEventArgs e)
{
this.songPlayer.Stop();
this.Exit();
}
private void XNAForm_VisibleChanged(object sender, EventArgs e)
{
if (XNAForm.Visible)
{
XNAForm.Visible = false;
}
}
private void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
{
e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = this.DrawingSurface;
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
this.spriteBatch = new SpriteBatch(this.GraphicsDevice);
this.nodeTexture = this.TextureFromFile(MainForm.Path_Img_EditorNode);
this.cursorTexture = this.TextureFromFile(MainForm.Path_Img_Cursor);
this.hitCircleTexture = this.TextureFromFile(MainForm.Path_Img_Hitcircle);
this.sliderFollowCircleTexture = this.TextureFromFile(MainForm.Path_Img_SliderFollowCircle);
this.spinnerTexture = this.TextureFromFile(MainForm.Path_Img_Spinner);
this.approachCircleTexture = this.TextureFromFile(MainForm.Path_Img_ApproachCircle);
this.helpTexture = this.TextureFromFile(MainForm.Path_Img_Help);
this.sliderEdgeTexture = this.TextureFromFile(MainForm.Path_Img_SliderEdge);
this.sliderBodyTexture = this.TextureFromFile(MainForm.Path_Img_SliderBody);
this.lineTexture = this.TextureFromColor(Color.White);
this.reverseArrowTexture = this.TextureFromFile(MainForm.Path_Img_ReverseArrow);
}
private Texture2D TextureFromFile(string path)
{
try
{
return Texture2D.FromStream(this.GraphicsDevice, new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read));
}
catch
{
MainForm.ErrorMessage(String.Format("Could not the load the image found at \"{0}\", please make sure it exists and is a valid .png image.\nRedownloading the .zip file will also restore lost images and update new ones.", path));
return this.TextureFromColor(Color.Magenta);
}
}
private Texture2D TextureFromColor(Color color, int w = 1, int h = 1)
{
Texture2D texture = new Texture2D(this.GraphicsDevice, w, h);
Color[] data = new Color[w * h];
for (int i = 0; i < w * h; i++)
{
data[i] = color;
}
texture.SetData<Color>(data);
return texture;
}
protected override void UnloadContent()
{
this.nodeTexture.Dispose();
this.cursorTexture.Dispose();
this.hitCircleTexture.Dispose();
this.sliderFollowCircleTexture.Dispose();
this.spinnerTexture.Dispose();
this.approachCircleTexture.Dispose();
this.helpTexture.Dispose();
this.sliderEdgeTexture.Dispose();
this.sliderBodyTexture.Dispose();
this.lineTexture.Dispose();
this.reverseArrowTexture.Dispose();
}
protected override void Update(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.H))
{
this.ShowHelp = 1;
}
else if (this.ShowHelp != 2)
{
this.ShowHelp = 0;
}
if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.D) || Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Right))
{
this.State_PlaybackFlow = 2;
}
else if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.A) || Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Left))
{
this.State_PlaybackFlow = 1;
}
else if (this.State_PlaybackFlow != 3)
{
this.State_PlaybackFlow = 0;
}
MainForm.self.SetPlayPause("Play");
if (this.State_PlaybackFlow == 0)
{
this.songPlayer.Pause();
}
else if (this.State_PlaybackFlow == 1)
{
this.songPlayer.Pause();
this.songPlayer.JumpTo((long)(this.songPlayer.SongTime - (gameTime.ElapsedGameTime.Milliseconds * this.State_PlaybackSpeed)));
}
else if (this.State_PlaybackFlow == 2)
{
this.songPlayer.Play();
}
else if (this.State_PlaybackFlow == 3)
{
MainForm.self.SetPlayPause("Pause");
this.songPlayer.Play();
}
if (this.MaxSongTime != 0)
{
MainForm.self.SetTimelinePercent((float)this.songPlayer.SongTime / (float)this.MaxSongTime);
}
MainForm.self.SetSongTimeLabel((int)this.songPlayer.SongTime);
this.nearbyHitObjects = new List<BMAPI.v1.HitObjects.CircleObject>();
if (this.Beatmap != null)
{
// we take advantage of the fact that the hitobjects are listed in chronological order and implement a binary search
// this will the index of the hitobject closest (rounded down) to the time
// we will get all the hitobjects a couple seconds after and before the current time
int startIndex = this.BinarySearchHitObjects((float)(this.songPlayer.SongTime - 10000)) - 5;
int endIndex = this.BinarySearchHitObjects((float)(this.songPlayer.SongTime + 2000)) + 5;
for (int k = startIndex; k < endIndex; k++)
{
if (k < 0)
{
continue;
}
else if (k >= this.Beatmap.HitObjects.Count)
{
break;
}
this.nearbyHitObjects.Add(this.Beatmap.HitObjects[k]);
}
}
for (int j = 0; j < 7; j++)
{
if (this.replayFrames[j] != null)
{
if (this.replayFrames[j].Count == 0)
{
MainForm.ErrorMessage("This replay contains no cursor data.");
this.replayFrames[j] = null;
continue;
}
// like the hitobjects, the replay frames are also in chronological order
// so we use more binary searches to efficiently get the index of the replay frame at a time
this.nearbyFrames[j] = new List<ReplayAPI.ReplayFrame>();
if (this.State_PlaybackMode == 0)
{
int lowIndex = this.BinarySearchReplayFrame(j, (int)(this.songPlayer.SongTime) - this.State_TimeRange);
int highIndex = this.BinarySearchReplayFrame(j, (int)this.songPlayer.SongTime) + 1;
for (int i = lowIndex; i <= highIndex; i++)
{
this.nearbyFrames[j].Add(this.replayFrames[j][i]);
}
}
else if (this.State_PlaybackMode == 1)
{
int nearestIndex = this.BinarySearchReplayFrame(j, (int)this.songPlayer.SongTime);
this.nearbyFrames[j].Add(this.replayFrames[j][nearestIndex]);
if (nearestIndex + 1 < this.replayFrames[j].Count)
{
this.nearbyFrames[j].Add(this.replayFrames[j][nearestIndex + 1]);
}
}
}
}
this.LastMouseState = this.CurrentMouseState;
this.CurrentMouseState = Mouse.GetState();
if (this.State_PlaybackMode == 0)
{
if (this.LastMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Released && this.CurrentMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
{
this.ToolRect.X = this.CurrentMouseState.X;
this.ToolRect.Y = this.CurrentMouseState.Y;
}
else if (this.LastMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed && this.CurrentMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
{
this.ToolRect.Width = this.CurrentMouseState.X - this.ToolRect.X;
this.ToolRect.Height = this.CurrentMouseState.Y - this.ToolRect.Y;
}
else if (this.LastMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed && this.CurrentMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Released)
{
if (this.ToolRect.X >= 0 && this.ToolRect.X <= this.Size.X && this.ToolRect.Y >= 0 && this.ToolRect.Y <= this.Size.Y)
{
this.ToolAction();
}
this.ToolRect.Width = 0;
this.ToolRect.Height = 0;
}
}
else
{
this.ToolRect.Width = 0;
this.ToolRect.Height = 0;
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(this.State_BackgroundColor);
this.spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.NonPremultiplied);
for (int b = this.nearbyHitObjects.Count - 1; b >= 0; b--)
{
BMAPI.v1.HitObjects.CircleObject hitObject = this.nearbyHitObjects[b];
// the song time relative to the hitobject start time
float diff = (float)(hitObject.StartTime - this.songPlayer.SongTime);
// transparency of hitobject
float alpha = 1.0f;
// a percentage of how open a slider is, 1.0 is closed, 0.0 is open
float approachCircleValue = 0.0f;
// length in time of hit object (only applies to sliders and spinners)
int hitObjectLength = 0;
// Use these types if the hitobject is a slider or spinner
BMAPI.v1.HitObjects.SliderObject hitObjectAsSlider = null;
BMAPI.v1.HitObjects.SpinnerObject hitObjectAsSpinner = null;
if (hitObject.Type.HasFlag(BMAPI.v1.HitObjectType.Spinner))
{
hitObjectAsSpinner = (BMAPI.v1.HitObjects.SpinnerObject)hitObject;
hitObjectLength = (int)(hitObjectAsSpinner.EndTime - hitObjectAsSpinner.StartTime);
}
else if (hitObject.Type.HasFlag(BMAPI.v1.HitObjectType.Slider))
{
hitObjectAsSlider = (BMAPI.v1.HitObjects.SliderObject)hitObject;
hitObjectLength = (int)((hitObjectAsSlider.SegmentEndTime - hitObjectAsSlider.StartTime) * hitObjectAsSlider.RepeatCount);
//hitObjectLength = 500;
}
// for reference: this.approachRate is the time in ms it takes for approach circle to close
if (diff < this.approachRate + this.State_FadeTime && diff > -(hitObjectLength + this.State_FadeTime))
{
if (diff < -hitObjectLength)
{
// fade out
alpha = 1 - ((diff + hitObjectLength) / -(float)this.State_FadeTime);
}
else if (!hitObject.Type.HasFlag(BMAPI.v1.HitObjectType.Spinner) && diff >= this.approachRate && diff < this.approachRate + this.State_FadeTime)
{
// fade in
alpha = 1 - (diff - this.approachRate) / (float)this.State_FadeTime;
}
else if (hitObject.Type.HasFlag(BMAPI.v1.HitObjectType.Spinner))
{
// because spinners don't have an approach circle before they appear
if (diff >= 0 && diff < this.State_FadeTime)
{
alpha = 1 - diff / (float)this.State_FadeTime;
}
else if (diff > 0)
{
alpha = 0;
}
}
if (diff < this.approachRate + this.State_FadeTime && diff > 0)
{
// hitcircle percentage from open to closed
approachCircleValue = diff / (float)(this.approachRate + this.State_FadeTime);
}
else if (diff > 0)
{
approachCircleValue = 1.0f;
}
if (hitObject.Type.HasFlag(BMAPI.v1.HitObjectType.Circle))
{
this.DrawHitcircle(hitObject, alpha, b);
this.DrawApproachCircle(hitObject, alpha, approachCircleValue);
}
else if (hitObject.Type.HasFlag(BMAPI.v1.HitObjectType.Slider))
{
this.DrawSlider(hitObjectAsSlider, alpha, b, approachCircleValue);
}
else if (hitObject.Type.HasFlag(BMAPI.v1.HitObjectType.Spinner))
{
this.DrawSpinner(hitObjectAsSpinner, alpha);
this.DrawSpinnerApproachCircle(hitObjectAsSpinner, alpha, (float)(this.songPlayer.SongTime - hitObjectAsSpinner.StartTime) / (hitObjectAsSpinner.EndTime - hitObjectAsSpinner.StartTime));
}
}
}
if (this.State_PlaybackMode == 0)
{
Vector2 currentPos = Vector2.Zero;
Vector2 lastPos = new Vector2(-222, 0);
for (int i = 0; i < this.nearbyFrames[this.state_ReplaySelected].Count; i++)
{
ReplayAPI.ReplayFrame currentFrame = this.nearbyFrames[this.state_ReplaySelected][i];
float alpha = i / (float)this.nearbyFrames[this.state_ReplaySelected].Count;
currentPos = this.InflateVector(new Vector2(currentFrame.X, currentFrame.Y));
bool selected = false;
if (this.selectedFrames != null)
{
selected = this.selectedFrames.Contains(currentFrame);
}
if (lastPos.X != -222)
{
Color linecolor;
if (selected)
{
linecolor = Color.White;
}
else
{
linecolor = new Color(1.0f, 0.0f, 0.0f, alpha);
}
this.DrawLine(lastPos, currentPos, linecolor);
}
Color nodeColor = Color.Gray;
if (currentFrame.Keys.HasFlag(ReplayAPI.Keys.K1))
{
nodeColor = Color.Cyan;
}
else if (currentFrame.Keys.HasFlag(ReplayAPI.Keys.K2))
{
nodeColor = Color.Magenta;
}
else if (currentFrame.Keys.HasFlag(ReplayAPI.Keys.M1))
{
nodeColor = Color.Lime;
}
else if (currentFrame.Keys.HasFlag(ReplayAPI.Keys.M2))
{
nodeColor = Color.Yellow;
}
if (! selected)
{
nodeColor.A = (byte)(alpha * 255);
}
this.spriteBatch.Draw(this.nodeTexture, currentPos - new Vector2(5, 5), nodeColor);
lastPos = currentPos;
}
if (this.ToolRect.Width != 0 && this.ToolRect.Height != 0)
{
this.DrawTool();
}
}
else if (this.State_PlaybackMode == 1)
{
for (int i = 0; i < 7; i++)
{
if (this.nearbyFrames[i] != null && this.nearbyFrames[i].Count >= 1)
{
this.spriteBatch.Draw(this.cursorTexture, this.InflateVector(this.GetInterpolatedFrame(i)) - new Vector2(this.cursorTexture.Width, this.cursorTexture.Height) / 2f, Canvas.Color_Cursor[i]);
}
}
}
if (this.ShowHelp != 0)
{
this.spriteBatch.Draw(this.helpTexture, Vector2.Zero, Color.White);
}
this.spriteBatch.End();
base.Draw(gameTime);
}
private int BinarySearchReplayFrame(int replaynum, int target)
{
int high = this.replayFrames[replaynum].Count - 1;
int low = 0;
while (low <= high)
{
int mid = (high + low) / 2;
if (mid == high || mid == low)
{
return mid;
}
if (this.replayFrames[replaynum][mid].Time >= target)
{
high = mid;
}
else
{
low = mid;
}
}
return 0;
}
private int BinarySearchHitObjects(float target)
{
if (this.Beatmap == null)
{
return -1;
}
int high = this.Beatmap.HitObjects.Count - 1;
int low = 0;
while (low <= high)
{
int mid = (high + low) / 2;
if (mid == high || mid == low)
{
return mid;
}
else if (this.Beatmap.HitObjects[mid].StartTime > target)
{
high = mid;
}
else
{
low = mid;
}
}
return 0;
}
private void DrawLine(Vector2 start, Vector2 end, Color color, int width = 1)
{
Rectangle r = new Rectangle((int)start.X, (int)start.Y, (int)(end - start).Length() + width, width);
Vector2 v = Vector2.Normalize(start - end);
float angle = (float)Math.Acos(Vector2.Dot(v, -Vector2.UnitX));
if (start.Y > end.Y)
{
angle = 6.28318530717f - angle;
}
spriteBatch.Draw(this.lineTexture, r, null, color, angle, Vector2.Zero, SpriteEffects.None, 0);
}
private void DrawHitcircle(BMAPI.v1.HitObjects.CircleObject hitObject, float alpha, int zindex)
{
int diameter = (int)(this.circleDiameter * this.Size.X / 512f);
Vector2 pos = this.InflateVector(hitObject.Location.ToVector2(), true);
this.DrawHitcircle(pos, diameter, alpha, zindex);
}
private void DrawHitcircle(Vector2 pos, int diameter, float alpha, int zindex)
{
Rectangle rect = new Rectangle((int)pos.X, (int)pos.Y, diameter, diameter);
rect.X -= rect.Width / 2;
rect.Y -= rect.Height / 2;
float depth = zindex / 1000.0f;
this.spriteBatch.Draw(this.hitCircleTexture, rect, null, new Color(1.0f, 1.0f, 1.0f, alpha), 0f, Vector2.Zero, SpriteEffects.None, 0.1f + depth);
}
private void DrawApproachCircle(BMAPI.v1.HitObjects.CircleObject hitObject, float alpha, float value)
{
float smallDiameter = this.circleDiameter * this.Size.X / 512f;
float largeDiameter = smallDiameter * 3.0f;
// linearly interpolate between two diameters
// makes approach circle shrink
int diameter = (int)(smallDiameter + (largeDiameter - smallDiameter) * value);
Vector2 pos = this.InflateVector(new Vector2(hitObject.Location.X, hitObject.Location.Y), true);
Rectangle rect = new Rectangle((int)pos.X, (int)pos.Y, diameter, diameter);
rect.X -= rect.Width / 2;
rect.Y -= rect.Height / 2;
this.spriteBatch.Draw(this.approachCircleTexture, rect, null, new Color(1.0f, 1.0f, 1.0f, alpha), 0f, Vector2.Zero, SpriteEffects.None, 0);
}
private void DrawSpinnerApproachCircle(BMAPI.v1.HitObjects.SpinnerObject hitObject, float alpha, float value)
{
if (value < 0)
{
value = 0;
}
else if (value > 1)
{
value = 1;
}
int diameter = (int)(this.spinnerTexture.Width * (1 - value) * 0.9);
Vector2 pos = this.InflateVector(new Vector2(hitObject.Location.X, hitObject.Location.Y), true);
Rectangle rect = new Rectangle((int)pos.X, (int)pos.Y, diameter, diameter);
rect.X -= rect.Width / 2;
rect.Y -= rect.Height / 2;
this.spriteBatch.Draw(this.spinnerTexture, rect, null, new Color(1.0f, 1.0f, 1.0f, alpha), 0f, Vector2.Zero, SpriteEffects.None, 0.0f);
}
private void DrawSpinner(BMAPI.v1.HitObjects.SpinnerObject hitObject, float alpha)
{
int diameter = (int)this.Size.Y;
Vector2 pos = this.InflateVector(new Vector2(hitObject.Location.X, hitObject.Location.Y));
Rectangle rect = new Rectangle((int)pos.X, (int)pos.Y, diameter, diameter);
rect.X -= rect.Width / 2;
rect.Y -= rect.Height / 2;
this.spriteBatch.Draw(this.spinnerTexture, rect, null, new Color(1.0f, 1.0f, 1.0f, alpha), 0f, Vector2.Zero, SpriteEffects.None, 0.1f);
}
private void DrawSlider(BMAPI.v1.HitObjects.SliderObject hitObject, float alpha, int zindex, float approachCircleValue)
{
float time = (float)(this.songPlayer.SongTime - hitObject.StartTime) / (float)((hitObject.SegmentEndTime - hitObject.StartTime) * hitObject.RepeatCount);
byte reverseArrowType = (hitObject.RepeatCount > 1) ? (byte)1 : (byte)0;
if (time < 0)
{
this.DrawHitcircle(hitObject, alpha, zindex);
this.DrawApproachCircle(hitObject, alpha, approachCircleValue);
this.DrawSliderBody(hitObject, alpha, this.circleDiameter / 2, zindex, reverseArrowType);
return;
}
else if (time > 1)
{
time = 1;
}
time *= hitObject.RepeatCount;
if (time > 1)
{
bool drawArrow = time - (hitObject.RepeatCount - 1) < 0;
int order = 0;
while (time > 1)
{
time -= 1;
order++;
reverseArrowType = drawArrow ? (byte)1 : (byte)0;
}
if (order % 2 != 0)
{
time = 1 - time;
reverseArrowType = drawArrow ? (byte)2 : (byte)0;
}
}
this.DrawSliderBody(hitObject, alpha, this.circleDiameter / 2, zindex, reverseArrowType);
Vector2 pos = this.InflateVector(hitObject.PositionAtTime(time), true);
// 128x128 is the size of the sprite image for hitcircles
int diameter = (int)(this.circleDiameter / 128f * this.sliderFollowCircleTexture.Width * this.Size.X / 512f);
Rectangle rect = new Rectangle((int)pos.X, (int)pos.Y, diameter, diameter);
rect.X -= rect.Width / 2;
rect.Y -= rect.Height / 2;
this.spriteBatch.Draw(this.sliderFollowCircleTexture, rect, null, new Color(1.0f, 1.0f, 1.0f, alpha), 0f, Vector2.Zero, SpriteEffects.None, 0f);
}
private void DrawSliderBody(BMAPI.v1.HitObjects.SliderObject hitObject, float alpha, int radius, int zindex, byte reverseArrowType)
{
float smallLength = hitObject.TotalLength;
Color color = Color.White;
float depthHigh = (zindex * 3 + 2) / 1000.0f;
float depthMed = (zindex * 3 + 1) / 1000.0f;
float depthLow = (zindex * 3) / 1000.0f;
byte alphaByte = (byte)(255 * alpha);
Rectangle firstRect = new Rectangle(-222, -222, 222, 222);
Rectangle lastRect = new Rectangle(-222, -222, 222, 222);
Rectangle firstRectDiff = new Rectangle(-222, -222, 222, 222);
Rectangle lastRectDiff = new Rectangle(-222, -222, 222, 222);
for (float i = 0; i < smallLength + 10; i += 10)
{
if (i > smallLength)
{
i = smallLength;
}
Vector2 pos = this.InflateVector(hitObject.PositionAtTime(i / smallLength), true);
int diameter = (int)(this.circleDiameter * this.Size.X / 512f);
Rectangle rect = new Rectangle((int)pos.X, (int)pos.Y, diameter, diameter);
rect.X -= rect.Width / 2;
rect.Y -= rect.Height / 2;
if (firstRect.X == -222)
{
firstRect = rect;
}
else if (firstRectDiff.X == -222)
{
firstRectDiff = rect;
}
lastRectDiff = lastRect;
lastRect = rect;
color.A = alphaByte;
this.spriteBatch.Draw(this.sliderEdgeTexture, rect, null, color, 0f, Vector2.Zero, SpriteEffects.None, 0.4f + depthHigh);
color.A = 255;
this.spriteBatch.Draw(this.sliderBodyTexture, rect, null, color, 0f, Vector2.Zero, SpriteEffects.None, 0.4f + depthMed);
if (i == smallLength)
{
break;
}
}
if (reverseArrowType != 0)
{
color.A = alphaByte;
Rectangle mode;
float rotation;
if (reverseArrowType == 1)
{
mode = lastRect;
rotation = (float)Math.Atan2(lastRectDiff.Y - lastRect.Y, lastRectDiff.X - lastRect.X);
}
else
{
rotation = (float)Math.Atan2(firstRectDiff.Y - firstRect.Y, firstRectDiff.X - firstRect.X);
mode = firstRect;
}
mode.X += 52;
mode.Y += 52;
this.spriteBatch.Draw(this.reverseArrowTexture, mode, null, color, rotation, new Vector2(64.0f), SpriteEffects.None, 0.4f + depthLow);
}
}
private void DrawBoxOutline(Rectangle rect, Color color)
{
Vector2 rp0 = new Vector2(rect.X, rect.Y);
Vector2 rp1 = new Vector2(rect.X + rect.Width, rect.Y);
Vector2 rp2 = new Vector2(rect.X + rect.Width, rect.Y + rect.Height);
Vector2 rp3 = new Vector2(rect.X, rect.Y + rect.Height);
this.DrawLine(rp0, rp1, color);
this.DrawLine(rp1, rp2, color);
this.DrawLine(rp2, rp3, color);
this.DrawLine(rp3, rp0, color);
}
public void LoadReplay(ReplayAPI.Replay replay)
{
this.ShowHelp = 0;
MainForm.self.MetadataForm.LoadReplay(this.State_ReplaySelected);
this.replayFrames[this.state_ReplaySelected] = replay.ReplayFrames;
this.JumpTo(0);
this.State_PlaybackFlow = 0;
if (replay.ReplayFrames.Count > 0)
{
this.MaxSongTime = replay.ReplayFrames[replay.ReplayFrames.Count - 1].Time;
}
else
{
this.MaxSongTime = 0;
}
if (this.Beatmap != null)
{
this.FirstHitObjectTime = (int)this.Beatmap.HitObjects[0].StartTime;
this.Visual_BeatmapAR = this.Beatmap.ApproachRate;
this.Visual_BeatmapCS = this.Beatmap.CircleSize;
this.songPlayer.Start(Path.Combine(this.Beatmap.Folder, this.Beatmap.AudioFilename));
this.JumpTo(this.FirstHitObjectTime - 1000);
}
this.ApplyMods(replay);
}
public void ApplyMods(ReplayAPI.Replay replay)
{
if (replay.Mods.HasFlag(ReplayAPI.Mods.Easy))
{
this.Visual_EasyAR = true;
this.Visual_EasyCS = true;
this.Visual_HardRockAR = false;
this.Visual_HardRockCS = false;
}
else if (replay.Mods.HasFlag(ReplayAPI.Mods.HardRock))
{
this.Visual_EasyAR = false;
this.Visual_EasyCS = false;
this.Visual_HardRockAR = true;
this.Visual_HardRockCS = true;
}
else
{
this.Visual_EasyAR = false;
this.Visual_EasyCS = false;
this.Visual_HardRockAR = false;
this.Visual_HardRockCS = false;
}
if (replay.Mods.HasFlag(ReplayAPI.Mods.DoubleTime))
{
this.State_PlaybackSpeed = 1.5f;
}
else if (replay.Mods.HasFlag(ReplayAPI.Mods.HalfTime))
{
State_PlaybackSpeed = 0.75f;
}
else
{
State_PlaybackSpeed = 1.0f;
}
this.UpdateApproachRate();
this.UpdateCircleSize();
this.Visual_MapInvert = this.Visual_HardRockAR && this.Visual_HardRockCS;
}
public void UnloadReplay(byte pos)
{
this.replayFrames[pos] = null;
this.nearbyFrames[pos] = new List<ReplayAPI.ReplayFrame>();
}
public void UpdateApproachRate()
{
// from beatmap approach rate to actual ms in approach rate
float moddedAR = this.Visual_BeatmapAR;
if (this.Visual_HardRockAR && !this.Visual_EasyAR)
{
moddedAR *= 1.4f;
}
else if (!this.Visual_HardRockAR && this.Visual_EasyAR)
{
moddedAR /= 2.0f;
}
if (moddedAR > 10)
{
moddedAR = 10;
}
this.approachRate = (int)(-150 * moddedAR + 1950);
}
public void UpdateCircleSize()
{
// from beatmap circle size to actual pixels in radius
float moddedCS = this.Visual_BeatmapCS;
if (this.Visual_HardRockCS && !this.Visual_EasyCS)
{
moddedCS *= 1.3f;
}
else if (!this.Visual_HardRockCS && this.Visual_EasyCS)
{
moddedCS /= 2.0f;
}
this.circleDiameter = (int)(2 * (40 - 4 * (moddedCS - 2)));
}
private Vector2 InflateVector(Vector2 vector, bool flipWhenHardrock = false)
{
// takes a vector with x: 0 - 512 and y: 0 - 384 and turns them into coordinates for whole canvas size
if (this.Visual_MapInvert && flipWhenHardrock)
{
return new Vector2(vector.X / 512f * this.Size.X, (384f - vector.Y) / 384f * this.Size.Y);
}
else
{
return new Vector2(vector.X / 512f * this.Size.X, vector.Y / 384f * this.Size.Y);
}
}
private Vector2 DeflateVector(Vector2 vector, bool flipWhenHardrock = false)
{
// takes a vector for the whole canvas and puts it with respect to x: 0 - 512 and y: 0 - 384
// opposite of inflate vector
if (this.Visual_MapInvert && flipWhenHardrock)
{
return new Vector2(vector.X / this.Size.X * 512f, (this.Size.Y - vector.Y) / this.Size.Y * 384f);
}
else
{
return new Vector2(vector.X / this.Size.X * 512f, vector.Y / this.Size.Y * 384f);
}
}
public void SetSongTimePercent(float percent)
{
// for when timeline is clicked, sets the song time in ms from percentage into the song
this.JumpTo((long)(percent * (float)this.MaxSongTime));
}
private Vector2 GetInterpolatedFrame(int replayNum)
{
// gets the cursor position at a given time based on the replay data
// if between two points, interpolate between
Vector2 p1 = new Vector2(this.nearbyFrames[replayNum][0].X, this.nearbyFrames[replayNum][0].Y);
Vector2 p2 = Vector2.Zero;
int t1 = this.nearbyFrames[replayNum][0].Time;
int t2 = t1 + 1;
// check to make sure it is not the final replay frame in the replay
if (this.nearbyFrames[replayNum].Count > 1)
{
p2.X = this.nearbyFrames[replayNum][1].X;
p2.Y = this.nearbyFrames[replayNum][1].Y;
t2 = this.nearbyFrames[replayNum][1].Time;
// While I don't think there would ever be two replay frames at the same time,
// this will prevent ever dividing by zero when calculating 'm'
if (t1 == t2)
{
t2++;
}
}
// 't' is the percentage (from 0.0 to 1.0) of time completed from one point to other
float t = ((float)this.songPlayer.SongTime - t1) / (float)(t2 - t1);
// Linearly interpolate between point 1 and point 2 based off the time percentage 'm'
return new Vector2(p1.X + (p2.X - p1.X) * t, p1.Y + (p2.Y - p1.Y) * t);
}
private void JumpTo(long value)
{
if (value < 0)
{
this.songPlayer.JumpTo(0);
this.State_PlaybackFlow = 0;
}
else if (value > this.MaxSongTime)
{
this.songPlayer.Stop();
this.State_PlaybackFlow = 0;
}
else
{
this.songPlayer.JumpTo(value);
}
}
private void ToolAction()
{
// a is the point first clicked
Vector2 a = new Vector2(this.ToolRect.X, this.ToolRect.Y);
// b is the point released
Vector2 b = new Vector2(this.ToolRect.X + this.ToolRect.Width, this.ToolRect.Y + this.ToolRect.Height);
// this always sets the rectangle so that the top left coords is the x and y, even if dragged from bottom right to top left
if (this.ToolRect.Width < 0)
{
this.ToolRect.X += this.ToolRect.Width;
this.ToolRect.Width *= -1;
}
if (this.ToolRect.Height < 0)
{
this.ToolRect.Y += this.ToolRect.Height;
this.ToolRect.Height *= -1;
}
if (this.State_ToolSelected == 0)
{
this.selectedFrames = new List<ReplayAPI.ReplayFrame>();
for (int i = 0; i < this.nearbyFrames[this.state_ReplaySelected].Count; i++)
{
ReplayAPI.ReplayFrame frame = this.nearbyFrames[this.state_ReplaySelected][i];
Vector2 frameCoor = this.InflateVector(new Vector2(frame.X, frame.Y));
if (frameCoor.X >= this.ToolRect.X && frameCoor.X < this.ToolRect.X + this.ToolRect.Width && frameCoor.Y >= this.ToolRect.Y && frameCoor.Y < this.ToolRect.Y + this.ToolRect.Height)
{
this.selectedFrames.Add(frame);
}
}
MainForm.self.SetNumberSelectedLabel(this.selectedFrames.Count);
}
else if (this.State_ToolSelected == 1)
{
Vector2 displace = this.DeflateVector(b - a);
for (int i = 0; i < this.selectedFrames.Count; i++)
{
ReplayAPI.ReplayFrame item = this.selectedFrames[i];
int k = this.replayFrames[this.State_ReplaySelected].IndexOf(item);
if (k >= 0)
{
ReplayAPI.ReplayFrame dup = new ReplayAPI.ReplayFrame();
dup.X = item.X + displace.X;
dup.Y = item.Y + displace.Y;
dup.Keys = item.Keys;
dup.Time = item.Time;
dup.TimeDiff = item.TimeDiff;
this.replayFrames[this.State_ReplaySelected][k] = dup;
this.selectedFrames[i] = dup;
}
}
}
else if (this.State_ToolSelected == 2)
{
Vector2 from = this.DeflateVector(a);
Vector2 to = this.DeflateVector(b);
for (int i = 0; i < this.selectedFrames.Count; i++)
{
ReplayAPI.ReplayFrame item = this.selectedFrames[i];
int k = this.replayFrames[this.State_ReplaySelected].IndexOf(item);
if (k >= 0)
{
ReplayAPI.ReplayFrame dup = new ReplayAPI.ReplayFrame();
float distance = (float)Math.Max(1, Math.Sqrt(Math.Pow(from.X - item.X, 2) + Math.Pow(from.Y - item.Y, 2)));
float reduction = (float)Math.Min(1, distance / 50);
dup.X = item.X + (to.X - item.X) * (1 - reduction);
dup.Y = item.Y + (to.Y - item.Y) * (1 - reduction);
dup.Keys = item.Keys;
dup.Time = item.Time;
dup.TimeDiff = item.TimeDiff;
this.replayFrames[this.State_ReplaySelected][k] = dup;
this.selectedFrames[i] = dup;
}
}
}
}
private void DrawTool()
{
// a is the point first clicked
Vector2 a = new Vector2(this.ToolRect.X, this.ToolRect.Y);
// b is the point released
Vector2 b = new Vector2(this.ToolRect.X + this.ToolRect.Width, this.ToolRect.Y + this.ToolRect.Height);
if (this.State_ToolSelected == 0)
{
this.DrawBoxOutline(this.ToolRect, Color.CornflowerBlue);
}
else if (this.State_ToolSelected == 1)
{
this.DrawLine(a, b, Color.CornflowerBlue);
}
else if (this.State_ToolSelected == 2)
{
float o = (Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y)) / 10f;
this.DrawLine(a + new Vector2(o, o), b, Color.CornflowerBlue);
this.DrawLine(a + new Vector2(-o, o), b, Color.CornflowerBlue);
this.DrawLine(a + new Vector2(o, -o), b, Color.CornflowerBlue);
this.DrawLine(a + new Vector2(-o, -o), b, Color.CornflowerBlue);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Design.Serialization
{
/// <summary>
/// A member relationship service is used by a serializer to announce that one
/// property is related to a property on another object. Consider a code
/// based serialization scheme where code is of the following form:
///
/// object1.Property1 = object2.Property2
///
/// Upon interpretation of this code, Property1 on object1 will be
/// set to the return value of object2.Property2. But the relationship
/// between these two objects is lost. Serialization schemes that
/// wish to maintain this relationship may install a MemberRelationshipService
/// into the serialization manager. When an object is deserialized
/// this service will be notified of these relationships. It is up to the service
/// to act on these notifications if it wishes. During serialization, the
/// service is also consulted. If a relationship exists the same
/// relationship is maintained by the serializer.
/// </summary>
public abstract class MemberRelationshipService
{
private readonly Dictionary<RelationshipEntry, RelationshipEntry> _relationships = new Dictionary<RelationshipEntry, RelationshipEntry>();
/// <summary>
/// Returns the current relationship associated with the source, or MemberRelationship.Empty if
/// there is no relationship. Also sets a relationship between two objects. Empty
/// can also be passed as the property value, in which case the relationship will
/// be cleared.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1043:UseIntegralOrStringArgumentForIndexers")]
public MemberRelationship this[MemberRelationship source]
{
get
{
// The Owner and Member properties can be null if the MemberRelationship is constructed
// using the default constructor. However there is no situation in which one is null
// and not the other as the main constructor performs argument validation.
if (source.Owner == null)
{
throw new ArgumentNullException(nameof(MemberRelationship.Owner));
}
Debug.Assert(source.Member != null);
return GetRelationship(source);
}
set
{
// The Owner and Member properties can be null if the MemberRelationship is constructed
// using the default constructor. However there is no situation in which one is null
// and not the other as the main constructor performs argument validation.
if (source.Owner == null)
{
throw new ArgumentNullException(nameof(MemberRelationship.Owner));
}
Debug.Assert(source.Member != null);
SetRelationship(source, value);
}
}
/// <summary>
/// Returns the current relationship associated with the source, or null if there is no relationship.
/// Also sets a relationship between two objects. Null can be passed as the property value, in which
/// case the relationship will be cleared.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1023:IndexersShouldNotBeMultidimensional")]
public MemberRelationship this[object sourceOwner, MemberDescriptor sourceMember]
{
get
{
if (sourceOwner == null)
{
throw new ArgumentNullException(nameof(sourceOwner));
}
if (sourceMember == null)
{
throw new ArgumentNullException(nameof(sourceMember));
}
return GetRelationship(new MemberRelationship(sourceOwner, sourceMember));
}
set
{
if (sourceOwner == null)
{
throw new ArgumentNullException(nameof(sourceOwner));
}
if (sourceMember == null)
{
throw new ArgumentNullException(nameof(sourceMember));
}
SetRelationship(new MemberRelationship(sourceOwner, sourceMember), value);
}
}
/// <summary>
/// This is the implementation API for returning relationships. The default implementation stores the
/// relationship in a table. Relationships are stored weakly, so they do not keep an object alive.
/// </summary>
protected virtual MemberRelationship GetRelationship(MemberRelationship source)
{
if (_relationships.TryGetValue(new RelationshipEntry(source), out RelationshipEntry retVal) && retVal._owner.IsAlive)
{
return new MemberRelationship(retVal._owner.Target, retVal._member);
}
return MemberRelationship.Empty;
}
/// <summary>
/// This is the implementation API for returning relationships. The default implementation stores the
/// relationship in a table. Relationships are stored weakly, so they do not keep an object alive. Empty can be
/// passed in for relationship to remove the relationship.
/// </summary>
protected virtual void SetRelationship(MemberRelationship source, MemberRelationship relationship)
{
if (!relationship.IsEmpty && !SupportsRelationship(source, relationship))
{
string sourceName = TypeDescriptor.GetComponentName(source.Owner);
string relName = TypeDescriptor.GetComponentName(relationship.Owner);
if (sourceName == null)
{
sourceName = source.Owner.ToString();
}
if (relName == null)
{
relName = relationship.Owner.ToString();
}
throw new ArgumentException(SR.Format(SR.MemberRelationshipService_RelationshipNotSupported, sourceName, source.Member.Name, relName, relationship.Member.Name));
}
_relationships[new RelationshipEntry(source)] = new RelationshipEntry(relationship);
}
/// <summary>
/// Returns true if the provided relationship is supported.
/// </summary>
public abstract bool SupportsRelationship(MemberRelationship source, MemberRelationship relationship);
/// <summary>
/// Used as storage in our relationship table
/// </summary>
private struct RelationshipEntry
{
internal WeakReference _owner;
internal MemberDescriptor _member;
private readonly int _hashCode;
internal RelationshipEntry(MemberRelationship rel)
{
_owner = new WeakReference(rel.Owner);
_member = rel.Member;
_hashCode = rel.Owner == null ? 0 : rel.Owner.GetHashCode();
}
public override bool Equals(object o)
{
Debug.Assert(o is RelationshipEntry, "This is only called indirectly from a dictionary only containing RelationshipEntry structs.");
return this == (RelationshipEntry)o;
}
public static bool operator ==(RelationshipEntry re1, RelationshipEntry re2)
{
object owner1 = (re1._owner.IsAlive ? re1._owner.Target : null);
object owner2 = (re2._owner.IsAlive ? re2._owner.Target : null);
return owner1 == owner2 && re1._member.Equals(re2._member);
}
public static bool operator !=(RelationshipEntry re1, RelationshipEntry re2)
{
return !(re1 == re2);
}
public override int GetHashCode() => _hashCode;
}
}
/// <summary>
/// This class represents a single relationship between an object and a member.
/// </summary>
public readonly struct MemberRelationship
{
public static readonly MemberRelationship Empty = new MemberRelationship();
/// <summary>
/// Creates a new member relationship.
/// </summary>
public MemberRelationship(object owner, MemberDescriptor member)
{
Owner = owner ?? throw new ArgumentNullException(nameof(owner));
Member = member ?? throw new ArgumentNullException(nameof(member));
}
/// <summary>
/// Returns true if this relationship is empty.
/// </summary>
public bool IsEmpty => Owner == null;
/// <summary>
/// The member in this relationship.
/// </summary>
public MemberDescriptor Member { get; }
/// <summary>
/// The object owning the member.
/// </summary>
public object Owner { get; }
/// <summary>
/// Infrastructure support to make this a first class struct
/// </summary>
public override bool Equals(object obj)
{
return obj is MemberRelationship rel && rel.Owner == Owner && rel.Member == Member;
}
/// <summary>
/// Infrastructure support to make this a first class struct
/// </summary>
public override int GetHashCode()
{
if (Owner == null)
{
return base.GetHashCode();
}
return Owner.GetHashCode() ^ Member.GetHashCode();
}
/// <summary>
/// Infrastructure support to make this a first class struct
/// </summary>
public static bool operator ==(MemberRelationship left, MemberRelationship right)
{
return left.Owner == right.Owner && left.Member == right.Member;
}
/// <summary>
/// Infrastructure support to make this a first class struct
/// </summary>
public static bool operator !=(MemberRelationship left, MemberRelationship right)
{
return !(left == right);
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices
{
public class PersistentStorageTests : IDisposable
{
private const int NumThreads = 10;
private const string PersistentFolderPrefix = "PersistentStorageTests_";
private readonly Encoding _encoding = Encoding.UTF8;
private readonly IOptionService _persistentEnabledOptionService = new OptionServiceMock(new Dictionary<IOption, object>
{
{ PersistentStorageOptions.Enabled, true },
{ InternalFeatureOnOffOptions.EsentPerformanceMonitor, false }
});
private readonly string _persistentFolder;
private const string Data1 = "Hello ESENT";
private const string Data2 = "Goodbye ESENT";
public PersistentStorageTests()
{
_persistentFolder = Path.Combine(Path.GetTempPath(), PersistentFolderPrefix + Guid.NewGuid());
Directory.CreateDirectory(_persistentFolder);
int workerThreads, completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
ThreadPool.SetMinThreads(Math.Max(workerThreads, NumThreads), completionPortThreads);
}
public void Dispose()
{
if (Directory.Exists(_persistentFolder))
{
Directory.Delete(_persistentFolder, true);
}
}
private void CleanUpPersistentFolder()
{
}
[Fact]
public void PersistentService_Solution_WriteReadDifferentInstances()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadDifferentInstances1";
var streamName2 = "PersistentService_Solution_WriteReadDifferentInstances2";
using (var storage = GetStorage(solution))
{
Assert.True(storage.WriteStreamAsync(streamName1, EncodeString(Data1)).Result);
Assert.True(storage.WriteStreamAsync(streamName2, EncodeString(Data2)).Result);
}
using (var storage = GetStorage(solution))
{
Assert.Equal(Data1, ReadStringToEnd(storage.ReadStreamAsync(streamName1).Result));
Assert.Equal(Data2, ReadStringToEnd(storage.ReadStreamAsync(streamName2).Result));
}
}
[Fact]
public void PersistentService_Solution_WriteReadReopenSolution()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadReopenSolution1";
var streamName2 = "PersistentService_Solution_WriteReadReopenSolution2";
using (var storage = GetStorage(solution))
{
Assert.True(storage.WriteStreamAsync(streamName1, EncodeString(Data1)).Result);
Assert.True(storage.WriteStreamAsync(streamName2, EncodeString(Data2)).Result);
}
solution = CreateOrOpenSolution();
using (var storage = GetStorage(solution))
{
Assert.Equal(Data1, ReadStringToEnd(storage.ReadStreamAsync(streamName1).Result));
Assert.Equal(Data2, ReadStringToEnd(storage.ReadStreamAsync(streamName2).Result));
}
}
[Fact]
public void PersistentService_Solution_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadSameInstance1";
var streamName2 = "PersistentService_Solution_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
Assert.True(storage.WriteStreamAsync(streamName1, EncodeString(Data1)).Result);
Assert.True(storage.WriteStreamAsync(streamName2, EncodeString(Data2)).Result);
Assert.Equal(Data1, ReadStringToEnd(storage.ReadStreamAsync(streamName1).Result));
Assert.Equal(Data2, ReadStringToEnd(storage.ReadStreamAsync(streamName2).Result));
}
}
[Fact]
public void PersistentService_Project_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_WriteReadSameInstance1";
var streamName2 = "PersistentService_Project_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
var project = solution.Projects.Single();
Assert.True(storage.WriteStreamAsync(project, streamName1, EncodeString(Data1)).Result);
Assert.True(storage.WriteStreamAsync(project, streamName2, EncodeString(Data2)).Result);
Assert.Equal(Data1, ReadStringToEnd(storage.ReadStreamAsync(project, streamName1).Result));
Assert.Equal(Data2, ReadStringToEnd(storage.ReadStreamAsync(project, streamName2).Result));
}
}
[Fact]
public void PersistentService_Document_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_WriteReadSameInstance1";
var streamName2 = "PersistentService_Document_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
var document = solution.Projects.Single().Documents.Single();
Assert.True(storage.WriteStreamAsync(document, streamName1, EncodeString(Data1)).Result);
Assert.True(storage.WriteStreamAsync(document, streamName2, EncodeString(Data2)).Result);
Assert.Equal(Data1, ReadStringToEnd(storage.ReadStreamAsync(document, streamName1).Result));
Assert.Equal(Data2, ReadStringToEnd(storage.ReadStreamAsync(document, streamName2).Result));
}
}
[Fact]
public void PersistentService_Solution_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(storage.ReadStreamAsync(streamName1).Result));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
[Fact]
public void PersistentService_Project_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(solution.Projects.Single(), streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(storage.ReadStreamAsync(solution.Projects.Single(), streamName1).Result));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
[Fact]
public void PersistentService_Document_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(solution.Projects.Single().Documents.Single(), streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(storage.ReadStreamAsync(solution.Projects.Single().Documents.Single(), streamName1).Result));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
private void DoSimultaneousWrites(Func<string, Task> write)
{
var barrier = new Barrier(NumThreads);
var countdown = new CountdownEvent(NumThreads);
for (int i = 0; i < NumThreads; i++)
{
ThreadPool.QueueUserWorkItem(s =>
{
int id = (int)s;
barrier.SignalAndWait();
write(id + "").Wait();
countdown.Signal();
}, i);
}
countdown.Wait();
}
[Fact]
public void PersistentService_Solution_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
storage.WriteStreamAsync(streamName1, EncodeString(Data1)).Wait();
DoSimultaneousReads(() => ReadStringToEnd(storage.ReadStreamAsync(streamName1).Result), Data1);
}
}
[Fact]
public void PersistentService_Project_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
storage.WriteStreamAsync(solution.Projects.Single(), streamName1, EncodeString(Data1)).Wait();
DoSimultaneousReads(() => ReadStringToEnd(storage.ReadStreamAsync(solution.Projects.Single(), streamName1).Result), Data1);
}
}
[Fact]
public void PersistentService_Document_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
storage.WriteStreamAsync(solution.Projects.Single().Documents.Single(), streamName1, EncodeString(Data1)).Wait();
DoSimultaneousReads(() => ReadStringToEnd(storage.ReadStreamAsync(solution.Projects.Single().Documents.Single(), streamName1).Result), Data1);
}
}
private void DoSimultaneousReads(Func<string> read, string expectedValue)
{
var barrier = new Barrier(NumThreads);
var countdown = new CountdownEvent(NumThreads);
for (int i = 0; i < NumThreads; i++)
{
ThreadPool.QueueUserWorkItem(s =>
{
barrier.SignalAndWait();
Assert.Equal(expectedValue, read());
countdown.Signal();
});
}
countdown.Wait();
}
[Fact]
public void PersistentService_IdentifierSet()
{
var solution = CreateOrOpenSolution();
var newId = DocumentId.CreateNewId(solution.ProjectIds[0]);
string documentFile = Path.Combine(Path.GetDirectoryName(solution.FilePath), "IdentifierSet.cs");
File.WriteAllText(documentFile, @"
class A
{
public int Test(int i, A a)
{
return a;
}
}");
var newSolution = solution.AddDocument(DocumentInfo.Create(newId, "IdentifierSet", loader: new FileTextLoader(documentFile, Encoding.UTF8), filePath: documentFile));
using (var storage = GetStorage(newSolution))
{
var syntaxTreeStorage = storage as ISyntaxTreeInfoPersistentStorage;
Assert.NotNull(syntaxTreeStorage);
var document = newSolution.GetDocument(newId);
var version = document.GetSyntaxVersionAsync().Result;
var root = document.GetSyntaxRootAsync().Result;
Assert.True(syntaxTreeStorage.WriteIdentifierLocations(document, version, root, CancellationToken.None));
Assert.Equal(version, syntaxTreeStorage.GetIdentifierSetVersion(document));
List<int> positions = new List<int>();
Assert.True(syntaxTreeStorage.ReadIdentifierPositions(document, version, "Test", positions, CancellationToken.None));
Assert.Equal(1, positions.Count);
Assert.Equal(29, positions[0]);
}
}
private Solution CreateOrOpenSolution()
{
string solutionFile = Path.Combine(_persistentFolder, "Solution1.sln");
bool newSolution;
if (newSolution = !File.Exists(solutionFile))
{
File.WriteAllText(solutionFile, "");
}
var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), solutionFile);
var workspace = new AdhocWorkspace();
workspace.AddSolution(info);
var solution = workspace.CurrentSolution;
if (newSolution)
{
string projectFile = Path.Combine(Path.GetDirectoryName(solutionFile), "Project1.csproj");
File.WriteAllText(projectFile, "");
solution = solution.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Project1", "Project1", LanguageNames.CSharp, projectFile));
var project = solution.Projects.Single();
string documentFile = Path.Combine(Path.GetDirectoryName(projectFile), "Document1.cs");
File.WriteAllText(documentFile, "");
solution = solution.AddDocument(DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Document1", filePath: documentFile));
}
return solution;
}
private IPersistentStorage GetStorage(Solution solution)
{
var storage = new PersistentStorageService(_persistentEnabledOptionService, testing: true).GetStorage(solution);
Assert.NotEqual(PersistentStorageService.NoOpPersistentStorageInstance, storage);
return storage;
}
private Stream EncodeString(string text)
{
var bytes = _encoding.GetBytes(text);
var stream = new MemoryStream(bytes);
return stream;
}
private string ReadStringToEnd(Stream stream)
{
using (stream)
{
var bytes = new byte[stream.Length];
int count = 0;
while (count < stream.Length)
{
count = stream.Read(bytes, count, (int)stream.Length - count);
}
return _encoding.GetString(bytes);
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing
{
/// <summary>
/// Summary description for LinkOptionsControl.
/// </summary>
public class LinkOptionsEditorControl : UserControl, ILinkOptionsEditor
{
private CheckBox cbNewWindow;
private CheckBox cbEnableViewer;
private Label label1;
private TextBox txtGroupName;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
private ImageViewer _imageViewer;
public LinkOptionsEditorControl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this.cbNewWindow.Text = Res.Get(StringId.ImgSBOpenInNewWindow);
this.cbEnableViewer.Text = Res.Get(StringId.ImageViewerLabel);
this.label1.Text = Res.Get(StringId.ImageViewerGroupLabel);
txtGroupName.Enabled = false;
cbEnableViewer.CheckedChanged += delegate
{
txtGroupName.Enabled = label1.Enabled = cbEnableViewer.Checked;
if (cbEnableViewer.Checked)
cbNewWindow.Checked = false;
};
cbNewWindow.CheckedChanged += delegate
{
if (cbNewWindow.Checked)
cbEnableViewer.Checked = false;
};
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
int deltaX = label1.Right - txtGroupName.Left;
if ((txtGroupName.Width - deltaX) >= 80)
{
txtGroupName.Left += deltaX;
txtGroupName.Width -= deltaX;
}
else
{
txtGroupName.Left = label1.Left;
int deltaY = label1.Bottom - txtGroupName.Top + Convert.ToInt32(DisplayHelper.ScaleY(3));
txtGroupName.Top += deltaY;
Parent.Height += deltaY;
Height += deltaY;
}
int origCbHeight = cbEnableViewer.Height;
// WinLive 116628: The call to LayoutHelper.NaturalizeHeight causes the cbEnableViewer to change location.
// This is due to a bug in our attempt to identify if a control is aligned right. For now this is just a
// workaround until we have time to fix LayoutHelper.NaturalizeHeight (and general RTL mirroring in WinForms).
Point origCbLocation = cbEnableViewer.Location;
LayoutHelper.NaturalizeHeight(cbEnableViewer);
cbEnableViewer.Location = origCbLocation;
int deltaY2 = cbEnableViewer.Height - origCbHeight;
txtGroupName.Top += deltaY2;
label1.Top += deltaY2;
Parent.Height += deltaY2;
Height += deltaY2;
//Height = txtGroupName.Bottom + 3;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cbNewWindow = new System.Windows.Forms.CheckBox();
this.cbEnableViewer = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.txtGroupName = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// cbNewWindow
//
this.cbNewWindow.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cbNewWindow.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.cbNewWindow.Location = new System.Drawing.Point(0, 0);
this.cbNewWindow.Name = "cbNewWindow";
this.cbNewWindow.Size = new System.Drawing.Size(281, 16);
this.cbNewWindow.TabIndex = 0;
this.cbNewWindow.Text = "Open in new window";
this.cbNewWindow.CheckedChanged += new System.EventHandler(this.cbNewWindow_CheckedChanged);
//
// cbEnableViewer
//
this.cbEnableViewer.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cbEnableViewer.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.cbEnableViewer.Location = new System.Drawing.Point(0, 19);
this.cbEnableViewer.Name = "cbEnableViewer";
this.cbEnableViewer.Size = new System.Drawing.Size(269, 16);
this.cbEnableViewer.TabIndex = 1;
this.cbEnableViewer.Text = "&Enable {0}";
this.cbEnableViewer.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(23, 42);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(85, 13);
this.label1.TabIndex = 2;
this.label1.Text = "&Group (optional):";
//
// txtGroupName
//
this.txtGroupName.Location = new System.Drawing.Point(114, 39);
this.txtGroupName.Name = "txtGroupName";
this.txtGroupName.Size = new System.Drawing.Size(155, 20);
this.txtGroupName.TabIndex = 3;
this.txtGroupName.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
this.txtGroupName.MaxLength = 100;
//
// LinkOptionsEditorControl
//
this.Controls.Add(this.label1);
this.Controls.Add(this.txtGroupName);
this.Controls.Add(this.cbNewWindow);
this.Controls.Add(this.cbEnableViewer);
this.Name = "LinkOptionsEditorControl";
this.Size = new System.Drawing.Size(281, 67);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public ILinkOptions LinkOptions
{
get
{
return new LinkOptions(cbNewWindow.Checked, cbEnableViewer.Checked, txtGroupName.Text.Trim());
}
set
{
cbNewWindow.Checked = value.ShowInNewWindow;
cbEnableViewer.Checked = value.UseImageViewer;
txtGroupName.Text = value.ImageViewerGroupName ?? "";
}
}
public IEditorOptions EditorOptions
{
set
{
string imageViewer = value.DhtmlImageViewer;
if (imageViewer != null)
{
_imageViewer = DhtmlImageViewers.GetImageViewer(imageViewer);
}
int deltaY = 0;
if (_imageViewer == null)
{
cbEnableViewer.Visible = false;
label1.Visible = false;
txtGroupName.Visible = false;
deltaY = txtGroupName.Bottom - cbNewWindow.Bottom;
}
else
{
cbEnableViewer.Text = string.Format(CultureInfo.CurrentCulture, cbEnableViewer.Text, DhtmlImageViewers.GetLocalizedName(_imageViewer.Name));
if (_imageViewer.GroupSupport == ImageViewerGroupSupport.None)
{
txtGroupName.Visible = false;
label1.Visible = false;
deltaY = txtGroupName.Bottom - cbEnableViewer.Bottom;
}
}
if (deltaY != 0)
{
Height -= deltaY;
Parent.Height -= deltaY;
}
}
}
public event EventHandler LinkOptionsChanged;
protected virtual void OnLinkOptionsChanged(EventArgs e)
{
if (LinkOptionsChanged != null)
LinkOptionsChanged(this, e);
}
private void cbNewWindow_CheckedChanged(object sender, EventArgs e)
{
OnLinkOptionsChanged(EventArgs.Empty);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
#define FEATURE_MANAGED_ETW
#if !ES_BUILD_STANDALONE
#define FEATURE_ACTIVITYSAMPLING
#endif
#if ES_BUILD_STANDALONE
#define FEATURE_MANAGED_ETW_CHANNELS
// #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
#endif
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor;
#endif
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections.ObjectModel;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
using System.Collections.Generic;
using System.Text;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
using System.Collections.Generic;
using System.Text;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
public partial class EventSource
{
private byte[] providerMetadata;
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
public EventSource(
string eventSourceName)
: this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat)
{ }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
public EventSource(
string eventSourceName,
EventSourceSettings config)
: this(eventSourceName, config, null) { }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
///
/// Also specify a list of key-value pairs called traits (you must pass an even number of strings).
/// The first string is the key and the second is the value. These are not interpreted by EventSource
/// itself but may be interprated the listeners. Can be fetched with GetTrait(string).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
/// <param name="traits">A collection of key-value strings (must be an even number).</param>
public EventSource(
string eventSourceName,
EventSourceSettings config,
params string[] traits)
: this(
eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()),
eventSourceName,
config, traits)
{
if (eventSourceName == null)
{
throw new ArgumentNullException("eventSourceName");
}
Contract.EndContractBlock();
}
/// <summary>
/// Writes an event with no fields and default options.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
[SecuritySafeCritical]
public unsafe void Write(string eventName)
{
if (eventName == null)
{
throw new ArgumentNullException("eventName");
}
Contract.EndContractBlock();
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance);
}
/// <summary>
/// Writes an event with no fields.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
[SecuritySafeCritical]
public unsafe void Write(string eventName, EventSourceOptions options)
{
if (eventName == null)
{
throw new ArgumentNullException("eventName");
}
Contract.EndContractBlock();
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
T data)
{
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
EventSourceOptions options,
T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// This overload is for use with extension methods that wish to efficiently
/// forward the options or data parameter without performing an extra copy.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// This overload is meant for clients that need to manipuate the activityId
/// and related ActivityId for the event.
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="activityId">
/// The GUID of the activity associated with this event.
/// </param>
/// <param name="relatedActivityId">
/// The GUID of another activity that is related to this activity, or Guid.Empty
/// if there is no related activity. Most commonly, the Start operation of a
/// new activity specifies a parent activity as its related activity.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref Guid activityId,
ref Guid relatedActivityId,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId)
{
this.WriteImpl(
eventName,
ref options,
data,
pActivity,
relatedActivityId == Guid.Empty ? null : pRelated,
SimpleEventTypes<T>.Instance);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// This method does a quick check on whether this event is enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null) </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
[SecuritySafeCritical]
private unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
if (!this.IsEnabled())
{
return;
}
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// Attention: This API does not check whether the event is enabled or not.
/// Please use WriteMultiMerge to avoid spending CPU cycles for events that are
/// not enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null)
/// </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
[SecuritySafeCritical]
private unsafe void WriteMultiMergeInner(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventTypes.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventTypes.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags);
if (nameInfo == null)
{
return;
}
identity = nameInfo.identity;
EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#if (!ES_BUILD_PCL && !PROJECTN)
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
var info = eventTypes.typeInfos[i];
info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(values[i]));
}
this.WriteEventRaw(
eventName,
ref descriptor,
activityID,
childActivityID,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
}
finally
{
this.WriteCleanup(pins, pinCount);
}
}
}
/// <summary>
/// Writes an extended event, where the values of the event have already
/// been serialized in "data".
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null)
/// </param>
/// <param name="data">
/// The previously serialized values to include in the event. Must not be null.
/// The number and types of the values must match the number and types of the
/// fields described by the eventTypes parameter.
/// </param>
[SecuritySafeCritical]
internal unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
EventData* data)
{
if (!this.IsEnabled())
{
return;
}
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
// We make a descriptor for each EventData, and because we morph strings to counted strings
// we may have 2 for each arg, so we allocate enough for this.
var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
int numDescrs = 3;
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
// Until M3, we need to morph strings to a counted representation
// When TDH supports null terminated strings, we can remove this.
if (eventTypes.typeInfos[i].DataType == typeof(string))
{
// Write out the size of the string
descriptors[numDescrs].m_Ptr = (long)&descriptors[numDescrs + 1].m_Size;
descriptors[numDescrs].m_Size = 2;
numDescrs++;
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator
numDescrs++;
}
else
{
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size;
// old conventions for bool is 4 bytes, but meta-data assumes 1.
if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool))
descriptors[numDescrs].m_Size = 1;
numDescrs++;
}
}
this.WriteEventRaw(
eventName,
ref descriptor,
activityID,
childActivityID,
numDescrs,
(IntPtr)descriptors);
}
}
}
[SecuritySafeCritical]
private unsafe void WriteImpl(
string eventName,
ref EventSourceOptions options,
object data,
Guid* pActivityId,
Guid* pRelatedActivityId,
TraceLoggingEventTypes eventTypes)
{
try
{
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName);
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#if (!ES_BUILD_PCL && !PROJECTN)
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
EventOpcode opcode = (EventOpcode)descriptor.Opcode;
Guid activityId = Guid.Empty;
Guid relatedActivityId = Guid.Empty;
if (pActivityId == null && pRelatedActivityId == null &&
((options.ActivityOptions & EventActivityOptions.Disable) == 0))
{
if (opcode == EventOpcode.Start)
{
m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions);
}
else if (opcode == EventOpcode.Stop)
{
m_activityTracker.OnStop(m_name, eventName, 0, ref activityId);
}
if (activityId != Guid.Empty)
pActivityId = &activityId;
if (relatedActivityId != Guid.Empty)
pRelatedActivityId = &relatedActivityId;
}
try
{
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
var info = eventTypes.typeInfos[0];
info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(data));
this.WriteEventRaw(
eventName,
ref descriptor,
pActivityId,
pRelatedActivityId,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
// TODO enable filtering for listeners.
if (m_Dispatchers != null)
{
var eventData = (EventPayload)(eventTypes.typeInfos[0].GetData(data));
WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData);
}
}
catch (Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(eventName, ex);
}
finally
{
this.WriteCleanup(pins, pinCount);
}
}
}
}
catch (Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(eventName, ex);
}
}
[SecurityCritical]
private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload)
{
EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
eventCallbackArgs.EventName = eventName;
eventCallbackArgs.m_level = (EventLevel) eventDescriptor.Level;
eventCallbackArgs.m_keywords = (EventKeywords) eventDescriptor.Keywords;
eventCallbackArgs.m_opcode = (EventOpcode) eventDescriptor.Opcode;
eventCallbackArgs.m_tags = tags;
// Self described events do not have an id attached. We mark it internally with -1.
eventCallbackArgs.EventId = -1;
if (pActivityId != null)
eventCallbackArgs.RelatedActivityId = *pActivityId;
if (payload != null)
{
eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values);
eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys);
}
DispatchToAllListeners(-1, pActivityId, eventCallbackArgs);
}
#if (!ES_BUILD_PCL && !PROJECTN)
[System.Runtime.ConstrainedExecution.ReliabilityContract(
System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState,
System.Runtime.ConstrainedExecution.Cer.Success)]
#endif
[SecurityCritical]
[NonEvent]
private unsafe void WriteCleanup(GCHandle* pPins, int cPins)
{
DataCollector.ThreadInstance.Disable();
for (int i = 0; i != cPins; i++)
{
if (IntPtr.Zero != (IntPtr)pPins[i])
{
pPins[i].Free();
}
}
}
private void InitializeProviderMetadata()
{
if (m_traits != null)
{
List<byte> traitMetaData = new List<byte>(100);
for (int i = 0; i < m_traits.Length - 1; i += 2)
{
if (m_traits[i].StartsWith("ETW_"))
{
string etwTrait = m_traits[i].Substring(4);
byte traitNum;
if (!byte.TryParse(etwTrait, out traitNum))
{
if (etwTrait == "GROUP")
{
traitNum = 1;
}
else
{
throw new ArgumentException(Resources.GetResourceString("UnknownEtwTrait", etwTrait), "traits");
}
}
string value = m_traits[i + 1];
int lenPos = traitMetaData.Count;
traitMetaData.Add(0); // Emit size (to be filled in later)
traitMetaData.Add(0);
traitMetaData.Add(traitNum); // Emit Trait number
var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above.
traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size
traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8));
}
}
providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0);
int startPos = providerMetadata.Length - traitMetaData.Count;
foreach (var b in traitMetaData)
providerMetadata[startPos++] = b;
}
else
providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0);
}
private static int AddValueToMetaData(List<byte> metaData, string value)
{
if (value.Length == 0)
return 0;
int startPos = metaData.Count;
char firstChar = value[0];
if (firstChar == '@')
metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1)));
else if (firstChar == '{')
metaData.AddRange(new Guid(value).ToByteArray());
else if (firstChar == '#')
{
for (int i = 1; i < value.Length; i++)
{
if (value[i] != ' ') // Skip spaces between bytes.
{
if (!(i + 1 < value.Length))
{
throw new ArgumentException(Resources.GetResourceString("EvenHexDigits"), "traits");
}
metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1])));
i++;
}
}
}
else if ('A' <= firstChar || ' ' == firstChar) // Is it alphabetic or space (excludes digits and most punctuation).
{
metaData.AddRange(Encoding.UTF8.GetBytes(value));
}
else
{
throw new ArgumentException(Resources.GetResourceString("IllegalValue", value), "traits");
}
return metaData.Count - startPos;
}
/// <summary>
/// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception.
/// </summary>
private static int HexDigit(char c)
{
if ('0' <= c && c <= '9')
{
return (c - '0');
}
if ('a' <= c)
{
c = unchecked((char)(c - ('a' - 'A'))); // Convert to lower case
}
if ('A' <= c && c <= 'F')
{
return (c - 'A' + 10);
}
throw new ArgumentException(Resources.GetResourceString("BadHexDigit", c), "traits");
}
private NameInfo UpdateDescriptor(
string name,
TraceLoggingEventTypes eventInfo,
ref EventSourceOptions options,
out EventDescriptor descriptor)
{
NameInfo nameInfo = null;
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventInfo.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventInfo.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventInfo.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventInfo.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags);
identity = nameInfo.identity;
}
descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
return nameInfo;
}
}
}
| |
// 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.
//
//(((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//permutations for (((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//(((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))))
//((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))
//(a+(b*((c*c)-(c+d))))
//((b*((c*c)-(c+d)))+a)
//a
//(b*((c*c)-(c+d)))
//(((c*c)-(c+d))*b)
//b
//((c*c)-(c+d))
//(c*c)
//(c*c)
//c
//c
//(c*c)
//(c*c)
//(c+d)
//(d+c)
//c
//d
//(d+c)
//(c+d)
//(c*c)
//((c*c)-(c+d))
//(((c*c)-(c+d))*b)
//(b*((c*c)-(c+d)))
//((b*((c*c)-(c+d)))+a)
//(a+(b*((c*c)-(c+d))))
//(((a*a)+a)+(a*b))
//((a*b)+((a*a)+a))
//((a*a)+a)
//(a+(a*a))
//(a*a)
//(a*a)
//a
//a
//(a*a)
//(a*a)
//a
//(a+(a*a))
//((a*a)+a)
//(a*b)
//(b*a)
//a
//b
//(b*a)
//(a*b)
//((a*a)+(a+(a*b)))
//(a+((a*a)+(a*b)))
//(a+(a*b))
//((a*b)+a)
//a
//(a*b)
//(b*a)
//a
//b
//(b*a)
//(a*b)
//((a*b)+a)
//(a+(a*b))
//((a*a)+(a*b))
//((a*b)+(a*a))
//(a*a)
//(a*a)
//a
//a
//(a*a)
//(a*a)
//(a*b)
//(b*a)
//a
//b
//(b*a)
//(a*b)
//((a*b)+(a*a))
//((a*a)+(a*b))
//((a*b)+((a*a)+a))
//(((a*a)+a)+(a*b))
//(a+(b*((c*c)-(c+d))))
//((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))
//(((abc+c)-(a-(ad*a)))+r)
//(r+((abc+c)-(a-(ad*a))))
//((abc+c)-(a-(ad*a)))
//(abc+c)
//(c+abc)
//abc
//c
//(c+abc)
//(abc+c)
//(a-(ad*a))
//a
//(ad*a)
//(a*ad)
//ad
//a
//(a*ad)
//(ad*a)
//a
//(a-(ad*a))
//(abc+c)
//((abc+c)-(a-(ad*a)))
//r
//(r+((abc+c)-(a-(ad*a))))
//(((abc+c)-(a-(ad*a)))+r)
//((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))))
//(((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
namespace CseTest
{
using System;
public class Test_Main
{
static int Main()
{
int ret = 100;
int d = return_int(false, -36);
int ad = return_int(false, 24);
int r = return_int(false, -9);
int abc = return_int(false, 47);
int b = return_int(false, -41);
int c = return_int(false, -25);
int a = return_int(false, -34);
int v;
v = (((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))) * (((abc + c) - (a - (ad * a))) + r));
if (v != 23589844)
{
Console.WriteLine("test0: for (((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((((abc + c) - (a - (ad * a))) + r) * ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))));
if (v != 23589844)
{
Console.WriteLine("test1: for ((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))) failed actual value {0} ", v);
ret = ret + 1;
}
a = return_int(false, 1);
v = ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b)));
if (v != -28086)
{
Console.WriteLine("test2: for ((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (b * ((c * c) - (c + d))));
if (v != -28125)
{
Console.WriteLine("test3: for (a+(b*((c*c)-(c+d)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b * ((c * c) - (c + d))) + a);
if (v != -28125)
{
Console.WriteLine("test4: for ((b*((c*c)-(c+d)))+a) failed actual value {0} ", v);
ret = ret + 1;
}
r = return_int(false, 20);
ad = return_int(false, 23);
v = (b * ((c * c) - (c + d)));
if (v != -28126)
{
Console.WriteLine("test5: for (b*((c*c)-(c+d))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((c * c) - (c + d)) * b);
if (v != -28126)
{
Console.WriteLine("test6: for (((c*c)-(c+d))*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((c * c) - (c + d));
if (v != 686)
{
Console.WriteLine("test7: for ((c*c)-(c+d)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 625)
{
Console.WriteLine("test8: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 625)
{
Console.WriteLine("test9: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 625)
{
Console.WriteLine("test10: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 625)
{
Console.WriteLine("test11: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + d);
if (v != -61)
{
Console.WriteLine("test12: for (c+d) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d + c);
if (v != -61)
{
Console.WriteLine("test13: for (d+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d + c);
if (v != -61)
{
Console.WriteLine("test14: for (d+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + d);
if (v != -61)
{
Console.WriteLine("test15: for (c+d) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 625)
{
Console.WriteLine("test16: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((c * c) - (c + d));
if (v != 686)
{
Console.WriteLine("test17: for ((c*c)-(c+d)) failed actual value {0} ", v);
ret = ret + 1;
}
ad = return_int(false, 10);
v = (((c * c) - (c + d)) * b);
if (v != -28126)
{
Console.WriteLine("test18: for (((c*c)-(c+d))*b) failed actual value {0} ", v);
ret = ret + 1;
}
d = return_int(false, 2);
v = (b * ((c * c) - (c + d)));
if (v != -26568)
{
Console.WriteLine("test19: for (b*((c*c)-(c+d))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b * ((c * c) - (c + d))) + a);
if (v != -26567)
{
Console.WriteLine("test20: for ((b*((c*c)-(c+d)))+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (b * ((c * c) - (c + d))));
if (v != -26567)
{
Console.WriteLine("test21: for (a+(b*((c*c)-(c+d)))) failed actual value {0} ", v);
ret = ret + 1;
}
a = return_int(false, 47);
v = (((a * a) + a) + (a * b));
if (v != 329)
{
Console.WriteLine("test22: for (((a*a)+a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + ((a * a) + a));
if (v != 329)
{
Console.WriteLine("test23: for ((a*b)+((a*a)+a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + a);
if (v != 2256)
{
Console.WriteLine("test24: for ((a*a)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * a));
if (v != 2256)
{
Console.WriteLine("test25: for (a+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 2209)
{
Console.WriteLine("test26: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 2209)
{
Console.WriteLine("test27: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 2209)
{
Console.WriteLine("test28: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 2209)
{
Console.WriteLine("test29: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * a));
if (v != 2256)
{
Console.WriteLine("test30: for (a+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + a);
if (v != 2256)
{
Console.WriteLine("test31: for ((a*a)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != -1927)
{
Console.WriteLine("test32: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != -1927)
{
Console.WriteLine("test33: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != -1927)
{
Console.WriteLine("test34: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != -1927)
{
Console.WriteLine("test35: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + (a + (a * b)));
if (v != 329)
{
Console.WriteLine("test36: for ((a*a)+(a+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + ((a * a) + (a * b)));
if (v != 329)
{
Console.WriteLine("test37: for (a+((a*a)+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * b));
if (v != -1880)
{
Console.WriteLine("test38: for (a+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + a);
if (v != -1880)
{
Console.WriteLine("test39: for ((a*b)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != -1927)
{
Console.WriteLine("test40: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != -1927)
{
Console.WriteLine("test41: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != -1927)
{
Console.WriteLine("test42: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != -1927)
{
Console.WriteLine("test43: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + a);
if (v != -1880)
{
Console.WriteLine("test44: for ((a*b)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * b));
if (v != -1880)
{
Console.WriteLine("test45: for (a+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + (a * b));
if (v != 282)
{
Console.WriteLine("test46: for ((a*a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + (a * a));
if (v != 282)
{
Console.WriteLine("test47: for ((a*b)+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 2209)
{
Console.WriteLine("test48: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 2209)
{
Console.WriteLine("test49: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 2209)
{
Console.WriteLine("test50: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 2209)
{
Console.WriteLine("test51: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != -1927)
{
Console.WriteLine("test52: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != -1927)
{
Console.WriteLine("test53: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
b = return_int(false, 39);
v = (b * a);
if (v != 1833)
{
Console.WriteLine("test54: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 1833)
{
Console.WriteLine("test55: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + (a * a));
if (v != 4042)
{
Console.WriteLine("test56: for ((a*b)+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + (a * b));
if (v != 4042)
{
Console.WriteLine("test57: for ((a*a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + ((a * a) + a));
if (v != 4089)
{
Console.WriteLine("test58: for ((a*b)+((a*a)+a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((a * a) + a) + (a * b));
if (v != 4089)
{
Console.WriteLine("test59: for (((a*a)+a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
b = return_int(false, -15);
v = (a + (b * ((c * c) - (c + d))));
if (v != -9673)
{
Console.WriteLine("test60: for (a+(b*((c*c)-(c+d)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b)));
if (v != -11224)
{
Console.WriteLine("test61: for ((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((abc + c) - (a - (ad * a))) + r);
if (v != 465)
{
Console.WriteLine("test62: for (((abc+c)-(a-(ad*a)))+r) failed actual value {0} ", v);
ret = ret + 1;
}
v = (r + ((abc + c) - (a - (ad * a))));
if (v != 465)
{
Console.WriteLine("test63: for (r+((abc+c)-(a-(ad*a)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((abc + c) - (a - (ad * a)));
if (v != 445)
{
Console.WriteLine("test64: for ((abc+c)-(a-(ad*a))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (abc + c);
if (v != 22)
{
Console.WriteLine("test65: for (abc+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + abc);
if (v != 22)
{
Console.WriteLine("test66: for (c+abc) failed actual value {0} ", v);
ret = ret + 1;
}
d = return_int(false, 31);
v = (c + abc);
if (v != 22)
{
Console.WriteLine("test67: for (c+abc) failed actual value {0} ", v);
ret = ret + 1;
}
v = (abc + c);
if (v != 22)
{
Console.WriteLine("test68: for (abc+c) failed actual value {0} ", v);
ret = ret + 1;
}
ad = return_int(false, 9);
v = (a - (ad * a));
if (v != -376)
{
Console.WriteLine("test69: for (a-(ad*a)) failed actual value {0} ", v);
ret = ret + 1;
}
r = return_int(false, -16);
v = (ad * a);
if (v != 423)
{
Console.WriteLine("test70: for (ad*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * ad);
if (v != 423)
{
Console.WriteLine("test71: for (a*ad) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * ad);
if (v != 423)
{
Console.WriteLine("test72: for (a*ad) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ad * a);
if (v != 423)
{
Console.WriteLine("test73: for (ad*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a - (ad * a));
if (v != -376)
{
Console.WriteLine("test74: for (a-(ad*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (abc + c);
if (v != 22)
{
Console.WriteLine("test75: for (abc+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((abc + c) - (a - (ad * a)));
if (v != 398)
{
Console.WriteLine("test76: for ((abc+c)-(a-(ad*a))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (r + ((abc + c) - (a - (ad * a))));
if (v != 382)
{
Console.WriteLine("test77: for (r+((abc+c)-(a-(ad*a)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((abc + c) - (a - (ad * a))) + r);
if (v != 382)
{
Console.WriteLine("test78: for (((abc+c)-(a-(ad*a)))+r) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((((abc + c) - (a - (ad * a))) + r) * ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))));
if (v != -4121398)
{
Console.WriteLine("test79: for ((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))) * (((abc + c) - (a - (ad * a))) + r));
if (v != -4121398)
{
Console.WriteLine("test80: for (((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r)) failed actual value {0} ", v);
ret = ret + 1;
}
return ret;
}
private static int return_int(bool verbose, int input)
{
int ans;
try
{
ans = input;
}
finally
{
if (verbose)
{
Console.WriteLine("returning : ans");
}
}
return ans;
}
}
}
| |
//! \file ArcPCG.cs
//! \date 2018 Jan 20
//! \brief Groover CG archive.
//
// Copyright (C) 2018 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Media;
using GameRes.Utility;
namespace GameRes.Formats.Groover
{
[Export(typeof(ArchiveFormat))]
public class DatOpener : ArchiveFormat
{
public override string Tag { get { return "DAT/PCG"; } }
public override string Description { get { return "Groover resource archive"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
static readonly Regex IndexNameRe = new Regex (@"^((.+)0\d)\.dat$", RegexOptions.IgnoreCase);
public override ArcFile TryOpen (ArcView file)
{
if (!file.Name.HasExtension (".dat"))
return null;
var arc_name = Path.GetFileName (file.Name);
var match = IndexNameRe.Match (arc_name);
if (!match.Success)
return null;
var base_name = match.Groups[2].Value;
base_name = VFS.ChangeFileName (file.Name, base_name);
var index_name = base_name + ".pcg";
if (!VFS.FileExists (index_name))
{
index_name = base_name + ".spf";
if (!VFS.FileExists (index_name))
return null;
}
arc_name = match.Groups[1].Value;
using (var index = VFS.OpenView (index_name))
{
int parts_count = index.View.ReadInt32 (0);
int count = index.View.ReadInt32 (4);
if (parts_count > 10 || !IsSaneCount (count))
return null;
int entry_size = (int)(index.MaxOffset - 0x198) / count;
if (entry_size < 0x30)
return null;
int first_index = -1, last_index = -1;
for (int i = 0; i < parts_count; ++i)
{
int name_pos = 8 + i * 0x20;
var name = index.View.ReadString (name_pos, 0x20);
if (name == arc_name)
{
int first_index_pos = 0x148 + i * 4;
int last_index_pos = 0x170 + i * 4;
first_index = index.View.ReadInt32 (first_index_pos);
last_index = index.View.ReadInt32 (last_index_pos);
break;
}
}
if (first_index < 0 || first_index >= last_index || last_index > count)
return null;
uint name_size = entry_size >= 0x48 ? 0x40u : 0x20u;
int index_offset = 0x198 + entry_size * first_index;
var dir = new List<Entry> (last_index-first_index);
for (int i = first_index; i < last_index; ++i)
{
var name = index.View.ReadString (index_offset, name_size);
var entry = FormatCatalog.Instance.Create<Entry> (name);
entry.Size = index.View.ReadUInt32 (index_offset+name_size);
entry.Offset = index.View.ReadUInt32 (index_offset+name_size+4);
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
index_offset += entry_size;
}
return new ArcFile (file, this, dir);
}
}
public override IImageDecoder OpenImage (ArcFile arc, Entry entry)
{
var input = arc.File.CreateStream (entry.Offset, entry.Size);
try
{
if (0x504D434E == input.Signature) // 'NCMP'
return new NcmpReader (input);
if (0x424352 == input.Signature) // 'RCB'
return new RcbReader (input);
return new ImageFormatDecoder (input);
}
catch
{
input.Dispose();
throw;
}
}
}
internal abstract class PcgReaderBase : IImageDecoder
{
protected IBinaryStream m_input;
private ImageData m_image;
protected int m_unpacked_size;
protected int m_packed_size;
public Stream Source { get { m_input.Position = 0; return m_input.AsStream; } }
public ImageFormat SourceFormat { get { return null; } }
public ImageMetaData Info { get; protected set; }
public PixelFormat Format { get { return PixelFormats.Bgr24; } }
public ImageData Image {
get {
if (null == m_image)
{
var pixels = Unpack();
m_image = ImageData.Create (Info, Format, null, pixels);
}
return m_image;
}
}
protected PcgReaderBase (IBinaryStream input)
{
m_input = input;
m_input.Position = 8;
uint w = m_input.ReadUInt32();
uint h = m_input.ReadUInt32();
m_unpacked_size = m_input.ReadInt32();
m_packed_size = m_input.ReadInt32();
Info = new ImageMetaData { Width = w, Height = h, BPP = 24 };
}
protected abstract byte[] Unpack ();
#region IDisposable Members
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
bool m_disposed = false;
protected virtual void Dispose (bool disposing)
{
if (!m_disposed)
{
m_input.Dispose();
m_disposed = true;
}
}
#endregion
}
internal class NcmpReader : PcgReaderBase
{
public NcmpReader (IBinaryStream input) : base (input) { }
protected override byte[] Unpack ()
{
m_input.Position = 0x18;
return m_input.ReadBytes (m_unpacked_size);
}
}
internal class RcbReader : PcgReaderBase
{
public RcbReader (IBinaryStream input) : base (input) { }
protected override byte[] Unpack ()
{
m_input.Position = 0x18;
var output = new byte[m_unpacked_size];
int dst = 0;
for (int src = 0; src < m_packed_size && dst < m_unpacked_size; ++src)
{
m_input.Read (output, dst, 3);
int count = m_input.ReadUInt8();
if (count > 0)
{
if (count > 1)
Binary.CopyOverlapped (output, dst, dst+3, (count-1) * 3);
dst += count * 3;
}
}
return output;
}
}
}
| |
using Skahal.Infrastructure.Framework.Domain;
using System.Collections.Generic;
using System;
using HelperSharp;
using System.Linq.Expressions;
namespace Skahal.Infrastructure.Framework.Repositories
{
/// <summary>
/// A base class for repositories.
/// </summary>
public abstract class RepositoryBase<TEntity>
: IRepository<TEntity>, IUnitOfWorkRepository where TEntity : IAggregateRoot
{
#region Fields
private IUnitOfWork m_unitOfWork;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Skahal.Infrastructure.Framework.Repositories.RepositoryBase<TEntity, TKey>"/> class.
/// </summary>
protected RepositoryBase()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Skahal.Infrastructure.Framework.Repositories.RepositoryBase<TEntity, TKey>"/> class.
/// </summary>
/// <param name="unitOfWork">Unit of work.</param>
protected RepositoryBase(IUnitOfWork unitOfWork)
{
m_unitOfWork = unitOfWork;
}
#endregion
#region IRepository<T> Members
/// <summary>
/// Finds an entity by the key.
/// </summary>
/// <returns>The entity.</returns>
/// <param name="key">Key.</param>
public abstract TEntity FindBy(object key);
/// <summary>
/// Finds all entities that matches the filter.
/// </summary>
/// <returns>The found entities.</returns>
/// <param name="offset">Offset.</param>
/// <param name="limit">Limit.</param>
/// <param name="filter">Filter.</param>
public abstract IEnumerable<TEntity> FindAll(int offset, int limit, Expression<Func<TEntity, bool>> filter);
/// <summary>
/// Finds all entities that matches the filter in a ascending order.
/// </summary>
/// <returns>The found entities.</returns>
/// <param name="offset">The offset to start the result.</param>
/// <param name="limit">The result count limit.</param>
/// <param name="filter">The entities filter.</param>
/// <param name="orderBy">The order.</param>
public abstract IEnumerable<TEntity> FindAllAscending<TKey>(int offset, int limit, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, TKey>> orderBy);
/// <summary>
/// Finds all entities that matches the filter in a descending order.
/// </summary>
/// <returns>The found entities.</returns>
/// <param name="offset">The offset to start the result.</param>
/// <param name="limit">The result count limit.</param>
/// <param name="filter">The entities filter.</param>
/// <param name="orderBy">The order.</param>
public abstract IEnumerable<TEntity> FindAllDescending<TKey>(int offset, int limit, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, TKey>> orderBy);
/// <summary>
/// Counts all entities that matches the filter.
/// </summary>
/// <returns>The found entities.</returns>
/// <param name="filter">Filter.</param>
public abstract long CountAll(Expression<Func<TEntity, bool>> filter);
/// <summary>
/// Sets the unit of work.
/// </summary>
/// <param name="unitOfWork">Unit of work.</param>
public virtual void SetUnitOfWork(IUnitOfWork unitOfWork)
{
m_unitOfWork = unitOfWork;
}
/// <summary>
/// Add the specified item.
/// </summary>
/// <param name="item">Item.</param>
public void Add(TEntity item)
{
ExceptionHelper.ThrowIfNull ("item", item);
ValidateUnitOfWork ();
m_unitOfWork.RegisterAdded(item, this);
}
/// <summary>
/// Remove the specified entity.
/// </summary>
/// <param name="item">The entity.</param>
public void Remove(TEntity item)
{
ExceptionHelper.ThrowIfNull ("item", item);
ValidateUnitOfWork ();
m_unitOfWork.RegisterRemoved(item, this);
}
/// <summary>
/// Gets or sets the <see cref="Skahal.Infrastructure.Framework.Repositories.RepositoryBase<TEntity, TKey>"/> with the specified key.
/// </summary>
/// <param name="key">Key.</param>
public TEntity this[object key]
{
get
{
return FindBy(key);
}
set
{
if (FindBy(key) == null)
{
Add(value);
}
else
{
ValidateUnitOfWork ();
m_unitOfWork.RegisterChanged(value, this);
}
}
}
#endregion
#region IUnitOfWorkRepository Members
/// <summary>
/// Persists the new item.
/// </summary>
/// <param name="item">Item.</param>
public virtual void PersistNewItem(IAggregateRoot item)
{
ExceptionHelper.ThrowIfNull("item", item);
PersistNewItem((TEntity)item);
}
/// <summary>
/// Persists the updated item.
/// </summary>
/// <param name="item">Item.</param>
public virtual void PersistUpdatedItem(IAggregateRoot item)
{
ExceptionHelper.ThrowIfNull("item", item);
PersistUpdatedItem((TEntity)item);
}
/// <summary>
/// Persists the deleted item.
/// </summary>
/// <param name="item">Item.</param>
public virtual void PersistDeletedItem(IAggregateRoot item)
{
ExceptionHelper.ThrowIfNull("item", item);
PersistDeletedItem((TEntity)item);
}
#endregion
#region Properties
/// <summary>
/// Gets the unit of work.
/// </summary>
/// <value>The unit of work.</value>
protected IUnitOfWork UnitOfWork
{
get { return m_unitOfWork; }
}
#endregion
#region Methods
/// <summary>
/// Persists the new item.
/// </summary>
/// <param name="item">Item.</param>
protected abstract void PersistNewItem(TEntity item);
/// <summary>
/// Persists the updated item.
/// </summary>
/// <param name="item">Item.</param>
protected abstract void PersistUpdatedItem(TEntity item);
/// <summary>
/// Persists the deleted item.
/// </summary>
/// <param name="item">Item.</param>
protected abstract void PersistDeletedItem(TEntity item);
#endregion
#region Helpers
/// <summary>
/// Validates the unit of work.
/// </summary>
/// <exception cref="System.InvalidOperationException">There is no UnitOfWork configured for the repository '{0}'..With(GetType().Name)</exception>
protected void ValidateUnitOfWork()
{
if (m_unitOfWork == null) {
throw new InvalidOperationException ("There is no UnitOfWork configured for the repository '{0}'.".With(GetType().Name));
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using Xunit;
using Xunit.Abstractions;
namespace System.Linq.Tests
{
public class SkipTests : EnumerableTests
{
private static IEnumerable<T> GuaranteeNotIList<T>(IEnumerable<T> source)
{
foreach (T element in source)
yield return element;
}
[Fact]
public void SkipSome()
{
Assert.Equal(Enumerable.Range(10, 10), NumberRangeGuaranteedNotCollectionType(0, 20).Skip(10));
}
[Fact]
public void SkipSomeIList()
{
Assert.Equal(Enumerable.Range(10, 10), NumberRangeGuaranteedNotCollectionType(0, 20).ToList().Skip(10));
}
[Fact]
public void RunOnce()
{
Assert.Equal(Enumerable.Range(10, 10), Enumerable.Range(0, 20).RunOnce().Skip(10));
Assert.Equal(Enumerable.Range(10, 10), Enumerable.Range(0, 20).ToList().RunOnce().Skip(10));
}
[Fact]
public void SkipNone()
{
Assert.Equal(Enumerable.Range(0, 20), NumberRangeGuaranteedNotCollectionType(0, 20).Skip(0));
}
[Fact]
public void SkipNoneIList()
{
Assert.Equal(Enumerable.Range(0, 20), NumberRangeGuaranteedNotCollectionType(0, 20).ToList().Skip(0));
}
[Fact]
public void SkipExcessive()
{
Assert.Equal(Enumerable.Empty<int>(), NumberRangeGuaranteedNotCollectionType(0, 20).Skip(42));
}
[Fact]
public void SkipExcessiveIList()
{
Assert.Equal(Enumerable.Empty<int>(), NumberRangeGuaranteedNotCollectionType(0, 20).ToList().Skip(42));
}
[Fact]
public void SkipAllExactly()
{
Assert.False(NumberRangeGuaranteedNotCollectionType(0, 20).Skip(20).Any());
}
[Fact]
public void SkipAllExactlyIList()
{
Assert.False(NumberRangeGuaranteedNotCollectionType(0, 20).Skip(20).ToList().Any());
}
[Fact]
public void SkipThrowsOnNull()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<DateTime>)null).Skip(3));
}
[Fact]
public void SkipThrowsOnNullIList()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((List<DateTime>)null).Skip(3));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IList<DateTime>)null).Skip(3));
}
[Fact]
public void SkipOnEmpty()
{
Assert.Equal(Enumerable.Empty<int>(), GuaranteeNotIList(Enumerable.Empty<int>()).Skip(0));
Assert.Equal(Enumerable.Empty<string>(), GuaranteeNotIList(Enumerable.Empty<string>()).Skip(-1));
Assert.Equal(Enumerable.Empty<double>(), GuaranteeNotIList(Enumerable.Empty<double>()).Skip(1));
}
[Fact]
public void SkipOnEmptyIList()
{
// Enumerable.Empty does return an IList, but not guaranteed as such
// by the spec.
Assert.Equal(Enumerable.Empty<int>(), Enumerable.Empty<int>().ToList().Skip(0));
Assert.Equal(Enumerable.Empty<string>(), Enumerable.Empty<string>().ToList().Skip(-1));
Assert.Equal(Enumerable.Empty<double>(), Enumerable.Empty<double>().ToList().Skip(1));
}
[Fact]
public void SkipNegative()
{
Assert.Equal(Enumerable.Range(0, 20), NumberRangeGuaranteedNotCollectionType(0, 20).Skip(-42));
}
[Fact]
public void SkipNegativeIList()
{
Assert.Equal(Enumerable.Range(0, 20), NumberRangeGuaranteedNotCollectionType(0, 20).ToList().Skip(-42));
}
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = GuaranteeNotIList(from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x);
Assert.Equal(q.Skip(0), q.Skip(0));
}
[Fact]
public void SameResultsRepeatCallsIntQueryIList()
{
var q = (from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x).ToList();
Assert.Equal(q.Skip(0), q.Skip(0));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = GuaranteeNotIList(from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x);
Assert.Equal(q.Skip(0), q.Skip(0));
}
[Fact]
public void SameResultsRepeatCallsStringQueryIList()
{
var q = (from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x).ToList();
Assert.Equal(q.Skip(0), q.Skip(0));
}
[Fact]
public void SkipOne()
{
int?[] source = { 3, 100, 4, null, 10 };
int?[] expected = { 100, 4, null, 10 };
Assert.Equal(expected, source.Skip(1));
}
[Fact]
public void SkipOneNotIList()
{
int?[] source = { 3, 100, 4, null, 10 };
int?[] expected = { 100, 4, null, 10 };
Assert.Equal(expected, GuaranteeNotIList(source).Skip(1));
}
[Fact]
public void SkipAllButOne()
{
int?[] source = { 3, 100, null, 4, 10 };
int?[] expected = { 10 };
Assert.Equal(expected, source.Skip(source.Length - 1));
}
[Fact]
public void SkipAllButOneNotIList()
{
int?[] source = { 3, 100, null, 4, 10 };
int?[] expected = { 10 };
Assert.Equal(expected, GuaranteeNotIList(source.Skip(source.Length - 1)));
}
[Fact]
public void SkipOneMoreThanAll()
{
int[] source = { 3, 100, 4, 10 };
Assert.Empty(source.Skip(source.Length + 1));
}
[Fact]
public void SkipOneMoreThanAllNotIList()
{
int[] source = { 3, 100, 4, 10 };
Assert.Empty(GuaranteeNotIList(source).Skip(source.Length + 1));
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Skip(2);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateIList()
{
var iterator = (new[] { 0, 1, 2 }).Skip(2);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void Count()
{
Assert.Equal(2, NumberRangeGuaranteedNotCollectionType(0, 3).Skip(1).Count());
Assert.Equal(2, new[] { 1, 2, 3 }.Skip(1).Count());
}
[Fact]
public void FollowWithTake()
{
var source = new[] { 5, 6, 7, 8 };
var expected = new[] { 6, 7 };
Assert.Equal(expected, source.Skip(1).Take(2));
}
[Fact]
public void FollowWithTakeNotIList()
{
var source = NumberRangeGuaranteedNotCollectionType(5, 4);
var expected = new[] { 6, 7 };
Assert.Equal(expected, source.Skip(1).Take(2));
}
[Fact]
public void FollowWithTakeThenMassiveTake()
{
var source = new[] { 5, 6, 7, 8 };
var expected = new[] { 7 };
Assert.Equal(expected, source.Skip(2).Take(1).Take(int.MaxValue));
}
[Fact]
public void FollowWithTakeThenMassiveTakeNotIList()
{
var source = NumberRangeGuaranteedNotCollectionType(5, 4);
var expected = new[] { 7 };
Assert.Equal(expected, source.Skip(2).Take(1).Take(int.MaxValue));
}
[Fact]
public void FollowWithSkip()
{
var source = new[] { 1, 2, 3, 4, 5, 6 };
var expected = new[] { 4, 5, 6 };
Assert.Equal(expected, source.Skip(1).Skip(2).Skip(-4));
}
[Fact]
public void FollowWithSkipNotIList()
{
var source = NumberRangeGuaranteedNotCollectionType(1, 6);
var expected = new[] { 4, 5, 6 };
Assert.Equal(expected, source.Skip(1).Skip(2).Skip(-4));
}
[Fact]
public void ElementAt()
{
var source = new[] { 1, 2, 3, 4, 5, 6 };
var remaining = source.Skip(2);
Assert.Equal(3, remaining.ElementAt(0));
Assert.Equal(4, remaining.ElementAt(1));
Assert.Equal(6, remaining.ElementAt(3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => remaining.ElementAt(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => remaining.ElementAt(4));
}
[Fact]
public void ElementAtNotIList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5, 6 });
var remaining = source.Skip(2);
Assert.Equal(3, remaining.ElementAt(0));
Assert.Equal(4, remaining.ElementAt(1));
Assert.Equal(6, remaining.ElementAt(3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => remaining.ElementAt(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => remaining.ElementAt(4));
}
[Fact]
public void ElementAtOrDefault()
{
var source = new[] { 1, 2, 3, 4, 5, 6 };
var remaining = source.Skip(2);
Assert.Equal(3, remaining.ElementAtOrDefault(0));
Assert.Equal(4, remaining.ElementAtOrDefault(1));
Assert.Equal(6, remaining.ElementAtOrDefault(3));
Assert.Equal(0, remaining.ElementAtOrDefault(-1));
Assert.Equal(0, remaining.ElementAtOrDefault(4));
}
[Fact]
public void ElementAtOrDefaultNotIList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5, 6 });
var remaining = source.Skip(2);
Assert.Equal(3, remaining.ElementAtOrDefault(0));
Assert.Equal(4, remaining.ElementAtOrDefault(1));
Assert.Equal(6, remaining.ElementAtOrDefault(3));
Assert.Equal(0, remaining.ElementAtOrDefault(-1));
Assert.Equal(0, remaining.ElementAtOrDefault(4));
}
[Fact]
public void First()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(1, source.Skip(0).First());
Assert.Equal(3, source.Skip(2).First());
Assert.Equal(5, source.Skip(4).First());
Assert.Throws<InvalidOperationException>(() => source.Skip(5).First());
}
[Fact]
public void FirstNotIList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(1, source.Skip(0).First());
Assert.Equal(3, source.Skip(2).First());
Assert.Equal(5, source.Skip(4).First());
Assert.Throws<InvalidOperationException>(() => source.Skip(5).First());
}
[Fact]
public void FirstOrDefault()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(1, source.Skip(0).FirstOrDefault());
Assert.Equal(3, source.Skip(2).FirstOrDefault());
Assert.Equal(5, source.Skip(4).FirstOrDefault());
Assert.Equal(0, source.Skip(5).FirstOrDefault());
}
[Fact]
public void FirstOrDefaultNotIList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(1, source.Skip(0).FirstOrDefault());
Assert.Equal(3, source.Skip(2).FirstOrDefault());
Assert.Equal(5, source.Skip(4).FirstOrDefault());
Assert.Equal(0, source.Skip(5).FirstOrDefault());
}
[Fact]
public void Last()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(5, source.Skip(0).Last());
Assert.Equal(5, source.Skip(1).Last());
Assert.Equal(5, source.Skip(4).Last());
Assert.Throws<InvalidOperationException>(() => source.Skip(5).Last());
}
[Fact]
public void LastNotList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(5, source.Skip(0).Last());
Assert.Equal(5, source.Skip(1).Last());
Assert.Equal(5, source.Skip(4).Last());
Assert.Throws<InvalidOperationException>(() => source.Skip(5).Last());
}
[Fact]
public void LastOrDefault()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(5, source.Skip(0).LastOrDefault());
Assert.Equal(5, source.Skip(1).LastOrDefault());
Assert.Equal(5, source.Skip(4).LastOrDefault());
Assert.Equal(0, source.Skip(5).LastOrDefault());
}
[Fact]
public void LastOrDefaultNotList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(5, source.Skip(0).LastOrDefault());
Assert.Equal(5, source.Skip(1).LastOrDefault());
Assert.Equal(5, source.Skip(4).LastOrDefault());
Assert.Equal(0, source.Skip(5).LastOrDefault());
}
[Fact]
public void ToArray()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Skip(0).ToArray());
Assert.Equal(new[] { 2, 3, 4, 5 }, source.Skip(1).ToArray());
Assert.Equal(5, source.Skip(4).ToArray().Single());
Assert.Empty(source.Skip(5).ToArray());
Assert.Empty(source.Skip(40).ToArray());
}
[Fact]
public void ToArrayNotList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Skip(0).ToArray());
Assert.Equal(new[] { 2, 3, 4, 5 }, source.Skip(1).ToArray());
Assert.Equal(5, source.Skip(4).ToArray().Single());
Assert.Empty(source.Skip(5).ToArray());
Assert.Empty(source.Skip(40).ToArray());
}
[Fact]
public void ToList()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Skip(0).ToList());
Assert.Equal(new[] { 2, 3, 4, 5 }, source.Skip(1).ToList());
Assert.Equal(5, source.Skip(4).ToList().Single());
Assert.Empty(source.Skip(5).ToList());
Assert.Empty(source.Skip(40).ToList());
}
[Fact]
public void ToListNotList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Skip(0).ToList());
Assert.Equal(new[] { 2, 3, 4, 5 }, source.Skip(1).ToList());
Assert.Equal(5, source.Skip(4).ToList().Single());
Assert.Empty(source.Skip(5).ToList());
Assert.Empty(source.Skip(40).ToList());
}
[Fact]
public void RepeatEnumerating()
{
var source = new[] { 1, 2, 3, 4, 5 };
var remaining = source.Skip(1);
Assert.Equal(remaining, remaining);
}
[Fact]
public void RepeatEnumeratingNotList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
var remaining = source.Skip(1);
Assert.Equal(remaining, remaining);
}
[Fact]
public void LazySkipMoreThan32Bits()
{
var range = NumberRangeGuaranteedNotCollectionType(1, 100);
var skipped = range.Skip(50).Skip(int.MaxValue); // Could cause an integer overflow.
Assert.Empty(skipped);
Assert.Equal(0, skipped.Count());
Assert.Empty(skipped.ToArray());
Assert.Empty(skipped.ToList());
}
[Fact]
public void IteratorStateShouldNotChangeIfNumberOfElementsIsUnbounded()
{
// With https://github.com/dotnet/corefx/pull/13628, Skip and Take return
// the same type of iterator. For Take, there is a limit, or upper bound,
// on how many items can be returned from the iterator. An integer field,
// _state, is incremented to keep track of this and to stop enumerating once
// we pass that limit. However, for Skip, there is no such limit and the
// iterator can contain an unlimited number of items (including past int.MaxValue).
// This test makes sure that, in Skip, _state is not incorrectly incremented,
// so that it does not overflow to a negative number and enumeration does not
// stop prematurely.
var iterator = new FastInfiniteEnumerator<int>().Skip(1).GetEnumerator();
iterator.MoveNext(); // Make sure the underlying enumerator has been initialized.
FieldInfo state = iterator.GetType().GetTypeInfo()
.GetField("_state", BindingFlags.Instance | BindingFlags.NonPublic);
// On platforms that do not have this change, the optimization may not be present
// and the iterator may not have a field named _state. In that case, nop.
if (state != null)
{
state.SetValue(iterator, int.MaxValue);
for (int i = 0; i < 10; i++)
{
Assert.True(iterator.MoveNext());
}
}
}
[Theory]
[InlineData(0, -1)]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(2, 1)]
[InlineData(2, 2)]
[InlineData(2, 3)]
public void DisposeSource(int sourceCount, int count)
{
int state = 0;
var source = new DelegateIterator<int>(
moveNext: () => ++state <= sourceCount,
current: () => 0,
dispose: () => state = -1);
IEnumerator<int> iterator = source.Skip(count).GetEnumerator();
int iteratorCount = Math.Max(0, sourceCount - Math.Max(0, count));
Assert.All(Enumerable.Range(0, iteratorCount), _ => Assert.True(iterator.MoveNext()));
Assert.False(iterator.MoveNext());
Assert.Equal(-1, state);
}
}
}
| |
//
// 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.
//
namespace NLog.LayoutRenderers
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using NLog.Common;
using NLog.Config;
using NLog.Layouts;
/// <summary>
/// The performance counter.
/// </summary>
[LayoutRenderer("performancecounter")]
public class PerformanceCounterLayoutRenderer : LayoutRenderer
{
private PerformanceCounterCached _fixedPerformanceCounter;
private PerformanceCounterCached _performanceCounter;
/// <summary>
/// Gets or sets the name of the counter category.
/// </summary>
/// <docgen category='Performance Counter Options' order='10' />
[RequiredParameter]
public string Category { get; set; }
/// <summary>
/// Gets or sets the name of the performance counter.
/// </summary>
/// <docgen category='Performance Counter Options' order='10' />
[RequiredParameter]
public string Counter { get; set; }
/// <summary>
/// Gets or sets the name of the performance counter instance (e.g. this.Global_).
/// </summary>
/// <docgen category='Performance Counter Options' order='10' />
public Layout Instance
{
get { return _instance; }
set
{
_instance = value;
ResetPerformanceCounters();
}
}
private Layout _instance;
/// <summary>
/// Gets or sets the name of the machine to read the performance counter from.
/// </summary>
/// <docgen category='Performance Counter Options' order='10' />
public Layout MachineName
{
get { return _machineName; }
set
{
_machineName = value;
ResetPerformanceCounters();
}
}
private Layout _machineName;
/// <summary>
/// Format string for conversion from float to string.
/// </summary>
/// <docgen category='Layout Options' order='50' />
public string Format { get; set; }
/// <summary>
/// Gets or sets the culture used for rendering.
/// </summary>
/// <docgen category='Layout Options' order='100' />
public CultureInfo Culture { get; set; }
/// <inheritdoc/>
protected override void InitializeLayoutRenderer()
{
base.InitializeLayoutRenderer();
if (_instance is null && string.Equals(Category, "Process", StringComparison.OrdinalIgnoreCase))
{
_instance = GetCurrentProcessInstanceName(Category) ?? string.Empty;
}
LookupPerformanceCounter(LogEventInfo.CreateNullEvent());
}
/// <inheritdoc/>
protected override void CloseLayoutRenderer()
{
base.CloseLayoutRenderer();
_fixedPerformanceCounter?.Close();
_performanceCounter?.Close();
ResetPerformanceCounters();
}
/// <inheritdoc/>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
var performanceCounter = LookupPerformanceCounter(logEvent);
var formatProvider = GetFormatProvider(logEvent, Culture);
builder.Append(performanceCounter.GetValue().ToString(Format, formatProvider));
}
private void ResetPerformanceCounters()
{
_fixedPerformanceCounter = null;
_performanceCounter = null;
}
PerformanceCounterCached LookupPerformanceCounter(LogEventInfo logEventInfo)
{
var perfCounterCached = _fixedPerformanceCounter;
if (perfCounterCached != null)
return perfCounterCached;
perfCounterCached = _performanceCounter;
var machineName = _machineName?.Render(logEventInfo) ?? string.Empty;
var instanceName = _instance?.Render(logEventInfo) ?? string.Empty;
if (perfCounterCached != null && perfCounterCached.MachineName == machineName && perfCounterCached.InstanceName == instanceName)
{
return perfCounterCached;
}
var perfCounter = CreatePerformanceCounter(machineName, instanceName);
perfCounterCached = new PerformanceCounterCached(machineName, instanceName, perfCounter);
if ((_machineName is null || (_machineName as SimpleLayout)?.IsFixedText == true) && (_instance is null || (_instance as SimpleLayout)?.IsFixedText == true))
{
_fixedPerformanceCounter = perfCounterCached;
}
else
{
_performanceCounter = perfCounterCached;
}
return perfCounterCached;
}
private PerformanceCounter CreatePerformanceCounter(string machineName, string instanceName)
{
if (!string.IsNullOrEmpty(machineName))
{
return new PerformanceCounter(Category, Counter, instanceName, machineName);
}
return new PerformanceCounter(Category, Counter, instanceName, true);
}
/// <summary>
/// If having multiple instances with the same process-name, then they will get different instance names
/// </summary>
private static string GetCurrentProcessInstanceName(string category)
{
try
{
using (Process proc = Process.GetCurrentProcess())
{
int pid = proc.Id;
PerformanceCounterCategory cat = new PerformanceCounterCategory(category);
foreach (string instanceValue in cat.GetInstanceNames())
{
int val = GetProcessIdFromInstanceName(category, instanceValue);
if (val == pid)
{
InternalLogger.Debug("PerformanceCounter - Found instance-name={0} from processId={1}", instanceValue, pid);
return instanceValue;
}
}
InternalLogger.Debug("PerformanceCounter - Failed to auto detect current process instance. ProcessId={0}", pid);
}
}
catch (Exception ex)
{
if (LogManager.ThrowExceptions)
throw;
InternalLogger.Warn(ex, "PerformanceCounter - Failed to auto detect current process instance.");
}
return string.Empty;
}
private static int GetProcessIdFromInstanceName(string category, string instanceName)
{
try
{
using (PerformanceCounter cnt = new PerformanceCounter(category, "ID Process", instanceName, true))
{
var val = (int)cnt.RawValue;
return val;
}
}
catch (Exception ex)
{
InternalLogger.Debug(ex, "PerformanceCounter - Skipped instance-name={0} since no longer valid.", instanceName);
}
return 0;
}
class PerformanceCounterCached
{
private readonly PerformanceCounter _perfCounter;
private readonly object _lockObject = new object();
private CounterSample _prevSample = CounterSample.Empty;
private CounterSample _nextSample = CounterSample.Empty;
public PerformanceCounterCached(string machineName, string instanceName, PerformanceCounter performanceCounter)
{
MachineName = machineName;
InstanceName = instanceName;
_perfCounter = performanceCounter;
GetValue(); // Prepare Performance Counter for CounterSample.Calculate
}
public string MachineName { get; }
public string InstanceName { get; }
public float GetValue()
{
lock (_lockObject)
{
CounterSample currentSample = _perfCounter.NextSample();
if (currentSample.SystemFrequency != 0)
{
// The recommended delay time between calls to the NextSample method is one second, to allow the counter to perform the next incremental read.
float timeDifferenceSecs = (currentSample.TimeStamp - _nextSample.TimeStamp) / (float)currentSample.SystemFrequency;
if (timeDifferenceSecs > 0.5F || timeDifferenceSecs < -0.5F)
{
_prevSample = _nextSample;
_nextSample = currentSample;
if (_prevSample.Equals(CounterSample.Empty))
_prevSample = currentSample;
}
}
else
{
_prevSample = _nextSample;
_nextSample = currentSample;
}
float sampleValue = CounterSample.Calculate(_prevSample, currentSample);
return sampleValue;
}
}
public void Close()
{
_perfCounter.Close();
}
}
}
}
| |
using System;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
namespace ServiceStack.ServiceInterface
{
/// <summary>
/// Base class for services that support HTTP verbs.
/// </summary>
/// <typeparam name="TRequest">The request class that the descendent class
/// is responsible for processing.</typeparam>
[Obsolete("Use the New API (ServiceStack.ServiceInterface.Service) for future services. See: https://github.com/ServiceStack/ServiceStack/wiki/New-Api")]
public abstract class RestServiceBase<TRequest>
: ServiceBase<TRequest>,
IRestGetService<TRequest>,
IRestPutService<TRequest>,
IRestPostService<TRequest>,
IRestDeleteService<TRequest>,
IRestPatchService<TRequest>
{
/// <summary>
/// What gets run when the request is sent to AsyncOneWay endpoint.
/// For a REST service the OnPost() method is called.
/// </summary>
protected override object Run(TRequest request)
{
return OnPost(request);
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// GET verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the GET
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnGet(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Get(TRequest request)
{
try
{
BeforeEachRequest(request);
return AfterEachRequest(request, OnGet(request));
}
catch (Exception ex)
{
var result = HandleException(request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// PUT verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the PUT
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnPut(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Put(TRequest request)
{
try
{
BeforeEachRequest(request);
return AfterEachRequest(request, OnPut(request));
}
catch (Exception ex)
{
var result = HandleException(request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// POST verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the POST
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnPost(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Post(TRequest request)
{
try
{
BeforeEachRequest(request);
return AfterEachRequest(request, OnPost(request));
}
catch (Exception ex)
{
var result = HandleException(request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// DELETE verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the DELETE
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnDelete(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Delete(TRequest request)
{
try
{
BeforeEachRequest(request);
return AfterEachRequest(request, OnDelete(request));
}
catch (Exception ex)
{
var result = HandleException(request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// PATCH verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the PATCH
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnPatch(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Patch(TRequest request)
{
try
{
BeforeEachRequest(request);
return AfterEachRequest(request, OnPatch(request));
}
catch (Exception ex)
{
var result = HandleException(request, ex);
if (result == null) throw;
return result;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using PAL_TlsHandshakeState = Interop.AppleCrypto.PAL_TlsHandshakeState;
using PAL_TlsIo = Interop.AppleCrypto.PAL_TlsIo;
namespace System.Net.Security
{
internal static class SslStreamPal
{
private static readonly StreamSizes s_streamSizes = new StreamSizes();
public static Exception GetException(SecurityStatusPal status)
{
return status.Exception ?? new Win32Exception((int)status.ErrorCode);
}
internal const bool StartMutualAuthAsAnonymous = false;
// SecureTransport is okay with a 0 byte input, but it produces a 0 byte output.
// Since ST is not producing the framed empty message just call this false and avoid the
// special case of an empty array being passed to the `fixed` statement.
internal const bool CanEncryptEmptyMessage = false;
public static void VerifyPackageInfo()
{
}
public static SecurityStatusPal AcceptSecurityContext(
ref SafeFreeCredentials credential,
ref SafeDeleteContext context,
SecurityBuffer[] inputBuffers,
SecurityBuffer outputBuffer,
SslAuthenticationOptions sslAuthenticationOptions)
{
if (inputBuffers != null)
{
Debug.Assert(inputBuffers.Length == 2);
Debug.Assert(inputBuffers[1].token == null);
return HandshakeInternal(credential, ref context, inputBuffers[0], outputBuffer, sslAuthenticationOptions);
}
else
{
return HandshakeInternal(credential, ref context, inputBuffer: null, outputBuffer, sslAuthenticationOptions);
}
}
public static SecurityStatusPal InitializeSecurityContext(
ref SafeFreeCredentials credential,
ref SafeDeleteContext context,
string targetName,
SecurityBuffer inputBuffer,
SecurityBuffer outputBuffer,
SslAuthenticationOptions sslAuthenticationOptions)
{
return HandshakeInternal(credential, ref context, inputBuffer, outputBuffer, sslAuthenticationOptions);
}
public static SecurityStatusPal InitializeSecurityContext(
SafeFreeCredentials credential,
ref SafeDeleteContext context,
string targetName,
SecurityBuffer[] inputBuffers,
SecurityBuffer outputBuffer,
SslAuthenticationOptions sslAuthenticationOptions)
{
Debug.Assert(inputBuffers.Length == 2);
Debug.Assert(inputBuffers[1].token == null);
return HandshakeInternal(credential, ref context, inputBuffers[0], outputBuffer, sslAuthenticationOptions);
}
public static SecurityBuffer[] GetIncomingSecurityBuffers(SslAuthenticationOptions options, ref SecurityBuffer incomingSecurity)
{
SecurityBuffer[] incomingSecurityBuffers = null;
if (incomingSecurity != null)
{
incomingSecurityBuffers = new SecurityBuffer[]
{
incomingSecurity,
new SecurityBuffer(null, 0, 0, SecurityBufferType.SECBUFFER_EMPTY)
};
}
return incomingSecurityBuffers;
}
public static SafeFreeCredentials AcquireCredentialsHandle(
X509Certificate certificate,
SslProtocols protocols,
EncryptionPolicy policy,
bool isServer)
{
return new SafeFreeSslCredentials(certificate, protocols, policy);
}
internal static byte[] GetNegotiatedApplicationProtocol(SafeDeleteContext context)
{
// OSX SecureTransport does not export APIs to support ALPN, no-op.
return null;
}
public static SecurityStatusPal EncryptMessage(
SafeDeleteContext securityContext,
ReadOnlyMemory<byte> input,
int headerSize,
int trailerSize,
ref byte[] output,
out int resultSize)
{
resultSize = 0;
Debug.Assert(input.Length > 0, $"{nameof(input.Length)} > 0 since {nameof(CanEncryptEmptyMessage)} is false");
try
{
SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext;
SafeSslHandle sslHandle = sslContext.SslContext;
unsafe
{
MemoryHandle memHandle = input.Retain(pin: true);
try
{
PAL_TlsIo status;
lock (sslHandle)
{
status = Interop.AppleCrypto.SslWrite(
sslHandle,
(byte*)memHandle.Pointer,
input.Length,
out int written);
}
if (status < 0)
{
return new SecurityStatusPal(
SecurityStatusPalErrorCode.InternalError,
Interop.AppleCrypto.CreateExceptionForOSStatus((int)status));
}
if (sslContext.BytesReadyForConnection <= output?.Length)
{
resultSize = sslContext.ReadPendingWrites(output, 0, output.Length);
}
else
{
output = sslContext.ReadPendingWrites();
resultSize = output.Length;
}
switch (status)
{
case PAL_TlsIo.Success:
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
case PAL_TlsIo.WouldBlock:
return new SecurityStatusPal(SecurityStatusPalErrorCode.ContinueNeeded);
default:
Debug.Fail($"Unknown status value: {status}");
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError);
}
}
finally
{
memHandle.Dispose();
}
}
}
catch (Exception e)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, e);
}
}
public static SecurityStatusPal DecryptMessage(
SafeDeleteContext securityContext,
byte[] buffer,
ref int offset,
ref int count)
{
try
{
SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext;
SafeSslHandle sslHandle = sslContext.SslContext;
sslContext.Write(buffer, offset, count);
unsafe
{
fixed (byte* offsetInput = &buffer[offset])
{
int written;
PAL_TlsIo status;
lock (sslHandle)
{
status = Interop.AppleCrypto.SslRead(sslHandle, offsetInput, count, out written);
}
if (status < 0)
{
return new SecurityStatusPal(
SecurityStatusPalErrorCode.InternalError,
Interop.AppleCrypto.CreateExceptionForOSStatus((int)status));
}
count = written;
switch (status)
{
case PAL_TlsIo.Success:
case PAL_TlsIo.WouldBlock:
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
case PAL_TlsIo.ClosedGracefully:
return new SecurityStatusPal(SecurityStatusPalErrorCode.ContextExpired);
case PAL_TlsIo.Renegotiate:
return new SecurityStatusPal(SecurityStatusPalErrorCode.Renegotiate);
default:
Debug.Fail($"Unknown status value: {status}");
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError);
}
}
}
}
catch (Exception e)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, e);
}
}
public static ChannelBinding QueryContextChannelBinding(
SafeDeleteContext securityContext,
ChannelBindingKind attribute)
{
switch (attribute)
{
case ChannelBindingKind.Endpoint:
return EndpointChannelBindingToken.Build(securityContext);
}
// SecureTransport doesn't expose the Finished messages, so a Unique binding token
// cannot be built.
//
// Windows/netfx compat says to return null for not supported kinds (including unmapped enum values).
return null;
}
public static void QueryContextStreamSizes(
SafeDeleteContext securityContext,
out StreamSizes streamSizes)
{
streamSizes = s_streamSizes;
}
public static void QueryContextConnectionInfo(
SafeDeleteContext securityContext,
out SslConnectionInfo connectionInfo)
{
connectionInfo = new SslConnectionInfo(((SafeDeleteSslContext)securityContext).SslContext);
}
private static SecurityStatusPal HandshakeInternal(
SafeFreeCredentials credential,
ref SafeDeleteContext context,
SecurityBuffer inputBuffer,
SecurityBuffer outputBuffer,
SslAuthenticationOptions sslAuthenticationOptions)
{
Debug.Assert(!credential.IsInvalid);
try
{
SafeDeleteSslContext sslContext = ((SafeDeleteSslContext)context);
if ((null == context) || context.IsInvalid)
{
sslContext = new SafeDeleteSslContext(credential as SafeFreeSslCredentials, sslAuthenticationOptions);
context = sslContext;
if (!string.IsNullOrEmpty(sslAuthenticationOptions.TargetHost))
{
Debug.Assert(!sslAuthenticationOptions.IsServer, "targetName should not be set for server-side handshakes");
Interop.AppleCrypto.SslSetTargetName(sslContext.SslContext, sslAuthenticationOptions.TargetHost);
}
if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired)
{
Interop.AppleCrypto.SslSetAcceptClientCert(sslContext.SslContext);
}
}
if (inputBuffer != null && inputBuffer.size > 0)
{
sslContext.Write(inputBuffer.token, inputBuffer.offset, inputBuffer.size);
}
SafeSslHandle sslHandle = sslContext.SslContext;
SecurityStatusPal status;
lock (sslHandle)
{
status = PerformHandshake(sslHandle);
}
byte[] output = sslContext.ReadPendingWrites();
outputBuffer.offset = 0;
outputBuffer.size = output?.Length ?? 0;
outputBuffer.token = output;
return status;
}
catch (Exception exc)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, exc);
}
}
private static SecurityStatusPal PerformHandshake(SafeSslHandle sslHandle)
{
while (true)
{
PAL_TlsHandshakeState handshakeState = Interop.AppleCrypto.SslHandshake(sslHandle);
switch (handshakeState)
{
case PAL_TlsHandshakeState.Complete:
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
case PAL_TlsHandshakeState.WouldBlock:
return new SecurityStatusPal(SecurityStatusPalErrorCode.ContinueNeeded);
case PAL_TlsHandshakeState.ServerAuthCompleted:
case PAL_TlsHandshakeState.ClientAuthCompleted:
// The standard flow would be to call the verification callback now, and
// possibly abort. But the library is set up to call this "success" and
// do verification between "handshake complete" and "first send/receive".
//
// So, call SslHandshake again to indicate to Secure Transport that we've
// accepted this handshake and it should go into the ready state.
break;
default:
return new SecurityStatusPal(
SecurityStatusPalErrorCode.InternalError,
Interop.AppleCrypto.CreateExceptionForOSStatus((int)handshakeState));
}
}
}
public static SecurityStatusPal ApplyAlertToken(
ref SafeFreeCredentials credentialsHandle,
SafeDeleteContext securityContext,
TlsAlertType alertType,
TlsAlertMessage alertMessage)
{
// There doesn't seem to be an exposed API for writing an alert,
// the API seems to assume that all alerts are generated internally by
// SSLHandshake.
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
public static SecurityStatusPal ApplyShutdownToken(
ref SafeFreeCredentials credentialsHandle,
SafeDeleteContext securityContext)
{
SafeDeleteSslContext sslContext = ((SafeDeleteSslContext)securityContext);
SafeSslHandle sslHandle = sslContext.SslContext;
int osStatus;
lock (sslHandle)
{
osStatus = Interop.AppleCrypto.SslShutdown(sslHandle);
}
if (osStatus == 0)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
return new SecurityStatusPal(
SecurityStatusPalErrorCode.InternalError,
Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus));
}
}
}
| |
using System;
using System.IO;
using System.Security.Cryptography;
namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// An input buffer customised for use by <see cref="InflaterInputStream"/>
/// </summary>
/// <remarks>
/// The buffer supports decryption of incoming data.
/// </remarks>
public class InflaterInputBuffer
{
#region Constructors
/// <summary>
/// Initialise a new instance of <see cref="InflaterInputBuffer"/> with a default buffer size
/// </summary>
/// <param name="stream">The stream to buffer.</param>
public InflaterInputBuffer(Stream stream) : this(stream, 4096)
{
}
/// <summary>
/// Initialise a new instance of <see cref="InflaterInputBuffer"/>
/// </summary>
/// <param name="stream">The stream to buffer.</param>
/// <param name="bufferSize">The size to use for the buffer</param>
/// <remarks>A minimum buffer size of 1KB is permitted. Lower sizes are treated as 1KB.</remarks>
public InflaterInputBuffer(Stream stream, int bufferSize)
{
inputStream = stream;
if (bufferSize < 1024)
{
bufferSize = 1024;
}
rawData = new byte[bufferSize];
clearText = rawData;
}
#endregion Constructors
/// <summary>
/// Get the length of bytes bytes in the <see cref="RawData"/>
/// </summary>
public int RawLength
{
get
{
return rawLength;
}
}
/// <summary>
/// Get the contents of the raw data buffer.
/// </summary>
/// <remarks>This may contain encrypted data.</remarks>
public byte[] RawData
{
get
{
return rawData;
}
}
/// <summary>
/// Get the number of useable bytes in <see cref="ClearText"/>
/// </summary>
public int ClearTextLength
{
get
{
return clearTextLength;
}
}
/// <summary>
/// Get the contents of the clear text buffer.
/// </summary>
public byte[] ClearText
{
get
{
return clearText;
}
}
/// <summary>
/// Get/set the number of bytes available
/// </summary>
public int Available
{
get { return available; }
set { available = value; }
}
/// <summary>
/// Call <see cref="Inflater.SetInput(byte[], int, int)"/> passing the current clear text buffer contents.
/// </summary>
/// <param name="inflater">The inflater to set input for.</param>
public void SetInflaterInput(Inflater inflater)
{
if (available > 0)
{
inflater.SetInput(clearText, clearTextLength - available, available);
available = 0;
}
}
/// <summary>
/// Fill the buffer from the underlying input stream.
/// </summary>
public void Fill()
{
rawLength = 0;
int toRead = rawData.Length;
while (toRead > 0)
{
int count = inputStream.Read(rawData, rawLength, toRead);
if (count <= 0)
{
break;
}
rawLength += count;
toRead -= count;
}
if (cryptoTransform != null)
{
clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0);
}
else
{
clearTextLength = rawLength;
}
available = clearTextLength;
}
/// <summary>
/// Read a buffer directly from the input stream
/// </summary>
/// <param name="buffer">The buffer to fill</param>
/// <returns>Returns the number of bytes read.</returns>
public int ReadRawBuffer(byte[] buffer)
{
return ReadRawBuffer(buffer, 0, buffer.Length);
}
/// <summary>
/// Read a buffer directly from the input stream
/// </summary>
/// <param name="outBuffer">The buffer to read into</param>
/// <param name="offset">The offset to start reading data into.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>Returns the number of bytes read.</returns>
public int ReadRawBuffer(byte[] outBuffer, int offset, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
int currentOffset = offset;
int currentLength = length;
while (currentLength > 0)
{
if (available <= 0)
{
Fill();
if (available <= 0)
{
return 0;
}
}
int toCopy = Math.Min(currentLength, available);
System.Array.Copy(rawData, rawLength - (int)available, outBuffer, currentOffset, toCopy);
currentOffset += toCopy;
currentLength -= toCopy;
available -= toCopy;
}
return length;
}
/// <summary>
/// Read clear text data from the input stream.
/// </summary>
/// <param name="outBuffer">The buffer to add data to.</param>
/// <param name="offset">The offset to start adding data at.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>Returns the number of bytes actually read.</returns>
public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
int currentOffset = offset;
int currentLength = length;
while (currentLength > 0)
{
if (available <= 0)
{
Fill();
if (available <= 0)
{
return 0;
}
}
int toCopy = Math.Min(currentLength, available);
Array.Copy(clearText, clearTextLength - (int)available, outBuffer, currentOffset, toCopy);
currentOffset += toCopy;
currentLength -= toCopy;
available -= toCopy;
}
return length;
}
/// <summary>
/// Read a <see cref="byte"/> from the input stream.
/// </summary>
/// <returns>Returns the byte read.</returns>
public int ReadLeByte()
{
if (available <= 0)
{
Fill();
if (available <= 0)
{
throw new ZipException("EOF in header");
}
}
byte result = rawData[rawLength - available];
available -= 1;
return result;
}
/// <summary>
/// Read an <see cref="short"/> in little endian byte order.
/// </summary>
/// <returns>The short value read case to an int.</returns>
public int ReadLeShort()
{
return ReadLeByte() | (ReadLeByte() << 8);
}
/// <summary>
/// Read an <see cref="int"/> in little endian byte order.
/// </summary>
/// <returns>The int value read.</returns>
public int ReadLeInt()
{
return ReadLeShort() | (ReadLeShort() << 16);
}
/// <summary>
/// Read a <see cref="long"/> in little endian byte order.
/// </summary>
/// <returns>The long value read.</returns>
public long ReadLeLong()
{
return (uint)ReadLeInt() | ((long)ReadLeInt() << 32);
}
/// <summary>
/// Get/set the <see cref="ICryptoTransform"/> to apply to any data.
/// </summary>
/// <remarks>Set this value to null to have no transform applied.</remarks>
public ICryptoTransform CryptoTransform
{
set
{
cryptoTransform = value;
if (cryptoTransform != null)
{
if (rawData == clearText)
{
if (internalClearText == null)
{
internalClearText = new byte[rawData.Length];
}
clearText = internalClearText;
}
clearTextLength = rawLength;
if (available > 0)
{
cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available);
}
}
else
{
clearText = rawData;
clearTextLength = rawLength;
}
}
}
#region Instance Fields
private int rawLength;
private byte[] rawData;
private int clearTextLength;
private byte[] clearText;
private byte[] internalClearText;
private int available;
private ICryptoTransform cryptoTransform;
private Stream inputStream;
#endregion Instance Fields
}
/// <summary>
/// This filter stream is used to decompress data compressed using the "deflate"
/// format. The "deflate" format is described in RFC 1951.
///
/// This stream may form the basis for other decompression filters, such
/// as the <see cref="ICSharpCode.SharpZipLib.GZip.GZipInputStream">GZipInputStream</see>.
///
/// Author of the original java version : John Leuner.
/// </summary>
public class InflaterInputStream : Stream
{
#region Constructors
/// <summary>
/// Create an InflaterInputStream with the default decompressor
/// and a default buffer size of 4KB.
/// </summary>
/// <param name = "baseInputStream">
/// The InputStream to read bytes from
/// </param>
public InflaterInputStream(Stream baseInputStream)
: this(baseInputStream, new Inflater(), 4096)
{
}
/// <summary>
/// Create an InflaterInputStream with the specified decompressor
/// and a default buffer size of 4KB.
/// </summary>
/// <param name = "baseInputStream">
/// The source of input data
/// </param>
/// <param name = "inf">
/// The decompressor used to decompress data read from baseInputStream
/// </param>
public InflaterInputStream(Stream baseInputStream, Inflater inf)
: this(baseInputStream, inf, 4096)
{
}
/// <summary>
/// Create an InflaterInputStream with the specified decompressor
/// and the specified buffer size.
/// </summary>
/// <param name = "baseInputStream">
/// The InputStream to read bytes from
/// </param>
/// <param name = "inflater">
/// The decompressor to use
/// </param>
/// <param name = "bufferSize">
/// Size of the buffer to use
/// </param>
public InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize)
{
if (baseInputStream == null)
{
throw new ArgumentNullException(nameof(baseInputStream));
}
if (inflater == null)
{
throw new ArgumentNullException(nameof(inflater));
}
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize));
}
this.baseInputStream = baseInputStream;
this.inf = inflater;
inputBuffer = new InflaterInputBuffer(baseInputStream, bufferSize);
}
#endregion Constructors
/// <summary>
/// Gets or sets a flag indicating ownership of underlying stream.
/// When the flag is true <see cref="Stream.Dispose()" /> will close the underlying stream also.
/// </summary>
/// <remarks>The default value is true.</remarks>
public bool IsStreamOwner { get; set; } = true;
/// <summary>
/// Skip specified number of bytes of uncompressed data
/// </summary>
/// <param name ="count">
/// Number of bytes to skip
/// </param>
/// <returns>
/// The number of bytes skipped, zero if the end of
/// stream has been reached
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="count">The number of bytes</paramref> to skip is less than or equal to zero.
/// </exception>
public long Skip(long count)
{
if (count <= 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
// v0.80 Skip by seeking if underlying stream supports it...
if (baseInputStream.CanSeek)
{
baseInputStream.Seek(count, SeekOrigin.Current);
return count;
}
else
{
int length = 2048;
if (count < length)
{
length = (int)count;
}
byte[] tmp = new byte[length];
int readCount = 1;
long toSkip = count;
while ((toSkip > 0) && (readCount > 0))
{
if (toSkip < length)
{
length = (int)toSkip;
}
readCount = baseInputStream.Read(tmp, 0, length);
toSkip -= readCount;
}
return count - toSkip;
}
}
/// <summary>
/// Clear any cryptographic state.
/// </summary>
protected void StopDecrypting()
{
inputBuffer.CryptoTransform = null;
}
/// <summary>
/// Returns 0 once the end of the stream (EOF) has been reached.
/// Otherwise returns 1.
/// </summary>
public virtual int Available
{
get
{
return inf.IsFinished ? 0 : 1;
}
}
/// <summary>
/// Fills the buffer with more data to decompress.
/// </summary>
/// <exception cref="SharpZipBaseException">
/// Stream ends early
/// </exception>
protected void Fill()
{
// Protect against redundant calls
if (inputBuffer.Available <= 0)
{
inputBuffer.Fill();
if (inputBuffer.Available <= 0)
{
throw new SharpZipBaseException("Unexpected EOF");
}
}
inputBuffer.SetInflaterInput(inf);
}
#region Stream Overrides
/// <summary>
/// Gets a value indicating whether the current stream supports reading
/// </summary>
public override bool CanRead
{
get
{
return baseInputStream.CanRead;
}
}
/// <summary>
/// Gets a value of false indicating seeking is not supported for this stream.
/// </summary>
public override bool CanSeek
{
get
{
return false;
}
}
/// <summary>
/// Gets a value of false indicating that this stream is not writeable.
/// </summary>
public override bool CanWrite
{
get
{
return false;
}
}
/// <summary>
/// A value representing the length of the stream in bytes.
/// </summary>
public override long Length
{
get
{
//return inputBuffer.RawLength;
throw new NotSupportedException("InflaterInputStream Length is not supported");
}
}
/// <summary>
/// The current position within the stream.
/// Throws a NotSupportedException when attempting to set the position
/// </summary>
/// <exception cref="NotSupportedException">Attempting to set the position</exception>
public override long Position
{
get
{
return baseInputStream.Position;
}
set
{
throw new NotSupportedException("InflaterInputStream Position not supported");
}
}
/// <summary>
/// Flushes the baseInputStream
/// </summary>
public override void Flush()
{
baseInputStream.Flush();
}
/// <summary>
/// Sets the position within the current stream
/// Always throws a NotSupportedException
/// </summary>
/// <param name="offset">The relative offset to seek to.</param>
/// <param name="origin">The <see cref="SeekOrigin"/> defining where to seek from.</param>
/// <returns>The new position in the stream.</returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("Seek not supported");
}
/// <summary>
/// Set the length of the current stream
/// Always throws a NotSupportedException
/// </summary>
/// <param name="value">The new length value for the stream.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void SetLength(long value)
{
throw new NotSupportedException("InflaterInputStream SetLength not supported");
}
/// <summary>
/// Writes a sequence of bytes to stream and advances the current position
/// This method always throws a NotSupportedException
/// </summary>
/// <param name="buffer">Thew buffer containing data to write.</param>
/// <param name="offset">The offset of the first byte to write.</param>
/// <param name="count">The number of bytes to write.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException("InflaterInputStream Write not supported");
}
/// <summary>
/// Writes one byte to the current stream and advances the current position
/// Always throws a NotSupportedException
/// </summary>
/// <param name="value">The byte to write.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void WriteByte(byte value)
{
throw new NotSupportedException("InflaterInputStream WriteByte not supported");
}
/// <summary>
/// Closes the input stream. When <see cref="IsStreamOwner"></see>
/// is true the underlying stream is also closed.
/// </summary>
protected override void Dispose(bool disposing)
{
if (!isClosed)
{
isClosed = true;
if (IsStreamOwner)
{
baseInputStream.Dispose();
}
}
}
/// <summary>
/// Reads decompressed data into the provided buffer byte array
/// </summary>
/// <param name ="buffer">
/// The array to read and decompress data into
/// </param>
/// <param name ="offset">
/// The offset indicating where the data should be placed
/// </param>
/// <param name ="count">
/// The number of bytes to decompress
/// </param>
/// <returns>The number of bytes read. Zero signals the end of stream</returns>
/// <exception cref="SharpZipBaseException">
/// Inflater needs a dictionary
/// </exception>
public override int Read(byte[] buffer, int offset, int count)
{
if (inf.IsNeedingDictionary)
{
throw new SharpZipBaseException("Need a dictionary");
}
int remainingBytes = count;
while (true)
{
int bytesRead = inf.Inflate(buffer, offset, remainingBytes);
offset += bytesRead;
remainingBytes -= bytesRead;
if (remainingBytes == 0 || inf.IsFinished)
{
break;
}
if (inf.IsNeedingInput)
{
Fill();
}
else if (bytesRead == 0)
{
throw new ZipException("Invalid input data");
}
}
return count - remainingBytes;
}
#endregion Stream Overrides
#region Instance Fields
/// <summary>
/// Decompressor for this stream
/// </summary>
protected Inflater inf;
/// <summary>
/// <see cref="InflaterInputBuffer">Input buffer</see> for this stream.
/// </summary>
protected InflaterInputBuffer inputBuffer;
/// <summary>
/// Base stream the inflater reads from.
/// </summary>
private Stream baseInputStream;
/// <summary>
/// The compressed size
/// </summary>
protected long csize;
/// <summary>
/// Flag indicating wether this instance has been closed or not.
/// </summary>
private bool isClosed;
#endregion Instance Fields
}
}
| |
/*
* 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 ParquetSharp.External;
using ParquetSharp.IO.Api;
using ParquetSharp.Schema;
namespace ParquetSharp.Column.Statistics
{
/**
* Statistics class to keep track of statistics in parquet pages and column chunks
*
* @author Katya Gonina
*/
public abstract class Statistics
{
private bool _hasNonNullValue;
private long num_nulls;
public Statistics()
{
_hasNonNullValue = false;
num_nulls = 0;
}
/**
* Returns the typed statistics object based on the passed type parameter
* @param type PrimitiveTypeName type of the column
* @return instance of a typed statistics class
*/
public static Statistics getStatsBasedOnType(PrimitiveType.PrimitiveTypeName type)
{
switch (type.Name)
{
case PrimitiveType.Name.INT32:
return new IntStatistics();
case PrimitiveType.Name.INT64:
return new LongStatistics();
case PrimitiveType.Name.FLOAT:
return new FloatStatistics();
case PrimitiveType.Name.DOUBLE:
return new DoubleStatistics();
case PrimitiveType.Name.BOOLEAN:
return new BooleanStatistics();
case PrimitiveType.Name.BINARY:
return new BinaryStatistics();
case PrimitiveType.Name.INT96:
return new BinaryStatistics();
case PrimitiveType.Name.FIXED_LEN_BYTE_ARRAY:
return new BinaryStatistics();
default:
throw new UnknownColumnTypeException(type);
}
}
/**
* updates statistics min and max using the passed value
* @param value value to use to update min and max
*/
public virtual void updateStats(int value)
{
throw new NotSupportedException();
}
/**
* updates statistics min and max using the passed value
* @param value value to use to update min and max
*/
public virtual void updateStats(long value)
{
throw new NotSupportedException();
}
/**
* updates statistics min and max using the passed value
* @param value value to use to update min and max
*/
public virtual void updateStats(float value)
{
throw new NotSupportedException();
}
/**
* updates statistics min and max using the passed value
* @param value value to use to update min and max
*/
public virtual void updateStats(double value)
{
throw new NotSupportedException();
}
/**
* updates statistics min and max using the passed value
* @param value value to use to update min and max
*/
public virtual void updateStats(bool value)
{
throw new NotSupportedException();
}
/**
* updates statistics min and max using the passed value
* @param value value to use to update min and max
*/
public virtual void updateStats(Binary value)
{
throw new NotSupportedException();
}
/**
* Hash code for the statistics object
* @return hash code int
*/
public override int GetHashCode()
{
return 31 * Arrays.hashCode(getMaxBytes()) + 17 * Arrays.hashCode(getMinBytes()) + this.getNumNulls().GetHashCode();
}
/**
* Abstract method to merge this statistics min and max with the values
* of the parameter object. Does not do any checks, only called internally.
* @param stats Statistics object to merge with
*/
abstract protected void mergeStatisticsMinMax(Statistics stats);
/**
* Abstract method to set min and max values from byte arrays.
* @param minBytes byte array to set the min value to
* @param maxBytes byte array to set the max value to
*/
abstract public void setMinMaxFromBytes(byte[] minBytes, byte[] maxBytes);
abstract public object genericGetMin();
abstract public object genericGetMax();
/**
* Abstract method to return the max value as a byte array
* @return byte array corresponding to the max value
*/
abstract public byte[] getMaxBytes();
/**
* Abstract method to return the min value as a byte array
* @return byte array corresponding to the min value
*/
abstract public byte[] getMinBytes();
/**
* toString() to display min, max, num_nulls in a string
*/
abstract public override string ToString();
/**
* Increments the null count by one
*/
public void incrementNumNulls()
{
num_nulls++;
}
/**
* Increments the null count by the parameter value
* @param increment value to increment the null count by
*/
public void incrementNumNulls(long increment)
{
num_nulls += increment;
}
/**
* Returns the null count
* @return null count
*/
public long getNumNulls()
{
return num_nulls;
}
/**
* Sets the number of nulls to the parameter value
* @param nulls null count to set the count to
*/
public void setNumNulls(long nulls)
{
num_nulls = nulls;
}
/**
* Returns a boolean specifying if the Statistics object is empty,
* i.e does not contain valid statistics for the page/column yet
* @return true if object is empty, false otherwise
*/
public bool isEmpty()
{
return !_hasNonNullValue && num_nulls == 0;
}
/**
* Returns whether there have been non-null values added to this statistics
*/
public bool hasNonNullValue()
{
return _hasNonNullValue;
}
/**
* Sets the page/column as having a valid non-null value
* kind of misnomer here
*/
protected void markAsNotEmpty()
{
_hasNonNullValue = true;
}
}
public abstract class Statistics<T> : Statistics where T : IComparable<T>, IComparable
{
/**
* Equality comparison method to compare two statistics objects.
* @param other Object to compare against
* @return true if objects are equal, false otherwise
*/
public override bool Equals(object other)
{
if (other == this)
return true;
if (!(other is Statistics<T>))
return false;
Statistics<T> stats = (Statistics<T>)other;
return Arrays.equals(stats.getMaxBytes(), this.getMaxBytes()) &&
Arrays.equals(stats.getMinBytes(), this.getMinBytes()) &&
stats.getNumNulls() == this.getNumNulls();
}
sealed protected override void mergeStatisticsMinMax(Statistics stats)
{
mergeStatisticsMinMax((Statistics<T>)stats);
}
protected abstract void mergeStatisticsMinMax(Statistics<T> stats);
/**
* Method to merge this statistics object with the object passed
* as parameter. Merging keeps the smallest of min values, largest of max
* values and combines the number of null counts.
* @param stats Statistics object to merge with
*/
public void mergeStatistics(Statistics<T> stats)
{
if (stats.isEmpty()) return;
incrementNumNulls(stats.getNumNulls());
if (stats.hasNonNullValue())
{
mergeStatisticsMinMax(stats);
markAsNotEmpty();
}
}
sealed public override object genericGetMin()
{
return getMin();
}
sealed public override object genericGetMax()
{
return getMax();
}
abstract public T getMin();
abstract public T getMax();
}
}
| |
//
// Copyright (c) 2004-2016 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.
//
using System.Text;
#pragma warning disable 0618
namespace NLog.UnitTests.Contexts
{
using System;
using System.Collections.Generic;
using System.Threading;
using Xunit;
public class NestedDiagnosticsContextTests
{
[Fact]
public void NDCTest1()
{
List<Exception> exceptions = new List<Exception>();
ManualResetEvent mre = new ManualResetEvent(false);
int counter = 100;
int remaining = counter;
for (int i = 0; i < counter; ++i)
{
ThreadPool.QueueUserWorkItem(
s =>
{
try
{
NestedDiagnosticsContext.Clear();
Assert.Equal(string.Empty, NestedDiagnosticsContext.TopMessage);
Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop());
AssertContents(NestedDiagnosticsContext.GetAllMessages());
using (NestedDiagnosticsContext.Push("foo"))
{
Assert.Equal("foo", NestedDiagnosticsContext.TopMessage);
AssertContents(NestedDiagnosticsContext.GetAllMessages(), "foo");
using (NestedDiagnosticsContext.Push("bar"))
{
AssertContents(NestedDiagnosticsContext.GetAllMessages(), "bar", "foo");
Assert.Equal("bar", NestedDiagnosticsContext.TopMessage);
NestedDiagnosticsContext.Push("baz");
AssertContents(NestedDiagnosticsContext.GetAllMessages(), "baz", "bar", "foo");
Assert.Equal("baz", NestedDiagnosticsContext.TopMessage);
Assert.Equal("baz", NestedDiagnosticsContext.Pop());
AssertContents(NestedDiagnosticsContext.GetAllMessages(), "bar", "foo");
Assert.Equal("bar", NestedDiagnosticsContext.TopMessage);
}
AssertContents(NestedDiagnosticsContext.GetAllMessages(), "foo");
Assert.Equal("foo", NestedDiagnosticsContext.TopMessage);
}
AssertContents(NestedDiagnosticsContext.GetAllMessages());
Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop());
}
catch (Exception ex)
{
lock (exceptions)
{
exceptions.Add(ex);
}
}
finally
{
if (Interlocked.Decrement(ref remaining) == 0)
{
mre.Set();
}
}
});
}
mre.WaitOne();
StringBuilder exceptionsMessage = new StringBuilder();
foreach (var ex in exceptions)
{
if (exceptionsMessage.Length > 0)
{
exceptionsMessage.Append("\r\n");
}
exceptionsMessage.Append(ex.ToString());
}
Assert.True(exceptions.Count == 0, exceptionsMessage.ToString());
}
[Fact]
public void NDCTest2()
{
List<Exception> exceptions = new List<Exception>();
ManualResetEvent mre = new ManualResetEvent(false);
int counter = 100;
int remaining = counter;
for (int i = 0; i < counter; ++i)
{
ThreadPool.QueueUserWorkItem(
s =>
{
try
{
NDC.Clear();
Assert.Equal(string.Empty, NDC.TopMessage);
Assert.Equal(string.Empty, NDC.Pop());
AssertContents(NDC.GetAllMessages());
using (NDC.Push("foo"))
{
Assert.Equal("foo", NDC.TopMessage);
AssertContents(NDC.GetAllMessages(), "foo");
using (NDC.Push("bar"))
{
AssertContents(NDC.GetAllMessages(), "bar", "foo");
Assert.Equal("bar", NDC.TopMessage);
NDC.Push("baz");
AssertContents(NDC.GetAllMessages(), "baz", "bar", "foo");
Assert.Equal("baz", NDC.TopMessage);
Assert.Equal("baz", NDC.Pop());
AssertContents(NDC.GetAllMessages(), "bar", "foo");
Assert.Equal("bar", NDC.TopMessage);
}
AssertContents(NDC.GetAllMessages(), "foo");
Assert.Equal("foo", NDC.TopMessage);
}
AssertContents(NDC.GetAllMessages());
Assert.Equal(string.Empty, NDC.Pop());
}
catch (Exception ex)
{
lock (exceptions)
{
exceptions.Add(ex);
}
}
finally
{
if (Interlocked.Decrement(ref remaining) == 0)
{
mre.Set();
}
}
});
}
mre.WaitOne();
StringBuilder exceptionsMessage = new StringBuilder();
foreach (var ex in exceptions)
{
if (exceptionsMessage.Length > 0)
{
exceptionsMessage.Append("\r\n");
}
exceptionsMessage.Append(ex.ToString());
}
Assert.True(exceptions.Count == 0, exceptionsMessage.ToString());
}
private static void AssertContents(string[] actual, params string[] expected)
{
Assert.Equal(expected.Length, actual.Length);
for (int i = 0; i < expected.Length; ++i)
{
Assert.Equal(expected[i], actual[i]);
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ODataMessageReaderSettings.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.Core
{
using System;
using Microsoft.OData.Edm;
/// <summary>
/// Configuration settings for OData message readers.
/// </summary>
public sealed class ODataMessageReaderSettings : ODataMessageReaderSettingsBase
{
/// <summary>
/// A instance representing any knobs that control the behavior of the readers
/// inside and outside of WCF Data Services.
/// </summary>
private ODataReaderBehavior readerBehavior;
/// <summary>
/// The base uri used in payload.
/// </summary>
private Uri payloadBaseUri;
/// <summary>
/// Media type resolver used for this writer.
/// </summary>
private ODataMediaTypeResolver mediaTypeResolver;
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.OData.Core.ODataMessageReaderSettings" /> class with default values.</summary>
public ODataMessageReaderSettings()
: base()
{
this.DisablePrimitiveTypeConversion = false;
this.DisableMessageStreamDisposal = false;
this.UndeclaredPropertyBehaviorKinds = ODataUndeclaredPropertyBehaviorKinds.None;
// Create the default reader behavior
this.readerBehavior = ODataReaderBehavior.DefaultBehavior;
this.MaxProtocolVersion = ODataConstants.ODataDefaultProtocolVersion;
this.EnableAtom = false;
this.EnableFullValidation = true;
this.UseKeyAsSegment = null;
this.mediaTypeResolver = null;
}
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.OData.Core.ODataMessageReaderSettings" /> class.</summary>
/// <param name="other">The other message reader settings.</param>
public ODataMessageReaderSettings(ODataMessageReaderSettings other)
: base(other)
{
ExceptionUtils.CheckArgumentNotNull(other, "other");
this.BaseUri = other.BaseUri;
this.DisableMessageStreamDisposal = other.DisableMessageStreamDisposal;
this.DisablePrimitiveTypeConversion = other.DisablePrimitiveTypeConversion;
this.UndeclaredPropertyBehaviorKinds = other.UndeclaredPropertyBehaviorKinds;
this.MaxProtocolVersion = other.MaxProtocolVersion;
// NOTE: reader behavior is immutable; copy by reference is ok.
this.readerBehavior = other.ReaderBehavior;
this.EnableAtom = other.EnableAtom;
this.EnableFullValidation = other.EnableFullValidation;
this.UseKeyAsSegment = other.UseKeyAsSegment;
this.mediaTypeResolver = other.mediaTypeResolver;
}
/// <summary>
/// Gets or sets the document base URI (used as base for all relative URIs). If this is set, it must be an absolute URI.
/// ODataMessageReaderSettings.BaseUri may be deprecated in the furture, please use ODataMessageReaderSettings.PayloadBaseUri instead.
/// </summary>
/// <returns>The base URI used in payload.</returns>
/// <remarks>
/// This URI will be used in ATOM format only, it would overrided by <xml:base /> element in ATOM payload.
/// If the URI does not end with a slash, a slash would be appended automatically.
/// </remarks>
public Uri BaseUri
{
get
{
return payloadBaseUri;
}
set
{
this.payloadBaseUri = UriUtils.EnsureTaillingSlash(value);
}
}
/// <summary>Gets or sets the document base URI (used as base for all relative URIs). If this is set, it must be an absolute URI.</summary>
/// <returns>The base URI used in payload.</returns>
/// <remarks>
/// This URI will be used in ATOM format only, it would overrided by <xml:base /> element in ATOM payload.
/// If the URI does not end with a slash, a slash would be appended automatically.
/// </remarks>
public Uri PayloadBaseUri
{
get
{
return payloadBaseUri;
}
set
{
this.payloadBaseUri = UriUtils.EnsureTaillingSlash(value);
}
}
/// <summary>Gets or sets a value that indicates whether not to convert all primitive values to the type specified in the model or provided as an expected type. Note that values will still be converted to the type specified in the payload itself.</summary>
/// <returns>true if primitive values and report values are not converted; false if all primitive values are converted to the type specified in the model or provided as an expected type. The default value is false.</returns>
public bool DisablePrimitiveTypeConversion
{
get;
set;
}
/// <summary>Gets or sets the behavior the reader should use when it finds undeclared property.</summary>
/// <returns>The behavior the reader should use when it finds undeclared property.</returns>
/// <remarks>
/// This setting has no effect if there's no model specified for the reader.
/// This setting must be set to Default when reading request payloads.
///
/// Detailed behavior description:
/// ODataUndeclaredPropertyBehaviorKind.Default
/// If an undeclared property is found reading fails.
///
/// ODataUndeclaredPropertyBehaviorKind.ReportUndeclaredLinkProperty
/// ATOM
/// - Undeclared deferred navigation link will be read and reported.
/// - Undeclared expanded navigation link will fail.
/// - Undeclared stream property link (both read and edit) will be read and reported.
/// - Undeclared association link will be read and reported.
/// - Undeclared properties inside m:properties fail.
/// Verbose JSON
/// - If an undeclared property is found a detection logic will run:
/// - __deferred value is found - the link will be read and reported as a deferred navigation link.
/// - __mediaresource value is found - the link will be read and reported as a stream property
/// - If nothing from the above matches the reading fails.
/// - Undeclared association links inside __metadata/properties will be read and reported.
/// JSON Light
/// - If an undeclared property is found a detection logic will run:
/// - The property has 'odata.navigationLink' or 'odata.associationLink' annotation on it and no value - it will be read as navigation/association link
/// - The property has 'odata.mediaEditLink', 'odata.mediaReadLink', 'odata.mediaContentType' or 'odata.mediaEtag' on it and no value
/// - it will be read as a stream property.
/// - Any other property (that is property with a value or property with no annotation mentioned above) will fail.
///
/// ODataUndeclaredPropertyBehaviorKind.IgnoreUndeclaredValueProperty
/// ATOM
/// - Undeclared property inside m:properties is ignored (not even read).
/// - Undeclared navigation link, stream property link or association link fail.
/// Verbose JSON
/// - If an undeclared property is found a detection logic will run:
/// - __deferred value is found - fail as undeclared deferred nav. link.
/// - __mediaresource value is found - fail as undeclared stream property.
/// - All other properties are ignored and not read.
/// - Undeclared association links inside __metadata/properties fail.
/// JSON Light
/// - If an undeclared property is found a detection logic will run:
/// - The property has 'odata.navigationLink' or 'odata.associationLink' annotation on it (deferred or expanded navigation link)
/// - fail as undeclared navigation property
/// - The property has 'odata.mediaEditLink', 'odata.mediaReadLink', 'odata.mediaContentType' or 'odata.mediaEtag' on it and no value
/// - fail as undeclared stream property.
/// - The property has a value and no annotation mentioned above - the property is ignored and not read.
///
/// ODataUndeclaredPropertyBehaviorKind.ReportUndeclaredLinkProperty | ODataUndeclaredPropertyBehaviorKind.IgnoreUndeclaredValueProperty
/// ATOM
/// - Undeclared deferred navigation link will be read and reported.
/// - Undeclared expanded navigation link will be read and the navigation link part will be reported,
/// the expanded content will be ignored and not read or reported.
/// - Undeclared stream property link (both read and edit) will be read and reported.
/// - Undeclared association link will be read and reported.
/// - Undeclared properties inside m:properties will be ignored and not read.
/// Verbose JSON
/// - If an undeclared property is found a detection logic will run:
/// - __deferred value is found - read and report a deferred navigation link.
/// - __mediaresource value is found - read and report stream property.
/// - All other properties are ignore and not read.
/// - Undeclared association links inside __metadata/properties are read and reported.
/// JSON Light
/// - If an undeclared property is found a detection logic will run:
/// - The property has 'odata.navigationLink' or 'odata.associationLink' annotation on it and no value (deferred navigation link)
/// - it will be read as navigation/association link
/// - The property has 'odata.navigationLink' or 'odata.associationLink' annotation on it and with value (expanded navigation link)
/// - it will be read, the navigation and association link will be reported and the content will be ignored.
/// - The property has 'odata.mediaEditLink', 'odata.mediaReadLink', 'odata.mediaContentType' or 'odata.mediaEtag' on it and no value
/// - it will be read as a stream property.
/// - The property has a value and no annotation mentioned above - the property is ignored and not read.
///
/// Note that there's one difference between ATOM/JSON Light and Verbose JSON. In ATOM and JSON Light expanded links are treated as both
/// undeclared link and a value property. The URLs are the link part, the expanded content is the value part.
/// In Verbose JSON expanded links are treated as a value property as a whole. Since in JSON expanded links don't actually have
/// the link part (the payload doesn't contain the "href") this is not such a big difference.
/// </remarks>
public ODataUndeclaredPropertyBehaviorKinds UndeclaredPropertyBehaviorKinds
{
get;
set;
}
/// <summary>Gets or sets a value that indicates whether the message stream will not be disposed after finishing writing with the message.</summary>
/// <returns>true if the message stream will not be disposed after finishing writing with the message; otherwise false. The default value is false.</returns>
public bool DisableMessageStreamDisposal
{
get;
set;
}
/// <summary>Gets or sets the maximum OData protocol version the reader should accept and understand.</summary>
/// <returns>The maximum OData protocol version the reader should accept and understand.</returns>
/// <remarks>
/// If the payload to be read has higher OData-Version than the value specified for this property
/// the reader will fail.
/// Reader will also not report features which require higher version than specified for this property.
/// It may either ignore such features in the payload or fail on them.
/// </remarks>
public ODataVersion MaxProtocolVersion
{
get;
set;
}
/// <summary>
/// If set to true, all the validation would be enabled. Else some validation will be skipped.
/// Default to true.
/// </summary>
public bool EnableFullValidation { get; set; }
/// <summary>
/// Gets or sets a value that indicates whether the reader should put key values in their own URI segment when automatically building URIs.
/// If this value is false, automatically-generated URLs will take the form "../EntitySet('KeyValue')/..".
/// If this value is true, automatically-generated URLs will take the form "../EntitySet/KeyValue/..".
/// If this value is not set (null), decision will be made based on the "Com.Microsoft.OData.Service.Conventions.V1.UrlConventions" vocabulary
/// annotation on the IEdmEntityContainer, if available. The default behavior is to put key values inside parentheses and not a distinct URL segments.
/// This setting only applies to URLs that are automatically generated by the <see cref="ODataMessageReader" /> and the URLs explicitly provided by the server won't be modified.
/// </summary>
public bool? UseKeyAsSegment
{
get;
set;
}
/// <summary>
/// The media type resolver to use when interpreting the incoming content type.
/// </summary>
public ODataMediaTypeResolver MediaTypeResolver
{
get
{
if (this.mediaTypeResolver == null)
{
this.mediaTypeResolver = ODataMediaTypeResolver.GetMediaTypeResolver(this.EnableAtom);
}
return this.mediaTypeResolver;
}
set
{
ExceptionUtils.CheckArgumentNotNull(value, "MediaTypeResolver");
this.mediaTypeResolver = value;
}
}
/// <summary>
/// false - metadata validation is strict, the input must exactly match against the model.
/// true - metadata validation is lax, the input doesn't have to match the model in all cases.
/// This property has effect only if the metadata model is specified.
/// </summary>
/// <remarks>
/// Strict metadata validation:
/// Primitive values: The wire type must be convertible to the expected type.
/// Complex values: The wire type must resolve against the model and it must exactly match the expected type.
/// Entities: The wire type must resolve against the model and it must be assignable to the expected type.
/// Collections: The wire type must exactly match the expected type.
/// If no expected type is available we use the payload type.
/// Lax metadata validation:
/// Primitive values: If expected type is available, we ignore the wire type.
/// Complex values: The wire type is used if the model defines it. If the model doesn't define such a type, the expected type is used.
/// If the wire type is not equal to the expected type, but it's assignable, we fail because we don't support complex type inheritance.
/// If the wire type if not assignable we use the expected type.
/// Entities: same as complex values except that if the payload type is assignable we use the payload type. This allows derived entity types.
/// Collections: If expected type is available, we ignore the wire type, except we fail if the item type is a derived complex type.
/// If no expected type is available we use the payload type and it must resolve against the model.
/// If DisablePrimitiveTypeConversion is on, the rules for primitive values don't apply
/// and the primitive values are always read with the type from the wire.
/// </remarks>
internal bool DisableStrictMetadataValidation
{
get
{
return this.ReaderBehavior.ApiBehaviorKind == ODataBehaviorKind.ODataServer || this.ReaderBehavior.ApiBehaviorKind == ODataBehaviorKind.WcfDataServicesClient;
}
}
/// <summary>
/// The reader behavior that holds all the knobs needed to make the reader
/// behave differently inside and outside of WCF Data Services.
/// </summary>
internal ODataReaderBehavior ReaderBehavior
{
get
{
return this.readerBehavior;
}
}
/// <summary>
/// Whether or not to report any undeclared link properties in the payload. Computed from the UndeclaredPropertyBehaviorKinds enum property.
/// </summary>
internal bool ReportUndeclaredLinkProperties
{
get
{
return this.UndeclaredPropertyBehaviorKinds.HasFlag(ODataUndeclaredPropertyBehaviorKinds.ReportUndeclaredLinkProperty);
}
}
/// <summary>
/// Whether or not to ignore any undeclared value properties in the payload. Computed from the UndeclaredPropertyBehaviorKinds enum property.
/// </summary>
internal bool IgnoreUndeclaredValueProperties
{
get
{
return this.UndeclaredPropertyBehaviorKinds.HasFlag(ODataUndeclaredPropertyBehaviorKinds.IgnoreUndeclaredValueProperty);
}
}
/// <summary>
/// Whether ATOM support is enabled.
/// </summary>
internal bool EnableAtom { get; set; }
/// <summary>Enables the default behavior.</summary>
public void EnableDefaultBehavior()
{
// We have to reset the ATOM entry XML customization since in the default behavior no atom entry customization is used.
this.readerBehavior = ODataReaderBehavior.DefaultBehavior;
}
/// <summary>Specifies whether the OData server behavior is enabled.</summary>
public void EnableODataServerBehavior()
{
// We have to reset the ATOM entry XML customization since in the server behavior no atom entry customization is used.
this.readerBehavior = ODataReaderBehavior.CreateWcfDataServicesServerBehavior();
}
/// <summary>
/// Enables the same behavior that the WCF Data Services client has. Also, lets the user set the values for custom data namespace and type scheme.
/// </summary>
/// <param name="typeResolver">Custom type resolver which takes both expected type and type name.
/// This function is used instead of the IEdmModel.FindType if it's specified.
/// The first parameter to the function is the expected type (the type inferred from the parent property or specified by the external caller).
/// The second parameter is the type name from the payload.
/// The function should return the resolved type, or null if no such type was found.</param>
public void EnableWcfDataServicesClientBehavior(Func<IEdmType, string, IEdmType> typeResolver)
{
this.readerBehavior = ODataReaderBehavior.CreateWcfDataServicesClientBehavior(typeResolver);
}
/// <summary>
/// Returns true to indicate that the annotation with the name <paramref name="annotationName"/> should be skipped, false otherwise.
/// </summary>
/// <param name="annotationName">The name of the annotation in question.</param>
/// <returns>Returns true to indicate that the annotation with the name <paramref name="annotationName"/> should be skipped, false otherwise.</returns>
internal bool ShouldSkipAnnotation(string annotationName)
{
return this.ShouldIncludeAnnotation == null || !this.ShouldIncludeAnnotation(annotationName);
}
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Xml
{
internal partial class XmlWellFormedWriter : XmlWriter
{
//
// Private types
//
private class NamespaceResolverProxy : IXmlNamespaceResolver
{
private XmlWellFormedWriter _wfWriter;
internal NamespaceResolverProxy(XmlWellFormedWriter wfWriter)
{
_wfWriter = wfWriter;
}
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
throw new NotImplementedException();
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return _wfWriter.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _wfWriter.LookupPrefix(namespaceName);
}
}
private partial struct ElementScope
{
internal int prevNSTop;
internal string prefix;
internal string localName;
internal string namespaceUri;
internal XmlSpace xmlSpace;
internal string xmlLang;
internal void Set(string prefix, string localName, string namespaceUri, int prevNSTop)
{
this.prevNSTop = prevNSTop;
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.localName = localName;
this.xmlSpace = (System.Xml.XmlSpace)(int)-1;
this.xmlLang = null;
}
internal void WriteEndElement(XmlRawWriter rawWriter)
{
rawWriter.WriteEndElement(prefix, localName, namespaceUri);
}
internal void WriteFullEndElement(XmlRawWriter rawWriter)
{
rawWriter.WriteFullEndElement(prefix, localName, namespaceUri);
}
}
private enum NamespaceKind
{
Written,
NeedToWrite,
Implied,
Special,
}
private partial struct Namespace
{
internal string prefix;
internal string namespaceUri;
internal NamespaceKind kind;
internal int prevNsIndex;
internal void Set(string prefix, string namespaceUri, NamespaceKind kind)
{
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.kind = kind;
this.prevNsIndex = -1;
}
internal void WriteDecl(XmlWriter writer, XmlRawWriter rawWriter)
{
Debug.Assert(kind == NamespaceKind.NeedToWrite);
if (null != rawWriter)
{
rawWriter.WriteNamespaceDeclaration(prefix, namespaceUri);
}
else
{
if (prefix.Length == 0)
{
writer.WriteStartAttribute(string.Empty, "xmlns", XmlReservedNs.NsXmlNs);
}
else
{
writer.WriteStartAttribute("xmlns", prefix, XmlReservedNs.NsXmlNs);
}
writer.WriteString(namespaceUri);
writer.WriteEndAttribute();
}
}
}
private struct AttrName
{
internal string prefix;
internal string namespaceUri;
internal string localName;
internal int prev;
internal void Set(string prefix, string localName, string namespaceUri)
{
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.localName = localName;
this.prev = 0;
}
internal bool IsDuplicate(string prefix, string localName, string namespaceUri)
{
return ((this.localName == localName)
&& ((this.prefix == prefix) || (this.namespaceUri == namespaceUri)));
}
}
private enum SpecialAttribute
{
No = 0,
DefaultXmlns,
PrefixedXmlns,
XmlSpace,
XmlLang
}
private partial class AttributeValueCache
{
private enum ItemType
{
EntityRef,
CharEntity,
SurrogateCharEntity,
Whitespace,
String,
StringChars,
Raw,
RawChars,
ValueString,
}
private class Item
{
internal ItemType type;
internal object data;
internal Item() { }
internal void Set(ItemType type, object data)
{
this.type = type;
this.data = data;
}
}
private class BufferChunk
{
internal char[] buffer;
internal int index;
internal int count;
internal BufferChunk(char[] buffer, int index, int count)
{
this.buffer = buffer;
this.index = index;
this.count = count;
}
}
private StringBuilder _stringValue = new StringBuilder();
private string _singleStringValue; // special-case for a single WriteString call
private Item[] _items;
private int _firstItem;
private int _lastItem = -1;
internal string StringValue
{
get
{
if (_singleStringValue != null)
{
return _singleStringValue;
}
else
{
return _stringValue.ToString();
}
}
}
internal void WriteEntityRef(string name)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
switch (name)
{
case "lt":
_stringValue.Append('<');
break;
case "gt":
_stringValue.Append('>');
break;
case "quot":
_stringValue.Append('"');
break;
case "apos":
_stringValue.Append('\'');
break;
case "amp":
_stringValue.Append('&');
break;
default:
_stringValue.Append('&');
_stringValue.Append(name);
_stringValue.Append(';');
break;
}
AddItem(ItemType.EntityRef, name);
}
internal void WriteCharEntity(char ch)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(ch);
AddItem(ItemType.CharEntity, ch);
}
internal void WriteSurrogateCharEntity(char lowChar, char highChar)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(highChar);
_stringValue.Append(lowChar);
AddItem(ItemType.SurrogateCharEntity, new char[] { lowChar, highChar });
}
internal void WriteWhitespace(string ws)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(ws);
AddItem(ItemType.Whitespace, ws);
}
internal void WriteString(string text)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
else
{
// special-case for a single WriteString
if (_lastItem == -1)
{
_singleStringValue = text;
return;
}
}
_stringValue.Append(text);
AddItem(ItemType.String, text);
}
internal void WriteChars(char[] buffer, int index, int count)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(buffer, index, count);
AddItem(ItemType.StringChars, new BufferChunk(buffer, index, count));
}
internal void WriteRaw(char[] buffer, int index, int count)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(buffer, index, count);
AddItem(ItemType.RawChars, new BufferChunk(buffer, index, count));
}
internal void WriteRaw(string data)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(data);
AddItem(ItemType.Raw, data);
}
internal void WriteValue(string value)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(value);
AddItem(ItemType.ValueString, value);
}
internal void Replay(XmlWriter writer)
{
if (_singleStringValue != null)
{
writer.WriteString(_singleStringValue);
return;
}
BufferChunk bufChunk;
for (int i = _firstItem; i <= _lastItem; i++)
{
Item item = _items[i];
switch (item.type)
{
case ItemType.EntityRef:
writer.WriteEntityRef((string)item.data);
break;
case ItemType.CharEntity:
writer.WriteCharEntity((char)item.data);
break;
case ItemType.SurrogateCharEntity:
char[] chars = (char[])item.data;
writer.WriteSurrogateCharEntity(chars[0], chars[1]);
break;
case ItemType.Whitespace:
writer.WriteWhitespace((string)item.data);
break;
case ItemType.String:
writer.WriteString((string)item.data);
break;
case ItemType.StringChars:
bufChunk = (BufferChunk)item.data;
writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count);
break;
case ItemType.Raw:
writer.WriteRaw((string)item.data);
break;
case ItemType.RawChars:
bufChunk = (BufferChunk)item.data;
writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count);
break;
case ItemType.ValueString:
writer.WriteValue((string)item.data);
break;
default:
Debug.Fail("Unexpected ItemType value.");
break;
}
}
}
// This method trims whitespace from the beginning and the end of the string and cached writer events
internal void Trim()
{
// if only one string value -> trim the write spaces directly
if (_singleStringValue != null)
{
_singleStringValue = XmlConvert.TrimString(_singleStringValue);
return;
}
// trim the string in StringBuilder
string valBefore = _stringValue.ToString();
string valAfter = XmlConvert.TrimString(valBefore);
if (valBefore != valAfter)
{
_stringValue = new StringBuilder(valAfter);
}
// trim the beginning of the recorded writer events
XmlCharType xmlCharType = XmlCharType.Instance;
int i = _firstItem;
while (i == _firstItem && i <= _lastItem)
{
Item item = _items[i];
switch (item.type)
{
case ItemType.Whitespace:
_firstItem++;
break;
case ItemType.String:
case ItemType.Raw:
case ItemType.ValueString:
item.data = XmlConvert.TrimStringStart((string)item.data);
if (((string)item.data).Length == 0)
{
// no characters left -> move the firstItem index to exclude it from the Replay
_firstItem++;
}
break;
case ItemType.StringChars:
case ItemType.RawChars:
BufferChunk bufChunk = (BufferChunk)item.data;
int endIndex = bufChunk.index + bufChunk.count;
while (bufChunk.index < endIndex && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index]))
{
bufChunk.index++;
bufChunk.count--;
}
if (bufChunk.index == endIndex)
{
// no characters left -> move the firstItem index to exclude it from the Replay
_firstItem++;
}
break;
}
i++;
}
// trim the end of the recorded writer events
i = _lastItem;
while (i == _lastItem && i >= _firstItem)
{
Item item = _items[i];
switch (item.type)
{
case ItemType.Whitespace:
_lastItem--;
break;
case ItemType.String:
case ItemType.Raw:
case ItemType.ValueString:
item.data = XmlConvert.TrimStringEnd((string)item.data);
if (((string)item.data).Length == 0)
{
// no characters left -> move the lastItem index to exclude it from the Replay
_lastItem--;
}
break;
case ItemType.StringChars:
case ItemType.RawChars:
BufferChunk bufChunk = (BufferChunk)item.data;
while (bufChunk.count > 0 && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index + bufChunk.count - 1]))
{
bufChunk.count--;
}
if (bufChunk.count == 0)
{
// no characters left -> move the lastItem index to exclude it from the Replay
_lastItem--;
}
break;
}
i--;
}
}
internal void Clear()
{
_singleStringValue = null;
_lastItem = -1;
_firstItem = 0;
_stringValue.Length = 0;
}
private void StartComplexValue()
{
Debug.Assert(_singleStringValue != null);
Debug.Assert(_lastItem == -1);
_stringValue.Append(_singleStringValue);
AddItem(ItemType.String, _singleStringValue);
_singleStringValue = null;
}
private void AddItem(ItemType type, object data)
{
int newItemIndex = _lastItem + 1;
if (_items == null)
{
_items = new Item[4];
}
else if (_items.Length == newItemIndex)
{
Item[] newItems = new Item[newItemIndex * 2];
Array.Copy(_items, 0, newItems, 0, newItemIndex);
_items = newItems;
}
if (_items[newItemIndex] == null)
{
_items[newItemIndex] = new Item();
}
_items[newItemIndex].Set(type, data);
_lastItem = newItemIndex;
}
}
}
}
| |
/*(c) Copyright 2012, VersionOne, Inc. All rights reserved. (c)*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using VersionOne.SDK.APIClient;
using VersionOne.ServiceHost.Eventing;
using VersionOne.Profile;
using VersionOne.ServiceHost.Core.Configuration;
using VersionOne.ServiceHost.Core.Logging;
namespace VersionOne.ServiceHost.Core.Services
{
// TODO apply ServerConnector
public abstract class V1WriterServiceBase : IHostedService
{
private IServices services;
protected XmlElement Config;
protected IEventManager EventManager;
protected ILogger Logger;
private const string MemberType = "Member";
private const string DefaultRoleNameProperty = "DefaultRole.Name";
protected virtual IServices Services
{
get
{
if (services == null)
{
try
{
var settings = VersionOneSettings.FromXmlElement(Config);
var connector = V1Connector
.WithInstanceUrl(settings.Url)
.WithUserAgentHeader("VersionOne.Integration.JIRASync", Assembly.GetEntryAssembly().GetName().Version.ToString());
ICanSetProxyOrEndpointOrGetConnector connectorWithAuth;
connectorWithAuth = connector.WithAccessToken(settings.AccessToken);
if (settings.ProxySettings.Enabled)
connectorWithAuth.WithProxy(
new ProxyProvider(
new Uri(settings.ProxySettings.Url), settings.ProxySettings.Username, settings.ProxySettings.Password, settings.ProxySettings.Domain));
services = new SDK.APIClient.Services(connectorWithAuth.UseOAuthEndpoints().Build());
if (!services.LoggedIn.IsNull)
LogVersionOneConnectionInformation();
}
catch (Exception ex)
{
Logger.Log("Failed to connect to VersionOne server", ex);
throw;
}
}
return services;
}
}
private void LogVersionOneConnectionInformation()
{
try
{
var metaVersion = ((MetaModel)Services.Meta).Version.ToString();
var memberOid = Services.LoggedIn.Momentless.ToString();
var defaultRole = GetLoggedInMemberRole();
Logger.LogVersionOneConnectionInformation(LogMessage.SeverityType.Info, metaVersion, memberOid, defaultRole);
}
catch (Exception ex)
{
Logger.Log(LogMessage.SeverityType.Warning, "Failed to log VersionOne connection information.", ex);
}
}
private string GetLoggedInMemberRole()
{
var query = new Query(Services.LoggedIn);
var defaultRoleAttribute = Services.Meta.GetAssetType(MemberType).GetAttributeDefinition(DefaultRoleNameProperty);
query.Selection.Add(defaultRoleAttribute);
return Services.Localization(defaultRoleAttribute);
}
public virtual void Initialize(XmlElement config, IEventManager eventManager, IProfile profile)
{
Config = config;
EventManager = eventManager;
Logger = new Logger(eventManager);
Logger.LogVersionOneConfiguration(LogMessage.SeverityType.Info, Config["Settings"]);
}
public void Start()
{
// TODO move subscriptions to timer events, etc. here
}
protected abstract IEnumerable<NeededAssetType> NeededAssetTypes { get; }
protected void VerifyMeta()
{
try
{
VerifyNeededMeta(NeededAssetTypes);
VerifyRuntimeMeta();
}
catch (MetaException ex)
{
throw new ApplicationException("Necessary meta is not present in this VersionOne system", ex);
}
}
protected virtual void VerifyRuntimeMeta()
{
}
protected struct NeededAssetType
{
public readonly string Name;
public readonly string[] AttributeDefinitionNames;
public NeededAssetType(string name, string[] attributedefinitionnames)
{
Name = name;
AttributeDefinitionNames = attributedefinitionnames;
}
}
protected void VerifyNeededMeta(IEnumerable<NeededAssetType> neededassettypes)
{
foreach (var neededAssetType in neededassettypes)
{
var assettype = Services.Meta.GetAssetType(neededAssetType.Name);
foreach (var attributeDefinitionName in neededAssetType.AttributeDefinitionNames)
{
var attribdef = assettype.GetAttributeDefinition(attributeDefinitionName);
}
}
}
#region Meta wrappers
protected IAssetType RequestType
{
get { return Services.Meta.GetAssetType("Request"); }
}
protected IAssetType DefectType
{
get { return Services.Meta.GetAssetType("Defect"); }
}
protected IAssetType StoryType
{
get { return Services.Meta.GetAssetType("Story"); }
}
protected IAssetType ReleaseVersionType
{
get { return Services.Meta.GetAssetType("StoryCategory"); }
}
protected IAssetType LinkType
{
get { return Services.Meta.GetAssetType("Link"); }
}
protected IAssetType NoteType
{
get { return Services.Meta.GetAssetType("Note"); }
}
protected IAttributeDefinition DefectName
{
get { return DefectType.GetAttributeDefinition("Name"); }
}
protected IAttributeDefinition DefectDescription
{
get { return DefectType.GetAttributeDefinition("Description"); }
}
protected IAttributeDefinition DefectOwners
{
get { return DefectType.GetAttributeDefinition("Owners"); }
}
protected IAttributeDefinition DefectScope
{
get { return DefectType.GetAttributeDefinition("Scope"); }
}
protected IAttributeDefinition DefectAssetState
{
get { return RequestType.GetAttributeDefinition("AssetState"); }
}
protected IAttributeDefinition RequestCompanyName
{
get { return RequestType.GetAttributeDefinition("Name"); }
}
protected IAttributeDefinition RequestNumber
{
get { return RequestType.GetAttributeDefinition("Number"); }
}
protected IAttributeDefinition RequestSuggestedInstance
{
get { return RequestType.GetAttributeDefinition("Reference"); }
}
protected IAttributeDefinition RequestMethodology
{
get { return RequestType.GetAttributeDefinition("Source"); }
}
protected IAttributeDefinition RequestMethodologyName
{
get { return RequestType.GetAttributeDefinition("Source.Name"); }
}
protected IAttributeDefinition RequestCommunityEdition
{
get { return RequestType.GetAttributeDefinition("Custom_CommunityEdition"); }
}
protected IAttributeDefinition RequestAssetState
{
get { return RequestType.GetAttributeDefinition("AssetState"); }
}
protected IAttributeDefinition RequestCreateDate
{
get { return RequestType.GetAttributeDefinition("CreateDate"); }
}
protected IAttributeDefinition RequestCreatedBy
{
get { return RequestType.GetAttributeDefinition("CreatedBy"); }
}
protected IOperation RequestInactivate
{
get { return Services.Meta.GetOperation("Request.Inactivate"); }
}
protected IAttributeDefinition StoryName
{
get { return StoryType.GetAttributeDefinition("Name"); }
}
protected IAttributeDefinition StoryActualInstance
{
get { return StoryType.GetAttributeDefinition("Reference"); }
}
protected IAttributeDefinition StoryRequests
{
get { return StoryType.GetAttributeDefinition("Requests"); }
}
protected IAttributeDefinition StoryReleaseVersion
{
get { return StoryType.GetAttributeDefinition("Category"); }
}
protected IAttributeDefinition StoryMethodology
{
get { return StoryType.GetAttributeDefinition("Source"); }
}
protected IAttributeDefinition StoryCommunitySite
{
get { return StoryType.GetAttributeDefinition("Custom_CommunitySite"); }
}
protected IAttributeDefinition StoryScope
{
get { return StoryType.GetAttributeDefinition("Scope"); }
}
protected IAttributeDefinition StoryOwners
{
get { return StoryType.GetAttributeDefinition("Owners"); }
}
protected IAttributeDefinition ReleaseVersionName
{
get { return ReleaseVersionType.GetAttributeDefinition("Name"); }
}
protected IAttributeDefinition LinkAsset
{
get { return LinkType.GetAttributeDefinition("Asset"); }
}
protected IAttributeDefinition LinkOnMenu
{
get { return LinkType.GetAttributeDefinition("OnMenu"); }
}
protected IAttributeDefinition LinkUrl
{
get { return LinkType.GetAttributeDefinition("URL"); }
}
protected IAttributeDefinition LinkName
{
get { return LinkType.GetAttributeDefinition("Name"); }
}
protected IAttributeDefinition NoteName
{
get { return NoteType.GetAttributeDefinition("Name"); }
}
protected IAttributeDefinition NoteAsset
{
get { return NoteType.GetAttributeDefinition("Asset"); }
}
protected IAttributeDefinition NotePersonal
{
get { return NoteType.GetAttributeDefinition("Personal"); }
}
protected IAttributeDefinition NoteContent
{
get { return NoteType.GetAttributeDefinition("Content"); }
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using NUnit.Framework.Constraints;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
/// <summary>
/// Delegate used by tests that execute code and
/// capture any thrown exception.
/// </summary>
public delegate void TestDelegate();
#if ASYNC
/// <summary>
/// Delegate used by tests that execute async code and
/// capture any thrown exception.
/// </summary>
public delegate System.Threading.Tasks.Task AsyncTestDelegate();
#endif
/// <summary>
/// The Assert class contains a collection of static methods that
/// implement the most common assertions used in NUnit.
/// </summary>
public partial class Assert
{
#region Constructor
/// <summary>
/// We don't actually want any instances of this object, but some people
/// like to inherit from it to add other static methods. Hence, the
/// protected constructor disallows any instances of this object.
/// </summary>
protected Assert() { }
#endregion
#region Equals and ReferenceEquals
/// <summary>
/// DO NOT USE! Use Assert.AreEqual(...) instead.
/// The Equals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool Equals(object a, object b)
{
throw new InvalidOperationException("Assert.Equals should not be used for Assertions, use Assert.AreEqual(...) instead.");
}
/// <summary>
/// DO NOT USE!
/// The ReferenceEquals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new void ReferenceEquals(object a, object b)
{
throw new InvalidOperationException("Assert.ReferenceEquals should not be used for Assertions, use Assert.AreSame(...) instead.");
}
#endregion
#region Pass
/// <summary>
/// Throws a <see cref="SuccessException"/> with the message and arguments
/// that are passed in. This allows a test to be cut short, with a result
/// of success returned to NUnit.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Pass(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
// If we are in a multiple assert block, this is an error
if (TestExecutionContext.CurrentContext.MultipleAssertLevel > 0)
throw new Exception("Assert.Pass may not be used in a multiple assertion block.");
throw new SuccessException(message);
}
/// <summary>
/// Throws a <see cref="SuccessException"/> with the message and arguments
/// that are passed in. This allows a test to be cut short, with a result
/// of success returned to NUnit.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
static public void Pass(string message)
{
Assert.Pass(message, null);
}
/// <summary>
/// Throws a <see cref="SuccessException"/> with the message and arguments
/// that are passed in. This allows a test to be cut short, with a result
/// of success returned to NUnit.
/// </summary>
static public void Pass()
{
Assert.Pass(string.Empty, null);
}
#endregion
#region Fail
/// <summary>
/// Throws an <see cref="AssertionException"/> with the message and arguments
/// that are passed in. This is used by the other Assert functions.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Fail(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
ReportFailure(message);
}
/// <summary>
/// Throws an <see cref="AssertionException"/> with the message that is
/// passed in. This is used by the other Assert functions.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
static public void Fail(string message)
{
Assert.Fail(message, null);
}
/// <summary>
/// Throws an <see cref="AssertionException"/>.
/// This is used by the other Assert functions.
/// </summary>
static public void Fail()
{
Assert.Fail(string.Empty, null);
}
#endregion
#region Warn
/// <summary>
/// Issues a warning using the message and arguments provided.
/// </summary>
/// <param name="message">The message to display.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Warn(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
IssueWarning(message);
}
/// <summary>
/// Issues a warning using the message provided.
/// </summary>
/// <param name="message">The message to display.</param>
static public void Warn(string message)
{
IssueWarning(message);
}
#endregion
#region Ignore
/// <summary>
/// Throws an <see cref="IgnoreException"/> with the message and arguments
/// that are passed in. This causes the test to be reported as ignored.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Ignore(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
// If we are in a multiple assert block, this is an error
if (TestExecutionContext.CurrentContext.MultipleAssertLevel > 0)
throw new Exception("Assert.Ignore may not be used in a multiple assertion block.");
throw new IgnoreException(message);
}
/// <summary>
/// Throws an <see cref="IgnoreException"/> with the message that is
/// passed in. This causes the test to be reported as ignored.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
static public void Ignore(string message)
{
Assert.Ignore(message, null);
}
/// <summary>
/// Throws an <see cref="IgnoreException"/>.
/// This causes the test to be reported as ignored.
/// </summary>
static public void Ignore()
{
Assert.Ignore(string.Empty, null);
}
#endregion
#region InConclusive
/// <summary>
/// Throws an <see cref="InconclusiveException"/> with the message and arguments
/// that are passed in. This causes the test to be reported as inconclusive.
/// </summary>
/// <param name="message">The message to initialize the <see cref="InconclusiveException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Inconclusive(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
// If we are in a multiple assert block, this is an error
if (TestExecutionContext.CurrentContext.MultipleAssertLevel > 0)
throw new Exception("Assert.Inconclusive may not be used in a multiple assertion block.");
throw new InconclusiveException(message);
}
/// <summary>
/// Throws an <see cref="InconclusiveException"/> with the message that is
/// passed in. This causes the test to be reported as inconclusive.
/// </summary>
/// <param name="message">The message to initialize the <see cref="InconclusiveException"/> with.</param>
static public void Inconclusive(string message)
{
Assert.Inconclusive(message, null);
}
/// <summary>
/// Throws an <see cref="InconclusiveException"/>.
/// This causes the test to be reported as Inconclusive.
/// </summary>
static public void Inconclusive()
{
Assert.Inconclusive(string.Empty, null);
}
#endregion
#region Contains
/// <summary>
/// Asserts that an object is contained in a collection.
/// </summary>
/// <param name="expected">The expected object</param>
/// <param name="actual">The collection to be examined</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Contains(object expected, ICollection actual, string message, params object[] args)
{
Assert.That(actual, new CollectionContainsConstraint(expected) ,message, args);
}
/// <summary>
/// Asserts that an object is contained in a collection.
/// </summary>
/// <param name="expected">The expected object</param>
/// <param name="actual">The collection to be examined</param>
public static void Contains(object expected, ICollection actual)
{
Assert.That(actual, new CollectionContainsConstraint(expected) ,null, null);
}
#endregion
#region Multiple
/// <summary>
/// Wraps code containing a series of assertions, which should all
/// be executed, even if they fail. Failed results are saved and
/// reported at the end of the code block.
/// </summary>
/// <param name="testDelegate">A TestDelegate to be executed in Multiple Assertion mode.</param>
public static void Multiple(TestDelegate testDelegate)
{
TestExecutionContext context = TestExecutionContext.CurrentContext;
Guard.OperationValid(context != null, "Assert.Multiple called outside of a valid TestExecutionContext");
context.MultipleAssertLevel++;
try
{
testDelegate();
}
finally
{
context.MultipleAssertLevel--;
}
if (context.MultipleAssertLevel == 0 && context.CurrentResult.PendingFailures > 0)
throw new MultipleAssertException();
}
#endregion
#region Helper Methods
private static void ReportFailure(ConstraintResult result, string message)
{
ReportFailure(result, message, null);
}
private static void ReportFailure(ConstraintResult result, string message, params object[] args)
{
MessageWriter writer = new TextMessageWriter(message, args);
result.WriteMessageTo(writer);
ReportFailure(writer.ToString());
}
private static void ReportFailure(string message)
{
// If we are outside any multiple assert block, then throw
if (TestExecutionContext.CurrentContext.MultipleAssertLevel == 0)
throw new AssertionException(message);
// Otherwise, just record the failure in an <assertion> element
var result = TestExecutionContext.CurrentContext.CurrentResult;
result.RecordAssertion(AssertionStatus.Failed, message, GetStackTrace());
}
private static void IssueWarning(string message)
{
var result = TestExecutionContext.CurrentContext.CurrentResult;
result.RecordAssertion(AssertionStatus.Warning, message, GetStackTrace());
}
// System.Environment.StackTrace puts extra entries on top of the stack, at least in some environments
private static StackFilter SystemEnvironmentFilter = new StackFilter(@" System\.Environment\.");
private static string GetStackTrace()
{
string stackTrace = null;
#if PORTABLE && !NETSTANDARD1_6
// TODO: This isn't actually working! Since we catch it right here,
// the stack trace only has one entry.
try
{
// Throw to get stack trace for recording the assertion
throw new Exception();
}
catch (Exception ex)
{
stackTrace = ex.StackTrace;
}
#else
stackTrace = SystemEnvironmentFilter.Filter(Environment.StackTrace);
#endif
return StackFilter.DefaultFilter.Filter(stackTrace);
}
private static void IncrementAssertCount()
{
TestExecutionContext.CurrentContext.IncrementAssertCount();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma warning disable 1591
using System.Collections.Generic;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive;
#if !NO_TPL
using System.Reactive.Threading.Tasks; // needed for doc comments
using System.Threading;
using System.Threading.Tasks;
#endif
/*
* Note: these methods just call methods in Observable.StandardSequenceOperators.cs
* in order to create the following method aliases:
*
* Map = Select
* FlatMap = SelectMany
* Filter = Where
*
*/
namespace System.Reactive.Observable.Aliases
{
public static class QueryLanguage
{
#region + Map +
/// <summary>
/// Projects each element of an observable sequence into a new form. Synonym for the method 'Select'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the elements in the result sequence, obtained by running the selector function for each element in the source sequence.</typeparam>
/// <param name="source">A sequence of elements to invoke a transform function on.</param>
/// <param name="selector">A transform function to apply to each source element.</param>
/// <returns>An observable sequence whose elements are the result of invoking the transform function on each element of source.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
public static IObservable<TResult> Map<TSource, TResult>(this IObservable<TSource> source, Func<TSource, TResult> selector)
{
return source.Select<TSource, TResult>(selector);
}
/// <summary>
/// Projects each element of an observable sequence into a new form by incorporating the element's index. Synonym for the method 'Select'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the elements in the result sequence, obtained by running the selector function for each element in the source sequence.</typeparam>
/// <param name="source">A sequence of elements to invoke a transform function on.</param>
/// <param name="selector">A transform function to apply to each source element; the second parameter of the function represents the index of the source element.</param>
/// <returns>An observable sequence whose elements are the result of invoking the transform function on each element of source.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
public static IObservable<TResult> Map<TSource, TResult>(this IObservable<TSource> source, Func<TSource, int, TResult> selector)
{
return source.Select<TSource, TResult>(selector);
}
#endregion
#region + FlatMap +
/// <summary>
/// Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TOther">The type of the elements in the other sequence and the elements in the result sequence.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="other">An observable sequence to project each element from the source sequence onto.</param>
/// <returns>An observable sequence whose elements are the result of projecting each source element onto the other sequence and merging all the resulting sequences together.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="other"/> is null.</exception>
public static IObservable<TOther> FlatMap<TSource, TOther>(this IObservable<TSource> source, IObservable<TOther> other)
{
return source.SelectMany<TSource, TOther>(other);
}
/// <summary>
/// Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the elements in the projected inner sequences and the elements in the merged result sequence.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
public static IObservable<TResult> FlatMap<TSource, TResult>(this IObservable<TSource> source, Func<TSource, IObservable<TResult>> selector)
{
return source.SelectMany<TSource, TResult>(selector);
}
/// <summary>
/// Projects each element of an observable sequence to an observable sequence by incorporating the element's index and merges the resulting observable sequences into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the elements in the projected inner sequences and the elements in the merged result sequence.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="selector">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
/// <returns>An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
public static IObservable<TResult> FlatMap<TSource, TResult>(this IObservable<TSource> source, Func<TSource, int, IObservable<TResult>> selector)
{
return source.SelectMany<TSource, TResult>(selector);
}
#if !NO_TPL
/// <summary>
/// Projects each element of an observable sequence to a task and merges all of the task results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the result produced by the projected tasks and the elements in the merged result sequence.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>An observable sequence whose elements are the result of the tasks executed for each element of the input sequence.</returns>
/// <remarks>This overload supports composition of observable sequences and tasks, without requiring manual conversion of the tasks to observable sequences using <see cref="TaskObservableExtensions.ToObservable<TResult>"/>.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
public static IObservable<TResult> FlatMap<TSource, TResult>(this IObservable<TSource> source, Func<TSource, Task<TResult>> selector)
{
return source.SelectMany<TSource, TResult>(selector);
}
/// <summary>
/// Projects each element of an observable sequence to a task by incorporating the element's index and merges all of the task results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the result produced by the projected tasks and the elements in the merged result sequence.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="selector">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
/// <returns>An observable sequence whose elements are the result of the tasks executed for each element of the input sequence.</returns>
/// <remarks>This overload supports composition of observable sequences and tasks, without requiring manual conversion of the tasks to observable sequences using <see cref="TaskObservableExtensions.ToObservable<TResult>"/>.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
public static IObservable<TResult> FlatMap<TSource, TResult>(this IObservable<TSource> source, Func<TSource, int, Task<TResult>> selector)
{
return source.SelectMany<TSource, TResult>(selector);
}
/// <summary>
/// Projects each element of an observable sequence to a task with cancellation support and merges all of the task results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the result produced by the projected tasks and the elements in the merged result sequence.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>An observable sequence whose elements are the result of the tasks executed for each element of the input sequence.</returns>
/// <remarks>This overload supports composition of observable sequences and tasks, without requiring manual conversion of the tasks to observable sequences using <see cref="TaskObservableExtensions.ToObservable<TResult>"/>.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
public static IObservable<TResult> FlatMap<TSource, TResult>(this IObservable<TSource> source, Func<TSource, CancellationToken, Task<TResult>> selector)
{
return source.SelectMany<TSource, TResult>(selector);
}
/// <summary>
/// Projects each element of an observable sequence to a task by incorporating the element's index with cancellation support and merges all of the task results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the result produced by the projected tasks and the elements in the merged result sequence.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="selector">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
/// <returns>An observable sequence whose elements are the result of the tasks executed for each element of the input sequence.</returns>
/// <remarks>This overload supports composition of observable sequences and tasks, without requiring manual conversion of the tasks to observable sequences using <see cref="TaskObservableExtensions.ToObservable<TResult>"/>.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
public static IObservable<TResult> FlatMap<TSource, TResult>(this IObservable<TSource> source, Func<TSource, int, CancellationToken, Task<TResult>> selector)
{
return source.SelectMany<TSource, TResult>(selector);
}
#endif
/// <summary>
/// Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TCollection">The type of the elements in the projected intermediate sequences.</typeparam>
/// <typeparam name="TResult">The type of the elements in the result sequence, obtained by using the selector to combine source sequence elements with their corresponding intermediate sequence elements.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="collectionSelector">A transform function to apply to each element.</param>
/// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence.</param>
/// <returns>An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="collectionSelector"/> or <paramref name="resultSelector"/> is null.</exception>
public static IObservable<TResult> FlatMap<TSource, TCollection, TResult>(this IObservable<TSource> source, Func<TSource, IObservable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
{
return source.SelectMany<TSource, TCollection, TResult>(collectionSelector, resultSelector);
}
/// <summary>
/// Projects each element of an observable sequence to an observable sequence by incorporating the element's index, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TCollection">The type of the elements in the projected intermediate sequences.</typeparam>
/// <typeparam name="TResult">The type of the elements in the result sequence, obtained by using the selector to combine source sequence elements with their corresponding intermediate sequence elements.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="collectionSelector">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
/// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence; the second parameter of the function represents the index of the source element and the fourth parameter represents the index of the intermediate element.</param>
/// <returns>An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="collectionSelector"/> or <paramref name="resultSelector"/> is null.</exception>
public static IObservable<TResult> FlatMap<TSource, TCollection, TResult>(this IObservable<TSource> source, Func<TSource, int, IObservable<TCollection>> collectionSelector, Func<TSource, int, TCollection, int, TResult> resultSelector)
{
return source.SelectMany<TSource, TCollection, TResult>(collectionSelector, resultSelector);
}
#if !NO_TPL
/// <summary>
/// Projects each element of an observable sequence to a task, invokes the result selector for the source element and the task result, and merges the results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TTaskResult">The type of the results produced by the projected intermediate tasks.</typeparam>
/// <typeparam name="TResult">The type of the elements in the result sequence, obtained by using the selector to combine source sequence elements with their corresponding intermediate task results.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="taskSelector">A transform function to apply to each element.</param>
/// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence.</param>
/// <returns>An observable sequence whose elements are the result of obtaining a task for each element of the input sequence and then mapping the task's result and its corresponding source element to a result element.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="taskSelector"/> or <paramref name="resultSelector"/> is null.</exception>
/// <remarks>This overload supports using LINQ query comprehension syntax in C# and Visual Basic to compose observable sequences and tasks, without requiring manual conversion of the tasks to observable sequences using <see cref="TaskObservableExtensions.ToObservable<TResult>"/>.</remarks>
public static IObservable<TResult> FlatMap<TSource, TTaskResult, TResult>(this IObservable<TSource> source, Func<TSource, Task<TTaskResult>> taskSelector, Func<TSource, TTaskResult, TResult> resultSelector)
{
return source.SelectMany<TSource, TTaskResult, TResult>(taskSelector, resultSelector);
}
/// <summary>
/// Projects each element of an observable sequence to a task by incorporating the element's index, invokes the result selector for the source element and the task result, and merges the results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TTaskResult">The type of the results produced by the projected intermediate tasks.</typeparam>
/// <typeparam name="TResult">The type of the elements in the result sequence, obtained by using the selector to combine source sequence elements with their corresponding intermediate task results.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="taskSelector">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
/// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence; the second parameter of the function represents the index of the source element.</param>
/// <returns>An observable sequence whose elements are the result of obtaining a task for each element of the input sequence and then mapping the task's result and its corresponding source element to a result element.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="taskSelector"/> or <paramref name="resultSelector"/> is null.</exception>
/// <remarks>This overload supports using LINQ query comprehension syntax in C# and Visual Basic to compose observable sequences and tasks, without requiring manual conversion of the tasks to observable sequences using <see cref="TaskObservableExtensions.ToObservable<TResult>"/>.</remarks>
public static IObservable<TResult> FlatMap<TSource, TTaskResult, TResult>(this IObservable<TSource> source, Func<TSource, int, Task<TTaskResult>> taskSelector, Func<TSource, int, TTaskResult, TResult> resultSelector)
{
return source.SelectMany<TSource, TTaskResult, TResult>(taskSelector, resultSelector);
}
/// <summary>
/// Projects each element of an observable sequence to a task with cancellation support, invokes the result selector for the source element and the task result, and merges the results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TTaskResult">The type of the results produced by the projected intermediate tasks.</typeparam>
/// <typeparam name="TResult">The type of the elements in the result sequence, obtained by using the selector to combine source sequence elements with their corresponding intermediate task results.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="taskSelector">A transform function to apply to each element.</param>
/// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence.</param>
/// <returns>An observable sequence whose elements are the result of obtaining a task for each element of the input sequence and then mapping the task's result and its corresponding source element to a result element.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="taskSelector"/> or <paramref name="resultSelector"/> is null.</exception>
/// <remarks>This overload supports using LINQ query comprehension syntax in C# and Visual Basic to compose observable sequences and tasks, without requiring manual conversion of the tasks to observable sequences using <see cref="TaskObservableExtensions.ToObservable<TResult>"/>.</remarks>
public static IObservable<TResult> FlatMap<TSource, TTaskResult, TResult>(this IObservable<TSource> source, Func<TSource, CancellationToken, Task<TTaskResult>> taskSelector, Func<TSource, TTaskResult, TResult> resultSelector)
{
return source.SelectMany<TSource, TTaskResult, TResult>(taskSelector, resultSelector);
}
/// <summary>
/// Projects each element of an observable sequence to a task by incorporating the element's index with cancellation support, invokes the result selector for the source element and the task result, and merges the results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TTaskResult">The type of the results produced by the projected intermediate tasks.</typeparam>
/// <typeparam name="TResult">The type of the elements in the result sequence, obtained by using the selector to combine source sequence elements with their corresponding intermediate task results.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="taskSelector">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
/// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence; the second parameter of the function represents the index of the source element.</param>
/// <returns>An observable sequence whose elements are the result of obtaining a task for each element of the input sequence and then mapping the task's result and its corresponding source element to a result element.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="taskSelector"/> or <paramref name="resultSelector"/> is null.</exception>
/// <remarks>This overload supports using LINQ query comprehension syntax in C# and Visual Basic to compose observable sequences and tasks, without requiring manual conversion of the tasks to observable sequences using <see cref="TaskObservableExtensions.ToObservable<TResult>"/>.</remarks>
public static IObservable<TResult> FlatMap<TSource, TTaskResult, TResult>(this IObservable<TSource> source, Func<TSource, int, CancellationToken, Task<TTaskResult>> taskSelector, Func<TSource, int, TTaskResult, TResult> resultSelector)
{
return source.SelectMany<TSource, TTaskResult, TResult>(taskSelector, resultSelector);
}
#endif
/// <summary>
/// Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the elements in the projected inner sequences and the elements in the merged result sequence.</typeparam>
/// <param name="source">An observable sequence of notifications to project.</param>
/// <param name="onNext">A transform function to apply to each element.</param>
/// <param name="onError">A transform function to apply when an error occurs in the source sequence.</param>
/// <param name="onCompleted">A transform function to apply when the end of the source sequence is reached.</param>
/// <returns>An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="onNext"/> or <paramref name="onError"/> or <paramref name="onCompleted"/> is null.</exception>
public static IObservable<TResult> FlatMap<TSource, TResult>(this IObservable<TSource> source, Func<TSource, IObservable<TResult>> onNext, Func<Exception, IObservable<TResult>> onError, Func<IObservable<TResult>> onCompleted)
{
return source.SelectMany<TSource, TResult>(onNext, onError, onCompleted);
}
/// <summary>
/// Projects each notification of an observable sequence to an observable sequence by incorporating the element's index and merges the resulting observable sequences into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the elements in the projected inner sequences and the elements in the merged result sequence.</typeparam>
/// <param name="source">An observable sequence of notifications to project.</param>
/// <param name="onNext">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
/// <param name="onError">A transform function to apply when an error occurs in the source sequence.</param>
/// <param name="onCompleted">A transform function to apply when the end of the source sequence is reached.</param>
/// <returns>An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="onNext"/> or <paramref name="onError"/> or <paramref name="onCompleted"/> is null.</exception>
public static IObservable<TResult> FlatMap<TSource, TResult>(this IObservable<TSource> source, Func<TSource, int, IObservable<TResult>> onNext, Func<Exception, IObservable<TResult>> onError, Func<IObservable<TResult>> onCompleted)
{
return source.SelectMany<TSource, TResult>(onNext, onError, onCompleted);
}
/// <summary>
/// Projects each element of an observable sequence to an enumerable sequence and concatenates the resulting enumerable sequences into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the elements in the projected inner enumerable sequences and the elements in the merged result sequence.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
/// <remarks>The projected sequences are enumerated synchonously within the OnNext call of the source sequence. In order to do a concurrent, non-blocking merge, change the selector to return an observable sequence obtained using the <see cref="Linq.Observable.ToObservable<TSource>(IEnumerable<TSource>)"/> conversion.</remarks>
public static IObservable<TResult> FlatMap<TSource, TResult>(this IObservable<TSource> source, Func<TSource, IEnumerable<TResult>> selector)
{
return source.SelectMany<TSource, TResult>(selector);
}
/// <summary>
/// Projects each element of an observable sequence to an enumerable sequence by incorporating the element's index and concatenates the resulting enumerable sequences into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TResult">The type of the elements in the projected inner enumerable sequences and the elements in the merged result sequence.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="selector">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
/// <returns>An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
/// <remarks>The projected sequences are enumerated synchonously within the OnNext call of the source sequence. In order to do a concurrent, non-blocking merge, change the selector to return an observable sequence obtained using the <see cref="Linq.Observable.ToObservable<TSource>(IEnumerable<TSource>)"/> conversion.</remarks>
public static IObservable<TResult> FlatMap<TSource, TResult>(this IObservable<TSource> source, Func<TSource, int, IEnumerable<TResult>> selector)
{
return source.SelectMany<TSource, TResult>(selector);
}
/// <summary>
/// Projects each element of an observable sequence to an enumerable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TCollection">The type of the elements in the projected intermediate enumerable sequences.</typeparam>
/// <typeparam name="TResult">The type of the elements in the result sequence, obtained by using the selector to combine source sequence elements with their corresponding intermediate sequence elements.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="collectionSelector">A transform function to apply to each element.</param>
/// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence.</param>
/// <returns>An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="collectionSelector"/> or <paramref name="resultSelector"/> is null.</exception>
/// <remarks>The projected sequences are enumerated synchonously within the OnNext call of the source sequence. In order to do a concurrent, non-blocking merge, change the selector to return an observable sequence obtained using the <see cref="Linq.Observable.ToObservable<TSource>(IEnumerable<TSource>)"/> conversion.</remarks>
public static IObservable<TResult> FlatMap<TSource, TCollection, TResult>(this IObservable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
{
return source.SelectMany<TSource, TCollection, TResult>(collectionSelector, resultSelector);
}
/// <summary>
/// Projects each element of an observable sequence to an enumerable sequence by incorporating the element's index, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
/// Synonym for the method 'SelectMany'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <typeparam name="TCollection">The type of the elements in the projected intermediate enumerable sequences.</typeparam>
/// <typeparam name="TResult">The type of the elements in the result sequence, obtained by using the selector to combine source sequence elements with their corresponding intermediate sequence elements.</typeparam>
/// <param name="source">An observable sequence of elements to project.</param>
/// <param name="collectionSelector">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
/// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence; the second parameter of the function represents the index of the source element and the fourth parameter represents the index of the intermediate element.</param>
/// <returns>An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="collectionSelector"/> or <paramref name="resultSelector"/> is null.</exception>
/// <remarks>The projected sequences are enumerated synchonously within the OnNext call of the source sequence. In order to do a concurrent, non-blocking merge, change the selector to return an observable sequence obtained using the <see cref="Linq.Observable.ToObservable<TSource>(IEnumerable<TSource>)"/> conversion.</remarks>
public static IObservable<TResult> FlatMap<TSource, TCollection, TResult>(this IObservable<TSource> source, Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, int, TCollection, int, TResult> resultSelector)
{
return source.SelectMany<TSource, TCollection, TResult>(collectionSelector, resultSelector);
}
#endregion
#region + Filter +
/// <summary>
/// Filters the elements of an observable sequence based on a predicate.
/// Synonym for the method 'Where'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <param name="source">An observable sequence whose elements to filter.</param>
/// <param name="predicate">A function to test each source element for a condition.</param>
/// <returns>An observable sequence that contains elements from the input sequence that satisfy the condition.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
public static IObservable<TSource> Filter<TSource>(this IObservable<TSource> source, Func<TSource, bool> predicate)
{
return source.Where<TSource>(predicate);
}
/// <summary>
/// Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
/// Synonym for the method 'Where'
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <param name="source">An observable sequence whose elements to filter.</param>
/// <param name="predicate">A function to test each source element for a conditio; the second parameter of the function represents the index of the source element.</param>
/// <returns>An observable sequence that contains elements from the input sequence that satisfy the condition.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
public static IObservable<TSource> Filter<TSource>(this IObservable<TSource> source, Func<TSource, int, bool> predicate)
{
return source.Where<TSource>(predicate);
}
#endregion
}
}
#pragma warning restore 1591
| |
using System.Collections.Generic;
using UnityEngine;
using Grouping;
using System.Security.Permissions;
using UnityEditor;
using System;
public class LaserEmitter : Entity
{
/// <summary>
/// The direction that laser is going to (not coming from).
/// For example: Right means the laser direction is left to right.
/// </summary>
private Direction direction;
public Material LaserMaterial;
public Color LaserColor;
public float LaserWidth;
public Direction Direction
{
get { return direction; }
set
{
direction = value;
switch (direction)
{
case Direction.Up:
spriteRenderer.sprite = EmitterUp;
break;
case Direction.Down:
spriteRenderer.sprite = EmitterDown;
break;
case Direction.Left:
spriteRenderer.sprite = EmitterLeft;
break;
case Direction.Right:
spriteRenderer.sprite = EmitterRight;
break;
}
}
}
private LineStripRenderer lineStrip;
public Sprite EmitterUp;
public Sprite EmitterDown;
public Sprite EmitterLeft;
public Sprite EmitterRight;
private int lastExplosiveID;
private static readonly Vector2 LaserPositionOffset = new Vector2(0, 0.3f);
public float LaserSpeed = 40;
//private List<Vector2> previousEndpoints;
public LaserEmitter()
{
direction = Direction.Down;
}
//private struct LaserHit
// Use this for initialization
protected override void Start()
{
base.Start();
lineStrip = new LineStripRenderer(this, LaserMaterial, LaserColor, LaserWidth);
GroupManager.main.group["To Level Over"].Add(this);
//previousEndpoints = new List<Vector2> { transform.position.xy() };
AddPrev(transform.position.xy());
}
//Hardcoded values for vertical laser facing upwards
private readonly static float wallOffset = -0.17f;
private readonly static float gateOffset = 0.16f;
private readonly static float doorOffset = 0.23f;
private readonly static float leverOffset = 0.13f;
private readonly static float trolleyOffset = -0.07f;
private readonly static float otherOffset = 0;
private readonly static float turretOffset = 0.24f;
private const int MaxEndpoints = 20;
int endpointSize = 0;
int offsetSize = 0;
int prevSize = 0;
private void AddPoint(Vector2 point) {
endpoints[endpointSize++] = point;
}
private void AddOffset(int offset) {
offsets[offsetSize++] = offset;
}
private void AddPrev(Vector2 point) {
prevPoints[prevSize++] = point;
}
private void SwapPoints() {
var temp = endpoints;
var tempSize = endpointSize;
endpoints = prevPoints;
endpointSize = prevSize;
prevPoints = temp;
prevSize = tempSize;
}
/// <summary>
/// The endpoints in the current update
/// </summary>
Vector2[] endpoints = new Vector2[MaxEndpoints];
int[] offsets = new int[MaxEndpoints];
/// <summary>
/// The endpoints from the previous update
/// </summary>
Vector2[] prevPoints = new Vector2[MaxEndpoints];
// Update is called once per frame
protected override void Update()
{
base.Update();
var currDirection = Direction;
var directionVector = currDirection.ToVector2();
var endpoint = transform.position.xy();
//Swap prev points with current endpoints
SwapPoints();
//Clear the endpoint and offset list
endpointSize = 0;
offsetSize = 0;
//Init
AddPoint(endpoint);
AddOffset(-1);
var movement = Time.deltaTime * LaserSpeed;
bool gorillaTape = true;
bool isMirror = false;
// Set max iteration 20 to avoid infinite reflection
for (var endpointIndex = 1; endpointIndex < MaxEndpoints; endpointIndex++)
{
var hit = Physics2D.Raycast(endpoint + directionVector, directionVector, 100); //TODO: change 100 to max level width
//Debug.Log(endpointIndex);
DebugExt.Assert(hit.collider != null);
if (hit.collider == null)
break; // for robustness
string hitName = hit.collider.name;
isMirror = hitName.StartsWith("Mirror");
var tPos = hit.collider.transform.position;
if (directionVector.x.IsZero())
{
//Adjust the hit point when hitting from below
if (directionVector.y > 0 && !isMirror) {
float offset = 0;
float dist;
if (hitName.StartsWith("Wall")) {
offset = wallOffset;
} else if (hitName.StartsWith("Gate")) {
offset = gateOffset;
} else if (hitName.StartsWith("Door")) {
offset = doorOffset;
} else if (hitName.StartsWith("Lever")) {
offset = leverOffset;
} else if (hitName.StartsWith("Trolley")) {
offset = trolleyOffset;
} else if (hitName.StartsWith("LaserEmitter")) {
if (hit.collider.gameObject.GetComponent<LaserEmitter>().direction != Direction.Down) {
offset = turretOffset;
}
} else {
offset = otherOffset;
}
//Fixes issue for when object is too close to the laser
//This assumes the object's collider is 1 unit high
if ((dist = tPos.y - endpoint.y) < 1.5f) {
offset -= 1.5f - dist;
}
endpoint.y = hit.point.y + offset;
//gorillaTape = hit.point;
} else {
endpoint.y = hit.collider.transform.position.y;
//Debug.Log("whoop-di-doo");
}
}
else
{
endpoint.x = hit.collider.transform.position.x;
}
Vector2? previousEndpoint = null;
if (endpointIndex >= prevSize)
{
previousEndpoint = endpoints[endpointIndex - 1];
}
else if (!endpoint.Equals(prevPoints[endpointIndex]))
{
previousEndpoint = prevPoints[endpointIndex];
var previousDirection = previousEndpoint.Value - prevPoints[endpointIndex - 1];
previousDirection.Normalize();
if (directionVector != previousDirection)
{
previousEndpoint = endpoints[endpointIndex - 1];
}
}
if (previousEndpoint.HasValue)
{
var newEndpoint = previousEndpoint.Value + movement * directionVector;
var diff = Vector2.Dot(endpoint - newEndpoint, directionVector);
if (diff > 0)
{
AddPoint(newEndpoint);
break;
}
movement += diff;
}
AddPoint(endpoint);
if (hit.transform.tag == "Player")
{
var player = hit.transform.GetComponent<PlayerController>();
if (player.IsAlive)
{
player.Die();
AudioManager.PlaySFX("Laser Hit");
}
break;
}
else if (isMirror)
{
var mirror = hit.collider.GetComponent<Mirror>();
if (mirror != null)
{
var oldDirection = currDirection;
currDirection = mirror.Reflect(currDirection);
var sortingOrderOffset = oldDirection == Direction.Down || currDirection == Direction.Up ? -1 : 1;
AddOffset(sortingOrderOffset);
directionVector = currDirection.ToVector2();
continue;
}
}
else if (hitName.StartsWith("Explosive"))
{
if (lastExplosiveID != hit.transform.GetInstanceID())
{
lastExplosiveID = hit.transform.GetInstanceID();
ExplosionManager.Instance.Add(hit.collider.gameObject, hit.collider.transform.position);
}
}
else if (hitName.StartsWith("Patient"))
{
var patient = hit.collider.GetComponent<Patient>();
if (patient != null)
{
patient.Kill(GameWorld.LevelOverReason.LaserKilledPatient);
AudioManager.PlaySFX("Laser Hit");
}
}
var plant = hit.collider.GetComponent<Plant>();
if (plant != null)
{
plant.Break();
}
break;
}
//Laser should be in front of the object when hitting from below
if (directionVector.y > 0 && !isMirror) {
AddOffset(5);
} else {
AddOffset(-5);
}
lineStrip.Draw(endpoints, offsets, endpointSize, LaserPositionOffset);
//previousEndpoints = endpoints;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text;
using Microsoft.Modeling;
using Microsoft.Protocols.TestSuites.FileSharing.SMB2Model.Adapter;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.Protocols.TestSuites.FileSharing.SMB2Model.Adapter.AppInstanceId;
using Microsoft.Xrt.Runtime;
[assembly: NativeType("System.Diagnostics.Tracing.*")]
namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2Model.Model.AppInstanceId
{
public static class AppInstanceIdModel
{
#region state
public static AppInstanceIdModelOpen Open = null;
/// <summary>
/// The state of the model.
/// </summary>
public static ModelState State = ModelState.Uninitialized;
/// <summary>
/// Max SMB dialect the server supports
/// </summary>
public static ModelDialectRevision MaxSmbVersionSupported;
#endregion
#region Rules
/// <summary>
/// The call for reading configuration.
/// </summary>
[Rule(Action = "call ReadConfig(out _)")]
public static void ReadConfigCall()
{
Condition.IsTrue(State == ModelState.Uninitialized);
}
/// <summary>
/// The return for reading configuration.
/// </summary>
/// <param name="dialectRevision">The max version of SMB supported by Server</param>
[Rule(Action = "return ReadConfig(out dialectRevision)")]
public static void ReadConfigReturn(ModelDialectRevision dialectRevision)
{
Condition.IsTrue(dialectRevision == ModelDialectRevision.Smb2002 ||
dialectRevision == ModelDialectRevision.Smb21 ||
dialectRevision == ModelDialectRevision.Smb30 ||
dialectRevision == ModelDialectRevision.Smb302);
MaxSmbVersionSupported = dialectRevision;
State = ModelState.Initialized;
}
/// <summary>
/// It contains Connect, Negotiate, SessionSetup, and CreateRequest, and it will also contain disconnect according to CreateType
/// </summary>
/// <param name="clientDialect">The dialect version for client used in Negotiation</param>
/// <param name="appInstanceIdType">How AppInstanceId is included in create request</param>
/// <param name="createType">How to construct create request and if disconnect/reconnect will be done</param>
[Rule]
public static void PrepareOpen(
ModelDialectRevision clientDialect,
AppInstanceIdType appInstanceIdType,
CreateType createType)
{
Condition.IsTrue(State == ModelState.Initialized);
// appInstanceIdType should not be Invalid or None when preparing.
Condition.IsFalse(appInstanceIdType == AppInstanceIdType.InvalidAppInstanceId || appInstanceIdType == AppInstanceIdType.NoAppInstanceId);
Condition.IsFalse(createType == CreateType.ReconnectDurable);
Combination.Isolated(clientDialect == ModelDialectRevision.Smb2002);
Combination.Isolated(clientDialect == ModelDialectRevision.Smb21);
// If the server doesn't support Dialect 3.x family, then createdurablev2 will not work and CreateDurableThenDisconnect will result in Open is null.
Condition.IfThen(!ModelUtility.IsSmb3xFamily(MaxSmbVersionSupported), createType != CreateType.CreateDurableThenDisconnect);
State = ModelState.Connected;
Open = new AppInstanceIdModelOpen();
Open.CreateTypeWhenPrepare = createType;
Open.AppInstanceId = AppInstanceIdType.NoAppInstanceId;
if (!ModelUtility.IsSmb3xFamily(MaxSmbVersionSupported))
{
ModelHelper.Log(LogType.TestInfo,
"Connection.Dialect does not belong to SMB 3.x dialect family. So Open.AppInstanceId is not set.");
return;
}
ModelHelper.Log(LogType.Requirement,
"3.3.5.9: If Connection.Dialect belongs to the SMB 3.x dialect family, the server MUST initialize the following:");
ModelHelper.Log(LogType.TestInfo, "Server supports dialect {0}.", MaxSmbVersionSupported);
if (createType == CreateType.CreateDurable)
{
ModelHelper.Log(LogType.Requirement,
"3.3.5.9: Open.AppInstanceId MUST be set to AppInstanceId in the SMB2_CREATE_APP_INSTANCE_ID create context request " +
"if the create request includes the SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2 and SMB2_CREATE_APP_INSTANCE_ID create contexts.");
Open.AppInstanceId = appInstanceIdType;
ModelHelper.Log(LogType.TestInfo,
"The create request includes the SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2 and SMB2_CREATE_APP_INSTANCE_ID create contexts.");
}
}
/// <summary>
/// Request Open to see if it can be closed.
/// </summary>
/// <param name="clientGuidType">If Open.Session.Connection.ClientGuid is equal to the current Connection.ClientGuid</param>
/// <param name="pathNameType">If Target path name is equal to Open.PathName</param>
/// <param name="createType">How to construct create request</param>
/// <param name="shareType">Type of the connected share</param>
/// <param name="appInstanceIdType">How AppInstanceId is included in create request</param>
[Rule]
public static void OpenRequest(
ClientGuidType clientGuidType,
PathNameType pathNameType,
CreateType createType,
ShareType shareType,
AppInstanceIdType appInstanceIdType)
{
Condition.IsTrue(State == ModelState.Connected);
Condition.IsNotNull(Open);
// Isolate below params to limite the expanded test cases.
Combination.Isolated(clientGuidType == ClientGuidType.SameClientGuid);
Combination.Isolated(pathNameType == PathNameType.DifferentPathName);
Combination.Isolated(shareType == ShareType.DifferentShareDifferentLocal);
Combination.Isolated(shareType == ShareType.DifferentShareSameLocal);
Combination.Isolated(appInstanceIdType == AppInstanceIdType.InvalidAppInstanceId);
Combination.Isolated(appInstanceIdType == AppInstanceIdType.NoAppInstanceId);
// "AppInstanceId is zero" is only applicable for the first Create Request.
// For the second Create Request, only valid/notvalid/none make sense.
Condition.IsFalse(appInstanceIdType == AppInstanceIdType.AppInstanceIdIsZero);
// CreateDurableThenDisconnect is only applicable for the first Create Request.
Condition.IsFalse(createType == CreateType.CreateDurableThenDisconnect);
// If the client doesn't disconnect from the server after sending the first Create Request,
// then the second Create Request does not need to contain reconnect context.
// And vice versa.
Condition.IfThen(Open.CreateTypeWhenPrepare != CreateType.CreateDurableThenDisconnect, createType != CreateType.ReconnectDurable);
Condition.IfThen(Open.CreateTypeWhenPrepare == CreateType.CreateDurableThenDisconnect, createType == CreateType.ReconnectDurable);
if (createType == CreateType.ReconnectDurable)
{
ModelHelper.Log(LogType.Requirement,
"3.3.5.9.13: If the create request also includes the SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 create context, " +
"the server MUST process the SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 create context as specified in section 3.3.5.9.12, " +
"and this section MUST be skipped.");
ModelHelper.Log(LogType.TestInfo, "SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 create context is included.");
return;
}
if (!ModelUtility.IsSmb3xFamily(MaxSmbVersionSupported))
{
ModelHelper.Log(LogType.Requirement,
"2.2.13.2.13: The SMB2_CREATE_APP_INSTANCE_ID context is valid only for the SMB 3.x dialect family.");
ModelHelper.Log(LogType.TestInfo, "The dialect version of the server is {0}.", MaxSmbVersionSupported);
return;
}
if (appInstanceIdType == AppInstanceIdType.ValidAppInstanceId && Open.AppInstanceId != AppInstanceIdType.NoAppInstanceId
&& pathNameType == PathNameType.SamePathName
&& shareType == ShareType.SameShare
&& clientGuidType == ClientGuidType.DifferentClientGuid)
{
ModelHelper.Log(LogType.Requirement,
"3.3.5.9.13: The server MUST attempt to locate an Open in GlobalOpenTable where:");
ModelHelper.Log(LogType.Requirement,
"\tAppInstanceId in the request is equal to Open.AppInstanceId.");
ModelHelper.Log(LogType.Requirement,
"\tTarget path name is equal to Open.PathName.");
ModelHelper.Log(LogType.Requirement,
"\tOpen.TreeConnect.Share is equal to TreeConnect.Share.");
ModelHelper.Log(LogType.Requirement,
"\tOpen.Session.Connection.ClientGuid is not equal to the current Connection.ClientGuid.");
ModelHelper.Log(LogType.TestInfo, "All the above conditions are met.");
ModelHelper.Log(LogType.Requirement,
"If an Open is found, the server MUST calculate the maximal access that the user, " +
"identified by Session.SecurityContext, has on the file being opened<277>. " +
"If the maximal access includes GENERIC_READ access, the server MUST close the open as specified in 3.3.4.17.");
// The user used in this model is administrator, so maximal access always includes GENERIC_READ access.
ModelHelper.Log(LogType.TestInfo, "The maximal access includes GENERIC_READ access. So open is closed.");
// close open
Open = null;
}
else
{
ModelHelper.Log(LogType.TestInfo, "appInstanceIdType is {0}.", appInstanceIdType.ToString());
ModelHelper.Log(LogType.TestInfo, "pathNameType is {0}.", pathNameType.ToString());
ModelHelper.Log(LogType.TestInfo, "shareType is {0}.", shareType.ToString());
ModelHelper.Log(LogType.TestInfo, "clientGuidType is {0}.", clientGuidType.ToString());
ModelHelper.Log(LogType.TestInfo, "All the above conditions do not match the requirement, so open will not be closed.");
ModelHelper.Log(LogType.TestTag, TestTag.UnexpectedFields);
}
}
/// <summary>
/// Verify status
/// </summary>
/// <param name="status"></param>
[Rule]
public static void OpenResponse(OpenStatus status)
{
ModelHelper.Log(LogType.TestInfo, "Open {0}.", Open == null ? "does not exist" : "exists");
if (null == Open)
{
Condition.IsTrue(status == OpenStatus.OpenClosed);
}
else
{
Condition.IsTrue(status == OpenStatus.OpenNotClosed);
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using Raksha.Asn1;
using Raksha.Asn1.X509;
using Raksha.Crypto;
using Raksha.Utilities;
using Raksha.Utilities.Collections;
using Raksha.X509;
using Raksha.X509.Store;
namespace Raksha.Pkix
{
/**
* The <i>Service Provider Interface</i> (<b>SPI</b>)
* for the {@link CertPathValidator CertPathValidator} class. All
* <code>CertPathValidator</code> implementations must include a class (the
* SPI class) that extends this class (<code>CertPathValidatorSpi</code>)
* and implements all of its methods. In general, instances of this class
* should only be accessed through the <code>CertPathValidator</code> class.
* For details, see the Java Cryptography Architecture.<br />
* <br />
* <b>Concurrent Access</b><br />
* <br />
* Instances of this class need not be protected against concurrent
* access from multiple threads. Threads that need to access a single
* <code>CertPathValidatorSpi</code> instance concurrently should synchronize
* amongst themselves and provide the necessary locking before calling the
* wrapping <code>CertPathValidator</code> object.<br />
* <br />
* However, implementations of <code>CertPathValidatorSpi</code> may still
* encounter concurrency issues, since multiple threads each
* manipulating a different <code>CertPathValidatorSpi</code> instance need not
* synchronize.
*/
/// <summary>
/// CertPathValidatorSpi implementation for X.509 Certificate validation a la RFC
/// 3280.
/// </summary>
public class PkixCertPathValidator
{
public virtual PkixCertPathValidatorResult Validate(
PkixCertPath certPath,
PkixParameters paramsPkix)
{
if (paramsPkix.GetTrustAnchors() == null)
{
throw new ArgumentException(
"trustAnchors is null, this is not allowed for certification path validation.",
"parameters");
}
//
// 6.1.1 - inputs
//
//
// (a)
//
IList certs = certPath.Certificates;
int n = certs.Count;
if (certs.Count == 0)
throw new PkixCertPathValidatorException("Certification path is empty.", null, certPath, 0);
//
// (b)
//
// DateTime validDate = PkixCertPathValidatorUtilities.GetValidDate(paramsPkix);
//
// (c)
//
ISet userInitialPolicySet = paramsPkix.GetInitialPolicies();
//
// (d)
//
TrustAnchor trust;
try
{
trust = PkixCertPathValidatorUtilities.FindTrustAnchor(
(X509Certificate)certs[certs.Count - 1],
paramsPkix.GetTrustAnchors());
}
catch (Exception e)
{
throw new PkixCertPathValidatorException(e.Message, e, certPath, certs.Count - 1);
}
if (trust == null)
throw new PkixCertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
//
// (e), (f), (g) are part of the paramsPkix object.
//
IEnumerator certIter;
int index = 0;
int i;
// Certificate for each interation of the validation loop
// Signature information for each iteration of the validation loop
//
// 6.1.2 - setup
//
//
// (a)
//
IList[] policyNodes = new IList[n + 1];
for (int j = 0; j < policyNodes.Length; j++)
{
policyNodes[j] = Platform.CreateArrayList();
}
ISet policySet = new HashSet();
policySet.Add(Rfc3280CertPathUtilities.ANY_POLICY);
PkixPolicyNode validPolicyTree = new PkixPolicyNode(Platform.CreateArrayList(), 0, policySet, null, new HashSet(),
Rfc3280CertPathUtilities.ANY_POLICY, false);
policyNodes[0].Add(validPolicyTree);
//
// (b) and (c)
//
PkixNameConstraintValidator nameConstraintValidator = new PkixNameConstraintValidator();
// (d)
//
int explicitPolicy;
ISet acceptablePolicies = new HashSet();
if (paramsPkix.IsExplicitPolicyRequired)
{
explicitPolicy = 0;
}
else
{
explicitPolicy = n + 1;
}
//
// (e)
//
int inhibitAnyPolicy;
if (paramsPkix.IsAnyPolicyInhibited)
{
inhibitAnyPolicy = 0;
}
else
{
inhibitAnyPolicy = n + 1;
}
//
// (f)
//
int policyMapping;
if (paramsPkix.IsPolicyMappingInhibited)
{
policyMapping = 0;
}
else
{
policyMapping = n + 1;
}
//
// (g), (h), (i), (j)
//
AsymmetricKeyParameter workingPublicKey;
X509Name workingIssuerName;
X509Certificate sign = trust.TrustedCert;
try
{
if (sign != null)
{
workingIssuerName = sign.SubjectDN;
workingPublicKey = sign.GetPublicKey();
}
else
{
workingIssuerName = new X509Name(trust.CAName);
workingPublicKey = trust.CAPublicKey;
}
}
catch (ArgumentException ex)
{
throw new PkixCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath,
-1);
}
AlgorithmIdentifier workingAlgId = null;
try
{
workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey);
}
catch (PkixCertPathValidatorException e)
{
throw new PkixCertPathValidatorException(
"Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
}
// DerObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.ObjectID;
// Asn1Encodable workingPublicKeyParameters = workingAlgId.Parameters;
//
// (k)
//
int maxPathLength = n;
//
// 6.1.3
//
X509CertStoreSelector certConstraints = paramsPkix.GetTargetCertConstraints();
if (certConstraints != null && !certConstraints.Match((X509Certificate)certs[0]))
{
throw new PkixCertPathValidatorException(
"Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
}
//
// initialize CertPathChecker's
//
IList pathCheckers = paramsPkix.GetCertPathCheckers();
certIter = pathCheckers.GetEnumerator();
while (certIter.MoveNext())
{
((PkixCertPathChecker)certIter.Current).Init(false);
}
X509Certificate cert = null;
for (index = certs.Count - 1; index >= 0; index--)
{
// try
// {
//
// i as defined in the algorithm description
//
i = n - index;
//
// set certificate to be checked in this round
// sign and workingPublicKey and workingIssuerName are set
// at the end of the for loop and initialized the
// first time from the TrustAnchor
//
cert = (X509Certificate)certs[index];
//
// 6.1.3
//
Rfc3280CertPathUtilities.ProcessCertA(certPath, paramsPkix, index, workingPublicKey,
workingIssuerName, sign);
Rfc3280CertPathUtilities.ProcessCertBC(certPath, index, nameConstraintValidator);
validPolicyTree = Rfc3280CertPathUtilities.ProcessCertD(certPath, index,
acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy);
validPolicyTree = Rfc3280CertPathUtilities.ProcessCertE(certPath, index, validPolicyTree);
Rfc3280CertPathUtilities.ProcessCertF(certPath, index, validPolicyTree, explicitPolicy);
//
// 6.1.4
//
if (i != n)
{
if (cert != null && cert.Version == 1)
{
throw new PkixCertPathValidatorException(
"Version 1 certificates can't be used as CA ones.", null, certPath, index);
}
Rfc3280CertPathUtilities.PrepareNextCertA(certPath, index);
validPolicyTree = Rfc3280CertPathUtilities.PrepareCertB(certPath, index, policyNodes,
validPolicyTree, policyMapping);
Rfc3280CertPathUtilities.PrepareNextCertG(certPath, index, nameConstraintValidator);
// (h)
explicitPolicy = Rfc3280CertPathUtilities.PrepareNextCertH1(certPath, index, explicitPolicy);
policyMapping = Rfc3280CertPathUtilities.PrepareNextCertH2(certPath, index, policyMapping);
inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertH3(certPath, index, inhibitAnyPolicy);
//
// (i)
//
explicitPolicy = Rfc3280CertPathUtilities.PrepareNextCertI1(certPath, index, explicitPolicy);
policyMapping = Rfc3280CertPathUtilities.PrepareNextCertI2(certPath, index, policyMapping);
// (j)
inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertJ(certPath, index, inhibitAnyPolicy);
// (k)
Rfc3280CertPathUtilities.PrepareNextCertK(certPath, index);
// (l)
maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertL(certPath, index, maxPathLength);
// (m)
maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertM(certPath, index, maxPathLength);
// (n)
Rfc3280CertPathUtilities.PrepareNextCertN(certPath, index);
ISet criticalExtensions1 = cert.GetCriticalExtensionOids();
if (criticalExtensions1 != null)
{
criticalExtensions1 = new HashSet(criticalExtensions1);
// these extensions are handled by the algorithm
criticalExtensions1.Remove(X509Extensions.KeyUsage.Id);
criticalExtensions1.Remove(X509Extensions.CertificatePolicies.Id);
criticalExtensions1.Remove(X509Extensions.PolicyMappings.Id);
criticalExtensions1.Remove(X509Extensions.InhibitAnyPolicy.Id);
criticalExtensions1.Remove(X509Extensions.IssuingDistributionPoint.Id);
criticalExtensions1.Remove(X509Extensions.DeltaCrlIndicator.Id);
criticalExtensions1.Remove(X509Extensions.PolicyConstraints.Id);
criticalExtensions1.Remove(X509Extensions.BasicConstraints.Id);
criticalExtensions1.Remove(X509Extensions.SubjectAlternativeName.Id);
criticalExtensions1.Remove(X509Extensions.NameConstraints.Id);
}
else
{
criticalExtensions1 = new HashSet();
}
// (o)
Rfc3280CertPathUtilities.PrepareNextCertO(certPath, index, criticalExtensions1, pathCheckers);
// set signing certificate for next round
sign = cert;
// (c)
workingIssuerName = sign.SubjectDN;
// (d)
try
{
workingPublicKey = PkixCertPathValidatorUtilities.GetNextWorkingKey(certPath.Certificates, index);
}
catch (PkixCertPathValidatorException e)
{
throw new PkixCertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
}
workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey);
// (f)
// workingPublicKeyAlgorithm = workingAlgId.ObjectID;
// (e)
// workingPublicKeyParameters = workingAlgId.Parameters;
}
}
//
// 6.1.5 Wrap-up procedure
//
explicitPolicy = Rfc3280CertPathUtilities.WrapupCertA(explicitPolicy, cert);
explicitPolicy = Rfc3280CertPathUtilities.WrapupCertB(certPath, index + 1, explicitPolicy);
//
// (c) (d) and (e) are already done
//
//
// (f)
//
ISet criticalExtensions = cert.GetCriticalExtensionOids();
if (criticalExtensions != null)
{
criticalExtensions = new HashSet(criticalExtensions);
// Requires .Id
// these extensions are handled by the algorithm
criticalExtensions.Remove(X509Extensions.KeyUsage.Id);
criticalExtensions.Remove(X509Extensions.CertificatePolicies.Id);
criticalExtensions.Remove(X509Extensions.PolicyMappings.Id);
criticalExtensions.Remove(X509Extensions.InhibitAnyPolicy.Id);
criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id);
criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id);
criticalExtensions.Remove(X509Extensions.PolicyConstraints.Id);
criticalExtensions.Remove(X509Extensions.BasicConstraints.Id);
criticalExtensions.Remove(X509Extensions.SubjectAlternativeName.Id);
criticalExtensions.Remove(X509Extensions.NameConstraints.Id);
criticalExtensions.Remove(X509Extensions.CrlDistributionPoints.Id);
}
else
{
criticalExtensions = new HashSet();
}
Rfc3280CertPathUtilities.WrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);
PkixPolicyNode intersection = Rfc3280CertPathUtilities.WrapupCertG(certPath, paramsPkix, userInitialPolicySet,
index + 1, policyNodes, validPolicyTree, acceptablePolicies);
if ((explicitPolicy > 0) || (intersection != null))
{
return new PkixCertPathValidatorResult(trust, intersection, cert.GetPublicKey());
}
throw new PkixCertPathValidatorException("Path processing failed on policy.", null, certPath, index);
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using GameStateManagement;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using CardsFramework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Input.Touch;
#endregion
namespace Blackjack
{
class GameplayScreen : GameScreen
{
#region Fields and Properties
BlackjackCardGame blackJackGame;
InputHelper inputHelper;
string theme;
List<DrawableGameComponent> pauseEnabledComponents = new List<DrawableGameComponent>();
List<DrawableGameComponent> pauseVisibleComponents = new List<DrawableGameComponent>();
Rectangle safeArea;
static Vector2[] playerCardOffset = new Vector2[]
{
new Vector2(100f * BlackjackGame.WidthScale, 190f * BlackjackGame.HeightScale),
new Vector2(336f * BlackjackGame.WidthScale, 210f * BlackjackGame.HeightScale),
new Vector2(570f * BlackjackGame.WidthScale, 190f * BlackjackGame.HeightScale)
};
#endregion
#region Initiaizations
/// <summary>
/// Initializes a new instance of the screen.
/// </summary>
public GameplayScreen(string theme)
{
TransitionOnTime = TimeSpan.FromSeconds(0.0);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
#if WINDOWS_PHONE
EnabledGestures = GestureType.Tap;
#endif
this.theme = theme;
}
#endregion
#region Loading
/// <summary>
/// Load content and initializes the actual game.
/// </summary>
public override void LoadContent()
{
safeArea = ScreenManager.SafeArea;
// Initialize virtual cursor
inputHelper = new InputHelper(ScreenManager.Game);
inputHelper.DrawOrder = 1000;
ScreenManager.Game.Components.Add(inputHelper);
// Ignore the curser when not run in Xbox
#if !XBOX
inputHelper.Visible = false;
inputHelper.Enabled = false;
#endif
blackJackGame = new BlackjackCardGame(ScreenManager.GraphicsDevice.Viewport.Bounds,
new Vector2(safeArea.Left + safeArea.Width / 2 - 50, safeArea.Top + 20),
GetPlayerCardPosition, ScreenManager, theme);
InitializeGame();
base.LoadContent();
}
/// <summary>
/// Unload content loaded by the screen.
/// </summary>
public override void UnloadContent()
{
ScreenManager.Game.Components.Remove(inputHelper);
base.UnloadContent();
}
#endregion
#region Update and Render
/// <summary>
/// Handle user input.
/// </summary>
/// <param name="input">User input information.</param>
public override void HandleInput(InputState input)
{
if (input.IsPauseGame(null))
{
PauseCurrentGame();
}
base.HandleInput(input);
}
/// <summary>
/// Perform the screen's update logic.
/// </summary>
/// <param name="gameTime">The time that has passed since the last call to
/// this method.</param>
/// <param name="otherScreenHasFocus">Whether or not another screen has
/// the focus.</param>
/// <param name="coveredByOtherScreen">Whether or not another screen covers
/// this one.</param>
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
#if XBOX
if (Guide.IsVisible)
{
PauseCurrentGame();
}
#endif
if (blackJackGame != null && !coveredByOtherScreen)
{
blackJackGame.Update(gameTime);
}
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
}
/// <summary>
/// Draw the screen
/// </summary>
/// <param name="gameTime"></param>
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
if (blackJackGame != null)
{
blackJackGame.Draw(gameTime);
}
}
#endregion
#region Private Methods
/// <summary>
/// Initializes the game component.
/// </summary>
private void InitializeGame()
{
blackJackGame.Initialize();
// Add human player
blackJackGame.AddPlayer(new BlackjackPlayer("Abe", blackJackGame));
// Add AI players
BlackjackAIPlayer player = new BlackjackAIPlayer("Benny", blackJackGame);
blackJackGame.AddPlayer(player);
player.Hit += player_Hit;
player.Stand += player_Stand;
player = new BlackjackAIPlayer("Chuck", blackJackGame);
blackJackGame.AddPlayer(player);
player.Hit += player_Hit;
player.Stand += player_Stand;
// Load UI assets
string[] assets = { "blackjack", "bust", "lose", "push", "win", "pass", "shuffle_" + theme };
for (int chipIndex = 0; chipIndex < assets.Length; chipIndex++)
{
blackJackGame.LoadUITexture("UI", assets[chipIndex]);
}
blackJackGame.StartRound();
}
/// <summary>
/// Gets the player hand positions according to the player index.
/// </summary>
/// <param name="player">The player's index.</param>
/// <returns>The position for the player's hand on the game table.</returns>
private Vector2 GetPlayerCardPosition(int player)
{
switch (player)
{
case 0:
case 1:
case 2:
return new Vector2(ScreenManager.SafeArea.Left,
ScreenManager.SafeArea.Top + 200 * (BlackjackGame.HeightScale - 1)) +
playerCardOffset[player];
default:
throw new ArgumentException(
"Player index should be between 0 and 2", "player");
}
}
/// <summary>
/// Pause the game.
/// </summary>
private void PauseCurrentGame()
{
// Move to the pause screen
ScreenManager.AddScreen(new BackgroundScreen(), null);
ScreenManager.AddScreen(new PauseScreen(), null);
// Hide and disable all components which are related to the gameplay screen
pauseEnabledComponents.Clear();
pauseVisibleComponents.Clear();
foreach (IGameComponent component in ScreenManager.Game.Components)
{
if (component is BetGameComponent ||
component is AnimatedGameComponent ||
component is GameTable ||
component is InputHelper)
{
DrawableGameComponent pauseComponent = (DrawableGameComponent)component;
if (pauseComponent.Enabled)
{
pauseEnabledComponents.Add(pauseComponent);
pauseComponent.Enabled = false;
}
if (pauseComponent.Visible)
{
pauseVisibleComponents.Add(pauseComponent);
pauseComponent.Visible = false;
}
}
}
}
/// <summary>
/// Returns from pause.
/// </summary>
public void ReturnFromPause()
{
// Reveal and enable all previously hidden components
foreach (DrawableGameComponent component in pauseEnabledComponents)
{
component.Enabled = true;
}
foreach (DrawableGameComponent component in pauseVisibleComponents)
{
component.Visible = true;
}
}
#endregion
#region Event Handler
/// <summary>
/// Responds to the event sent when AI player's choose to "Stand".
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The
/// <see cref="System.EventArgs"/> instance containing the event data.</param>
void player_Stand(object sender, EventArgs e)
{
blackJackGame.Stand();
}
/// <summary>
/// Responds to the event sent when AI player's choose to "Split".
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The
/// <see cref="System.EventArgs"/> instance containing the event data.</param>
void player_Split(object sender, EventArgs e)
{
blackJackGame.Split();
}
/// <summary>
/// Responds to the event sent when AI player's choose to "Hit".
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void player_Hit(object sender, EventArgs e)
{
blackJackGame.Hit();
}
/// <summary>
/// Responds to the event sent when AI player's choose to "Double".
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void player_Double(object sender, EventArgs e)
{
blackJackGame.Double();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XmlDiff;
using Microsoft.Test.ModuleCore;
using XmlCoreTest.Common;
namespace CoreXml.Test.XLinq
{
public class BridgeHelpers : XLinqTestCase
{
private XmlDiff _diff = null;
private XmlReaderSettings _rsx;
private XmlReaderSettings _rsxNoWs;
public BridgeHelpers()
{
_diff = new XmlDiff();
_rsx = new XmlReaderSettings();
_rsx.DtdProcessing = DtdProcessing.Ignore;
_rsxNoWs = new XmlReaderSettings();
_rsxNoWs.DtdProcessing = DtdProcessing.Ignore;
_rsxNoWs.IgnoreWhitespace = true;
Init();
}
//BridgeHelpers constants
public const string TestSaveFileName = "testSave.xml";
public const string ST_XML = "xml";
public const string strBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
public const string strBinHex = "0123456789ABCDEF";
public static string pLbNormEnt1 = "se3_1.ent";
public static string pLbNormEnt2 = "se3_2.ent";
public static string pGenericXml = "Generic.xml";
public static string pXsltCopyStylesheet = "XsltCtest.xsl";
public static string pValidXDR = "XdrFile.xml";
//Reader constants
public const string ST_TEST_NAME = "ISDEFAULT";
public const string ST_ENTTEST_NAME = "ENTITY1";
public const string ST_MARKUP_TEST_NAME = "CHARS2";
public const string ST_EMPTY_TEST_NAME = "EMPTY1";
public static string pJunkFileXml = "Junk.xml";
public static string pBase64Xml = "Base64.xml";
public static string pBinHexXml = "BinHex.xml";
public const string ST_EXPAND_ENTITIES = "xxx>xxxBxxxDxxxe1fooxxx";
public const string ST_EXPAND_ENTITIES2 = "xxx>xxxBxxxDxxxe1fooxxx";
public const string ST_ENT1_ATT_EXPAND_ENTITIES = "xxx<xxxAxxxCxxxe1fooxxx";
public const string ST_EXPAND_CHAR_ENTITIES = "xxx>xxxBxxxDxxx";
public const string ST_GEN_ENT_NAME = "e1";
public const string ST_ENT1_ATT_EXPAND_CHAR_ENTITIES4 = "xxx<xxxAxxxCxxxe1fooxxx";
public const string ST_IGNORE_ENTITIES = "xxx>xxxBxxxDxxx&e1;xxx";
public static string strNamespace = "http://www.foo.com";
public static string strAttr = "Attr";
public const string ST_D1_VALUE = "d1value";
public const string ST_GEN_ENT_VALUE = "e1foo";
//Writer helpers
public XmlWriter CreateWriter()
{
XDocument doc = new XDocument();
return CreateWriter(doc);
}
public XmlWriter CreateWriter(XDocument d)
{
return d.CreateWriter();
}
//Reader helpers
public XmlReader GetReader()
{
string file = Path.Combine("TestData", "XmlReader", "API", pGenericXml);
Stream s = FilePathUtil.getStream(file);
if (s == null)
{
throw new FileNotFoundException("File Not Found: " + pGenericXml);
}
using (XmlReader r = XmlReader.Create(s, _rsx))
{
XDocument doc = XDocument.Load(r, LoadOptions.PreserveWhitespace);
return doc.CreateReader();
}
}
public XmlReader GetPGenericXmlReader()
{
string file = Path.Combine("TestData", "XmlReader", "API", pGenericXml);
{
Stream s = FilePathUtil.getStreamDirect(file);
if (s == null)
{
throw new FileNotFoundException("File Not Found: " + pGenericXml);
}
using (XmlReader r = XmlReader.Create(s, _rsx))
{
XDocument doc = XDocument.Load(r, LoadOptions.PreserveWhitespace);
return doc.CreateReader();
}
}
}
public XmlReader GetReader(string strSource, bool preserveWhitespace)
{
using (XmlReader r = XmlReader.Create(FilePathUtil.getStream(strSource), preserveWhitespace ? _rsx : _rsxNoWs))
{
XDocument doc = XDocument.Load(r, preserveWhitespace ? LoadOptions.PreserveWhitespace : LoadOptions.None);
return doc.CreateReader();
}
}
public XmlReader GetReader(string strSource)
{
using (XmlReader r = XmlReader.Create(FilePathUtil.getStream(strSource), _rsx))
{
XDocument doc = XDocument.Load(r, LoadOptions.PreserveWhitespace);
return doc.CreateReader();
}
}
public XmlReader GetReader(TextReader sr)
{
using (XmlReader r = XmlReader.Create(sr, _rsx))
{
XDocument doc = XDocument.Load(r, LoadOptions.PreserveWhitespace);
return doc.CreateReader();
}
}
public XmlReader GetReader(XmlReader r)
{
XDocument doc = XDocument.Load(r);
return doc.CreateReader();
}
public XmlReader GetReader(Stream stream)
{
using (XmlReader r = XmlReader.Create(stream, _rsx))
{
XDocument doc = XDocument.Load(r);
return doc.CreateReader();
}
}
public XmlReader GetReaderStr(string xml)
{
using (XmlReader r = XmlReader.Create(new StringReader(xml), _rsx))
{
XDocument doc = XDocument.Load(r, LoadOptions.PreserveWhitespace);
return doc.CreateReader();
}
}
public static string GetTestFileName()
{
return Path.Combine("TestData", "XmlReader", "API", pGenericXml);
}
public bool CompareReader(XDocument doc, string expectedXml)
{
XmlReaderSettings rs = new XmlReaderSettings();
rs.ConformanceLevel = ConformanceLevel.Auto;
rs.DtdProcessing = DtdProcessing.Ignore;
rs.CloseInput = true;
_diff.Option = XmlDiffOption.IgnoreAttributeOrder;
using (XmlReader r1 = doc.CreateReader())
using (XmlReader r2 = XmlReader.Create(new StringReader(expectedXml), rs))
{
if (!_diff.Compare(r1, r2))
{
TestLog.WriteLine("Mismatch : expected: " + expectedXml + "\n actual: " + doc.ToString());
return false;
}
}
return true;
}
public bool CompareReader(XmlReader r1, string expectedXml)
{
XmlReaderSettings rs = new XmlReaderSettings();
rs.ConformanceLevel = ConformanceLevel.Auto;
rs.CloseInput = true;
_diff.Option = XmlDiffOption.IgnoreAttributeOrder;
using (XmlReader r2 = XmlReader.Create(new StringReader(expectedXml), rs))
{
if (!_diff.Compare(r1, r2))
{
TestLog.WriteLine("Mismatch : expected: " + expectedXml + "\n actual: ");
return false;
}
}
return true;
}
public string GetString(string fileName)
{
string strRet = string.Empty;
Stream temp = FilePathUtil.getStream(fileName);
StreamReader srTemp = new StreamReader(temp);
strRet = srTemp.ReadToEnd();
srTemp.Dispose();
temp.Dispose();
return strRet;
}
public bool CompareBaseline(XDocument doc, string baselineFile)
{
XmlReaderSettings rs = new XmlReaderSettings();
rs.ConformanceLevel = ConformanceLevel.Auto;
rs.DtdProcessing = DtdProcessing.Ignore;
rs.CloseInput = true;
_diff.Option = XmlDiffOption.IgnoreAttributeOrder;
using (XmlReader r1 = XmlReader.Create(FilePathUtil.getStream(FullPath(baselineFile)), rs))
using (XmlReader r2 = doc.CreateReader())
{
if (!_diff.Compare(r1, r2))
{
TestLog.WriteLine("Mismatch : expected: " + this.GetString(FullPath(baselineFile)) + "\n actual: " + doc.ToString());
return false;
}
}
return true;
}
public string FullPath(string fileName)
{
if (fileName == null || fileName == string.Empty)
return fileName;
return Path.Combine("TestData", "XmlWriter2", fileName);
}
public static void EnsureSpace(ref byte[] buffer, int len)
{
if (len >= buffer.Length)
{
int originalLen = buffer.Length;
byte[] newBuffer = new byte[(int)(len * 2)];
for (int i = 0; i < originalLen; newBuffer[i] = buffer[i++])
{
// Intentionally Empty
}
buffer = newBuffer;
}
}
public static void WriteToBuffer(ref byte[] destBuff, ref int len, byte srcByte)
{
EnsureSpace(ref destBuff, len);
destBuff[len++] = srcByte;
return;
}
public static void WriteToBuffer(ref byte[] destBuff, ref int len, byte[] srcBuff)
{
int srcArrayLen = srcBuff.Length;
WriteToBuffer(ref destBuff, ref len, srcBuff, 0, (int)srcArrayLen);
return;
}
public static void WriteToBuffer(ref byte[] destBuff, ref int destStart, byte[] srcBuff, int srcStart, int count)
{
EnsureSpace(ref destBuff, destStart + count - 1);
for (int i = srcStart; i < srcStart + count; i++)
{
destBuff[destStart++] = srcBuff[i];
}
}
public static void WriteToBuffer(ref byte[] destBuffer, ref int destBuffLen, string strValue)
{
for (int i = 0; i < strValue.Length; i++)
{
WriteToBuffer(ref destBuffer, ref destBuffLen, System.BitConverter.GetBytes(strValue[i]));
}
WriteToBuffer(ref destBuffer, ref destBuffLen, System.BitConverter.GetBytes('\0'));
}
public void CheckClosedState(WriteState ws)
{
TestLog.Compare(ws, WriteState.Closed, "WriteState should be Closed");
}
public void CheckErrorState(WriteState ws)
{
TestLog.Compare(ws, WriteState.Error, "WriteState should be Error");
}
public void CheckElementState(WriteState ws)
{
TestLog.Compare(ws, WriteState.Element, "WriteState should be Element");
}
public void VerifyInvalidWrite(string methodName, int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
byte[] byteBuffer = new byte[iBufferSize];
for (int i = 0; i < iBufferSize; i++)
byteBuffer[i] = (byte)(i + '0');
char[] charBuffer = new char[iBufferSize];
for (int i = 0; i < iBufferSize; i++)
charBuffer[i] = (char)(i + '0');
XDocument doc = new XDocument();
XmlWriter w = CreateWriter(doc);
w.WriteStartElement("root");
try
{
switch (methodName)
{
case "WriteBase64":
w.WriteBase64(byteBuffer, iIndex, iCount);
break;
case "WriteRaw":
w.WriteRaw(charBuffer, iIndex, iCount);
break;
case "WriteBinHex":
w.WriteBinHex(byteBuffer, iIndex, iCount);
break;
case "WriteChars":
w.WriteChars(charBuffer, iIndex, iCount);
break;
default:
TestLog.Compare(false, "Unexpected method name " + methodName);
break;
}
}
catch (Exception e)
{
if (exceptionType.Equals(e.GetType()))
{
return;
}
else
{
TestLog.WriteLine("Did not throw exception of type {0}", exceptionType);
}
}
finally
{
w.Dispose();
}
throw new TestException(TestResult.Failed, "");
}
public byte[] StringToByteArray(string src)
{
byte[] base64 = new byte[src.Length * 2];
for (int i = 0; i < src.Length; i++)
{
byte[] temp = System.BitConverter.GetBytes(src[i]);
base64[2 * i] = temp[0];
base64[2 * i + 1] = temp[1];
}
return base64;
}
public static bool VerifyNode(XmlReader r, XmlNodeType eExpNodeType, string strExpName, string strExpValue)
{
bool bPassed = true;
if (r.NodeType != eExpNodeType)
{
TestLog.WriteLine("NodeType doesn't match");
TestLog.WriteLine(" Expected NodeType: " + eExpNodeType);
TestLog.WriteLine(" Actual NodeType: " + r.NodeType);
bPassed = false;
}
if (r.Name != strExpName)
{
TestLog.WriteLine("Name doesn't match:");
TestLog.WriteLine(" Expected Name: '" + strExpName + "'");
TestLog.WriteLine(" Actual Name: '" + r.Name + "'");
bPassed = false;
}
if (r.Value != strExpValue)
{
TestLog.WriteLine("Value doesn't match:");
TestLog.WriteLine(" Expected Value: '" + strExpValue + "'");
TestLog.WriteLine(" Actual Value: '" + r.Value + "'");
bPassed = false;
}
return bPassed;
}
public void CompareNode(XmlReader r, XmlNodeType eExpNodeType, string strExpName, string strExpValue)
{
bool bNode = VerifyNode(r, eExpNodeType, strExpName, strExpValue);
TestLog.Compare(bNode, "VerifyNode failed");
}
public void CheckXmlException(string expectedCode, XmlException e, int expectedLine, int expectedPosition)
{
TestLog.Compare(e.LineNumber, expectedLine, "CheckXmlException:LineNumber");
TestLog.Compare(e.LinePosition, expectedPosition, "CheckXmlException:LinePosition");
}
public void PositionOnNodeType(XmlReader r, XmlNodeType nodeType)
{
if (nodeType == XmlNodeType.DocumentType)
{
TestLog.Skip("There is no DocumentType");
}
if (r.NodeType == nodeType)
return;
while (r.Read() && r.NodeType != nodeType)
{
if (nodeType == XmlNodeType.ProcessingInstruction && r.NodeType == XmlNodeType.XmlDeclaration)
{
if (string.Compare(Name, 0, ST_XML, 0, 3) != 0)
return;
}
if (r.NodeType == XmlNodeType.Element && nodeType == XmlNodeType.Attribute)
{
if (r.MoveToFirstAttribute())
{
return;
}
}
}
if (r.EOF)
{
throw new TestException(TestResult.Failed, "Couldn't find XmlNodeType " + nodeType);
}
}
public void PositionOnElement(XmlReader r, string strElementName)
{
if (r.NodeType == XmlNodeType.Element && r.Name == strElementName)
return;
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element && r.Name == strElementName)
break;
}
if (r.EOF)
{
throw new TestException(TestResult.Failed, "Couldn't find element '" + strElementName + "'");
}
}
public XmlReader CreateReader(int size)
{
StringBuilder sb = new StringBuilder();
sb.Append("<root>");
for (int i = 0; i < size; i++)
{
sb.Append("A");
}
sb.Append("</root>");
return GetReaderStr(sb.ToString());
}
public XmlReader CreateReaderIgnoreWS(string fileName)
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreWhitespace = true;
readerSettings.CloseInput = false;
Stream stream = FilePathUtil.getStream(fileName);
return GetReader(XmlReader.Create(stream, readerSettings));
}
public XmlReader CreateReader(string fileName)
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.DtdProcessing = DtdProcessing.Ignore;
readerSettings.CloseInput = false;
Stream stream = FilePathUtil.getStream(fileName);
return GetReader(XmlReader.Create(stream, readerSettings));
}
public XmlReader CreateReader(TextReader sr)
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.CloseInput = true;
return GetReader(XmlReader.Create(sr, readerSettings));
}
// return string of current mode
public string InitStringValue(string str)
{
object obj = TestInput.Properties["CommandLine/" + str];
if (obj == null)
{
return string.Empty;
}
return obj.ToString();
}
public void DiffTwoXmlStrings(string source, string target)
{
_diff.Option = XmlDiffOption.IgnoreAttributeOrder;
XmlReaderSettings rs = new XmlReaderSettings();
rs.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader src = XmlReader.Create(new StringReader(source), rs);
XmlReader tgt = XmlReader.Create(new StringReader(target), rs);
bool retVal = _diff.Compare(src, tgt);
if (!retVal)
{
TestLog.WriteLine("XmlDif failed:");
TestLog.WriteLine("DIFF: {0}", _diff.ToXml());
throw new TestException(TestResult.Failed, "");
}
}
public void BoolToLTMResult(bool bResult)
{
if (!bResult)
throw new TestException(TestResult.Failed, "");
}
public static void DeleteTestFile(string strFileName)
{
}
public static void CreateByteTestFile(string strFileName)
{
FilePathUtil.addStream(strFileName, new MemoryStream());
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("x");
tw.Flush();
tw.Dispose();
}
public static void CreateUTF8EncodedTestFile(string strFileName, Encoding encode)
{
FilePathUtil.addStream(strFileName, new MemoryStream());
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName), encode);
tw.WriteLine("<root>");
tw.Write("\uFFFD");
tw.WriteLine("</root>");
tw.Flush();
tw.Dispose();
}
public static void CreateEncodedTestFile(string strFileName, Encoding encode)
{
FilePathUtil.addStream(strFileName, new MemoryStream());
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName), encode);
tw.WriteLine("<root>");
tw.WriteLine("</root>");
tw.Flush();
tw.Dispose();
}
public static void CreateWhitespaceHandlingTestFile(string strFileName)
{
FilePathUtil.addStream(strFileName, new MemoryStream());
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<!DOCTYPE dt [");
tw.WriteLine("<!ELEMENT WHITESPACE1 (#PCDATA)*>");
tw.WriteLine("<!ELEMENT WHITESPACE2 (#PCDATA)*>");
tw.WriteLine("<!ELEMENT WHITESPACE3 (#PCDATA)*>");
tw.WriteLine("]>");
tw.WriteLine("<doc>");
tw.WriteLine("<WHITESPACE1>\r\n<ELEM />\r\n</WHITESPACE1>");
tw.WriteLine("<WHITESPACE2> <ELEM /> </WHITESPACE2>");
tw.WriteLine("<WHITESPACE3>\t<ELEM />\t</WHITESPACE3>");
tw.WriteLine("</doc>");
tw.Flush();
tw.Dispose();
}
public static void CreateGenericXsltTestFile(string strFileName)
{
CreateXSLTStyleSheetWCopyTestFile(pXsltCopyStylesheet);
CreateGenericTestFile(strFileName);
}
public static void CreateGenericTestFile(string strFileName)
{
FilePathUtil.addStream(strFileName, new MemoryStream());
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
tw.WriteLine("<!-- comment1 -->");
tw.WriteLine("<?PI1_First processing instruction?>");
tw.WriteLine("<?PI1a?>");
tw.WriteLine("<?PI1b?>");
tw.WriteLine("<?PI1c?>");
tw.WriteLine("<!DOCTYPE root SYSTEM \"AllNodeTypes.dtd\" [");
tw.WriteLine("<!NOTATION gif SYSTEM \"foo.exe\">");
tw.WriteLine("<!ELEMENT root ANY>");
tw.WriteLine("<!ELEMENT elem1 ANY>");
tw.WriteLine("<!ELEMENT ISDEFAULT ANY>");
tw.WriteLine("<!ENTITY % e SYSTEM \"AllNodeTypes.ent\">");
tw.WriteLine("%e;");
tw.WriteLine("<!ENTITY e1 \"e1foo\">");
tw.WriteLine("<!ENTITY e2 \"&ext3; e2bar\">");
tw.WriteLine("<!ENTITY e3 \"&e1; e3bzee \">");
tw.WriteLine("<!ENTITY e4 \"&e3; e4gee\">");
tw.WriteLine("<!ATTLIST elem1 child1 CDATA #IMPLIED child2 CDATA \"&e2;\" child3 CDATA #REQUIRED>");
tw.WriteLine("<!ATTLIST root xmlns:something CDATA #FIXED \"something\" xmlns:my CDATA #FIXED \"my\" xmlns:dt CDATA #FIXED \"urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/\">");
tw.WriteLine("<!ATTLIST ISDEFAULT d1 CDATA #FIXED \"d1value\">");
tw.WriteLine("<!ATTLIST MULTISPACES att IDREFS #IMPLIED>");
tw.WriteLine("<!ELEMENT CATMIXED (#PCDATA)>");
tw.WriteLine("]>");
tw.WriteLine("<PLAY>");
tw.WriteLine("<root xmlns:something=\"something\" xmlns:my=\"my\" xmlns:dt=\"urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/\">");
tw.WriteLine("<elem1 child1=\"\" child2=\"&e2;\" child3=\"something\">");
tw.WriteLine("text node two &e1; text node three");
tw.WriteLine("</elem1>");
tw.WriteLine("&e2;");
tw.WriteLine("<![CDATA[ This section contains characters that should not be interpreted as markup. For example, characters ', \",");
tw.WriteLine("<, >, and & are all fine here.]]>");
tw.WriteLine("<elem2 att1=\"id1\" att2=\"up\" att3=\"attribute3\"> ");
tw.WriteLine("<a />");
tw.WriteLine("</elem2>");
tw.WriteLine("<elem2> ");
tw.WriteLine("elem2-text1");
tw.WriteLine("<a refs=\"id2\"> ");
tw.WriteLine("this-is-a ");
tw.WriteLine("</a> ");
tw.WriteLine("elem2-text2");
tw.WriteLine("&e3;");
tw.WriteLine("&e4;");
tw.WriteLine("<!-- elem2-comment1-->");
tw.WriteLine("elem2-text3");
tw.WriteLine("<b> ");
tw.WriteLine("this-is-b");
tw.WriteLine("</b>");
tw.WriteLine("elem2-text4");
tw.WriteLine("<?elem2_PI elem2-PI?>");
tw.WriteLine("elem2-text5");
tw.WriteLine("</elem2>");
tw.WriteLine("<elem2 att1=\"id2\"></elem2>");
tw.WriteLine("</root>");
tw.Write("<ENTITY1 att1='xxx<xxxAxxxCxxx&e1;xxx'>xxx>xxxBxxxDxxx&e1;xxx</ENTITY1>");
tw.WriteLine("<ENTITY2 att1='xxx<xxxAxxxCxxx&e1;xxx'>xxx>xxxBxxxDxxx&e1;xxx</ENTITY2>");
tw.WriteLine("<ENTITY3 att1='xxx<xxxAxxxCxxx&e1;xxx'>xxx>xxxBxxxDxxx&e1;xxx</ENTITY3>");
tw.WriteLine("<ENTITY4 att1='xxx<xxxAxxxCxxx&e1;xxx'>xxx>xxxBxxxDxxx&e1;xxx</ENTITY4>");
tw.WriteLine("<ENTITY5>&ext3;</ENTITY5>");
tw.WriteLine("<ATTRIBUTE1 />");
tw.WriteLine("<ATTRIBUTE2 a1='a1value' />");
tw.WriteLine("<ATTRIBUTE3 a1='a1value' a2='a2value' a3='a3value' />");
tw.WriteLine("<ATTRIBUTE4 a1='' />");
tw.WriteLine("<ATTRIBUTE5 CRLF='x\r\nx' CR='x\rx' LF='x\nx' MS='x x' TAB='x\tx' />");
tw.WriteLine("<?PI1a a\r\n\rb ?>");
tw.WriteLine("<!--comm\r\n\rent-->");
tw.WriteLine("<![CDATA[cd\r\n\rata]]>");
tw.WriteLine("<ENDOFLINE1>x\r\nx</ENDOFLINE1>");
tw.WriteLine("<ENDOFLINE2>x\rx</ENDOFLINE2>");
tw.WriteLine("<ENDOFLINE3>x\nx</ENDOFLINE3>");
tw.WriteLine("<WHITESPACE1>\r\n<ELEM />\r\n</WHITESPACE1>");
tw.WriteLine("<WHITESPACE2> <ELEM /> </WHITESPACE2>");
tw.WriteLine("<WHITESPACE3>\t<ELEM />\t</WHITESPACE3>");
tw.WriteLine("<SKIP1 /><AFTERSKIP1 />");
tw.WriteLine("<SKIP2></SKIP2><AFTERSKIP2 />");
tw.WriteLine("<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3><AFTERSKIP3></AFTERSKIP3>");
tw.WriteLine("<SKIP4><ELEM1 /><ELEM2>xxx<ELEM3 /></ELEM2></SKIP4>");
tw.WriteLine("<CHARS1>0123456789</CHARS1>");
tw.WriteLine("<CHARS2>xxx<MARKUP />yyy</CHARS2>");
tw.WriteLine("<CHARS_ELEM1>xxx<MARKUP />yyy</CHARS_ELEM1>");
tw.WriteLine("<CHARS_ELEM2><MARKUP />yyy</CHARS_ELEM2>");
tw.WriteLine("<CHARS_ELEM3>xxx<MARKUP /></CHARS_ELEM3>");
tw.WriteLine("<CHARS_CDATA1>xxx<![CDATA[yyy]]>zzz</CHARS_CDATA1>");
tw.WriteLine("<CHARS_CDATA2><![CDATA[yyy]]>zzz</CHARS_CDATA2>");
tw.WriteLine("<CHARS_CDATA3>xxx<![CDATA[yyy]]></CHARS_CDATA3>");
tw.WriteLine("<CHARS_PI1>xxx<?PI_CHAR1 yyy?>zzz</CHARS_PI1>");
tw.WriteLine("<CHARS_PI2><?PI_CHAR2?>zzz</CHARS_PI2>");
tw.WriteLine("<CHARS_PI3>xxx<?PI_CHAR3 yyy?></CHARS_PI3>");
tw.WriteLine("<CHARS_COMMENT1>xxx<!-- comment1-->zzz</CHARS_COMMENT1>");
tw.WriteLine("<CHARS_COMMENT2><!-- comment1-->zzz</CHARS_COMMENT2>");
tw.WriteLine("<CHARS_COMMENT3>xxx<!-- comment1--></CHARS_COMMENT3>");
tw.Flush();
tw.WriteLine("<ISDEFAULT />");
tw.WriteLine("<ISDEFAULT a1='a1value' />");
tw.WriteLine("<BOOLEAN1>true</BOOLEAN1>");
tw.WriteLine("<BOOLEAN2>false</BOOLEAN2>");
tw.WriteLine("<BOOLEAN3>1</BOOLEAN3>");
tw.WriteLine("<BOOLEAN4>tRue</BOOLEAN4>");
tw.WriteLine("<DATETIME>1999-02-22T11:11:11</DATETIME>");
tw.WriteLine("<DATE>1999-02-22</DATE>");
tw.WriteLine("<TIME>11:11:11</TIME>");
tw.WriteLine("<INTEGER>9999</INTEGER>");
tw.WriteLine("<FLOAT>99.99</FLOAT>");
tw.WriteLine("<DECIMAL>.09</DECIMAL>");
tw.WriteLine("<CONTENT><e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1></CONTENT>");
tw.WriteLine("<TITLE><!-- this is a comment--></TITLE>");
tw.WriteLine("<PGROUP>");
tw.WriteLine("<ACT0 xmlns:foo=\"http://www.foo.com\" foo:Attr0=\"0\" foo:Attr1=\"1111111101\" foo:Attr2=\"222222202\" foo:Attr3=\"333333303\" foo:Attr4=\"444444404\" foo:Attr5=\"555555505\" foo:Attr6=\"666666606\" foo:Attr7=\"777777707\" foo:Attr8=\"888888808\" foo:Attr9=\"999999909\" />");
tw.WriteLine("<ACT1 Attr0=\'0\' Attr1=\'1111111101\' Attr2=\'222222202\' Attr3=\'333333303\' Attr4=\'444444404\' Attr5=\'555555505\' Attr6=\'666666606\' Attr7=\'777777707\' Attr8=\'888888808\' Attr9=\'999999909\' />");
tw.WriteLine("<QUOTE1 Attr0=\"0\" Attr1=\'1111111101\' Attr2=\"222222202\" Attr3=\'333333303\' />");
tw.WriteLine("<PERSONA>DROMIO OF EPHESUS</PERSONA>");
tw.WriteLine("<QUOTE2 Attr0=\"0\" Attr1=\"1111111101\" Attr2=\'222222202\' Attr3=\'333333303\' />");
tw.WriteLine("<QUOTE3 Attr0=\'0\' Attr1=\"1111111101\" Attr2=\'222222202\' Attr3=\"333333303\" />");
tw.WriteLine("<EMPTY1 />");
tw.WriteLine("<EMPTY2 val=\"abc\" />");
tw.WriteLine("<EMPTY3></EMPTY3>");
tw.WriteLine("<NONEMPTY0></NONEMPTY0>");
tw.WriteLine("<NONEMPTY1>ABCDE</NONEMPTY1>");
tw.WriteLine("<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>");
tw.WriteLine("<ACT2 Attr0=\"10\" Attr1=\"1111111011\" Attr2=\"222222012\" Attr3=\"333333013\" Attr4=\"444444014\" Attr5=\"555555015\" Attr6=\"666666016\" Attr7=\"777777017\" Attr8=\"888888018\" Attr9=\"999999019\" />");
tw.WriteLine("<GRPDESCR>twin brothers, and sons to Aegeon and Aemilia.</GRPDESCR>");
tw.WriteLine("</PGROUP>");
tw.WriteLine("<PGROUP>");
tw.Flush();
tw.WriteLine("<XMLLANG0 xml:lang=\"en-US\">What color &e1; is it?</XMLLANG0>");
tw.Write("<XMLLANG1 xml:lang=\"en-GB\">What color is it?<a><b><c>Language Test</c><PERSONA>DROMIO OF EPHESUS</PERSONA></b></a></XMLLANG1>");
tw.WriteLine("<NOXMLLANG />");
tw.WriteLine("<EMPTY_XMLLANG Attr0=\"0\" xml:lang=\"en-US\" />");
tw.WriteLine("<XMLLANG2 xml:lang=\"en-US\">What color is it?<TITLE><!-- this is a comment--></TITLE><XMLLANG1 xml:lang=\"en-GB\">Testing language<XMLLANG0 xml:lang=\"en-US\">What color is it?</XMLLANG0>haha </XMLLANG1>hihihi</XMLLANG2>");
tw.WriteLine("<DONEXMLLANG />");
tw.WriteLine("<XMLSPACE1 xml:space=\'default\'>< ></XMLSPACE1>");
tw.Write("<XMLSPACE2 xml:space=\'preserve\'>< ><a><!-- comment--><b><?PI1a?><c>Space Test</c><PERSONA>DROMIO OF SYRACUSE</PERSONA></b></a></XMLSPACE2>");
tw.WriteLine("<NOSPACE />");
tw.WriteLine("<EMPTY_XMLSPACE Attr0=\"0\" xml:space=\'default\' />");
tw.WriteLine("<XMLSPACE2A xml:space=\'default\'>< <XMLSPACE3 xml:space=\'preserve\'> < > <XMLSPACE4 xml:space=\'default\'> < > </XMLSPACE4> test </XMLSPACE3> ></XMLSPACE2A>");
tw.WriteLine("<GRPDESCR>twin brothers, and attendants on the two Antipholuses.</GRPDESCR>");
tw.WriteLine("<DOCNAMESPACE>");
tw.WriteLine("<NAMESPACE0 xmlns:bar=\"1\"><bar:check>Namespace=1</bar:check></NAMESPACE0>");
tw.WriteLine("<NAMESPACE1 xmlns:bar=\"1\"><a><b><c><d><bar:check>Namespace=1</bar:check><bar:check2></bar:check2></d></c></b></a></NAMESPACE1>");
tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>");
tw.WriteLine("<EMPTY_NAMESPACE bar:Attr0=\"0\" xmlns:bar=\"1\" />");
tw.WriteLine("<EMPTY_NAMESPACE1 Attr0=\"0\" xmlns=\"14\" />");
tw.WriteLine("<EMPTY_NAMESPACE2 Attr0=\"0\" xmlns=\"14\"></EMPTY_NAMESPACE2>");
tw.WriteLine("<NAMESPACE2 xmlns:bar=\"1\"><a><b><c xmlns:bar=\"2\"><d><bar:check>Namespace=2</bar:check></d></c></b></a></NAMESPACE2>");
tw.WriteLine("<NAMESPACE3 xmlns=\"1\"><a xmlns:a=\"2\" xmlns:b=\"3\" xmlns:c=\"4\"><b xmlns:d=\"5\" xmlns:e=\"6\" xmlns:f='7'><c xmlns:d=\"8\" xmlns:e=\"9\" xmlns:f=\"10\">");
tw.WriteLine("<d xmlns:g=\"11\" xmlns:h=\"12\"><check>Namespace=1</check><testns xmlns=\"100\"><empty100 /><check100>Namespace=100</check100></testns><check1>Namespace=1</check1><d:check8>Namespace=8</d:check8></d></c><d:check5>Namespace=5</d:check5></b></a>");
tw.WriteLine("<a13 a:check=\"Namespace=13\" xmlns:a=\"13\" /><check14 xmlns=\"14\">Namespace=14</check14></NAMESPACE3>");
tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>");
tw.WriteLine("<NONAMESPACE1 Attr1=\"one\" xmlns=\"1000\">Namespace=\"\"</NONAMESPACE1>");
tw.WriteLine("</DOCNAMESPACE>");
tw.WriteLine("</PGROUP>");
tw.WriteLine("<GOTOCONTENT>some text<![CDATA[cdata info]]></GOTOCONTENT>");
tw.WriteLine("<SKIPCONTENT att1=\"\"> <!-- comment1--> \n <?PI_SkipContent instruction?></SKIPCONTENT>");
tw.WriteLine("<MIXCONTENT> <!-- comment1-->some text<?PI_SkipContent instruction?><![CDATA[cdata info]]></MIXCONTENT>");
tw.WriteLine("<A att=\"123\">1<B>2<C>3<D>4<E>5<F>6<G>7<H>8<I>9<J>10");
tw.WriteLine("<A1 att=\"456\">11<B1>12<C1>13<D1>14<E1>15<F1>16<G1>17<H1>18<I1>19<J1>20");
tw.WriteLine("<A2 att=\"789\">21<B2>22<C2>23<D2>24<E2>25<F2>26<G2>27<H2>28<I2>29<J2>30");
tw.WriteLine("<A3 att=\"123\">31<B3>32<C3>33<D3>34<E3>35<F3>36<G3>37<H3>38<I3>39<J3>40");
tw.WriteLine("<A4 att=\"456\">41<B4>42<C4>43<D4>44<E4>45<F4>46<G4>47<H4>48<I4>49<J4>50");
tw.WriteLine("<A5 att=\"789\">51<B5>52<C5>53<D5>54<E5>55<F5>56<G5>57<H5>58<I5>59<J5>60");
tw.WriteLine("<A6 att=\"123\">61<B6>62<C6>63<D6>64<E6>65<F6>66<G6>67<H6>68<I6>69<J6>70");
tw.WriteLine("<A7 att=\"456\">71<B7>72<C7>73<D7>74<E7>75<F7>76<G7>77<H7>78<I7>79<J7>80");
tw.WriteLine("<A8 att=\"789\">81<B8>82<C8>83<D8>84<E8>85<F8>86<G8>87<H8>88<I8>89<J8>90");
tw.WriteLine("<A9 att=\"123\">91<B9>92<C9>93<D9>94<E9>95<F9>96<G9>97<H9>98<I9>99<J9>100");
tw.WriteLine("<A10 att=\"123\">101<B10>102<C10>103<D10>104<E10>105<F10>106<G10>107<H10>108<I10>109<J10>110");
tw.WriteLine("</J10>109</I10>108</H10>107</G10>106</F10>105</E10>104</D10>103</C10>102</B10>101</A10>");
tw.WriteLine("</J9>99</I9>98</H9>97</G9>96</F9>95</E9>94</D9>93</C9>92</B9>91</A9>");
tw.WriteLine("</J8>89</I8>88</H8>87</G8>86</F8>85</E8>84</D8>83</C8>82</B8>81</A8>");
tw.WriteLine("</J7>79</I7>78</H7>77</G7>76</F7>75</E7>74</D7>73</C7>72</B7>71</A7>");
tw.WriteLine("</J6>69</I6>68</H6>67</G6>66</F6>65</E6>64</D6>63</C6>62</B6>61</A6>");
tw.WriteLine("</J5>59</I5>58</H5>57</G5>56</F5>55</E5>54</D5>53</C5>52</B5>51</A5>");
tw.WriteLine("</J4>49</I4>48</H4>47</G4>46</F4>45</E4>44</D4>43</C4>42</B4>41</A4>");
tw.WriteLine("</J3>39</I3>38</H3>37</G3>36</F3>35</E3>34</D3>33</C3>32</B3>31</A3>");
tw.WriteLine("</J2>29</I2>28</H2>27</G2>26</F2>25</E2>24</D2>23</C2>22</B2>21</A2>");
tw.WriteLine("</J1>19</I1>18</H1>17</G1>16</F1>15</E1>14</D1>13</C1>12</B1>11</A1>");
tw.Write("</J>9</I>8</H>7</G>6</F>5</E>4</D>3</C>2</B>1</A>");
tw.WriteLine("<EMPTY4 val=\"abc\"></EMPTY4>");
tw.WriteLine("<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>");
tw.WriteLine("<DUMMY />");
tw.WriteLine("<MULTISPACES att=' \r\n \t \r\r\n n1 \r\n \t \r\r\n n2 \r\n \t \r\r\n ' />");
tw.WriteLine("<CAT>AB<![CDATA[CD]]> </CAT>");
tw.WriteLine("<CATMIXED>AB<![CDATA[CD]]> </CATMIXED>");
tw.WriteLine("<VALIDXMLLANG0 xml:lang=\"a\" />");
tw.WriteLine("<VALIDXMLLANG1 xml:lang=\"\" />");
tw.WriteLine("<VALIDXMLLANG2 xml:lang=\"ab-cd-\" />");
tw.WriteLine("<VALIDXMLLANG3 xml:lang=\"a b-cd\" />");
tw.Write("</PLAY>");
tw.Flush();
//Create external DTD file
FilePathUtil.addStream("AllNodeTypes.dtd", new MemoryStream());
TextWriter twDTD = new StreamWriter(FilePathUtil.getStream("AllNodeTypes.dtd"));
twDTD.WriteLine("<!ELEMENT elem2 (#PCDATA| a | b )* >");
twDTD.WriteLine("<!ELEMENT a ANY>");
twDTD.WriteLine("<!ELEMENT b ANY>");
twDTD.WriteLine("<!ELEMENT c ANY>");
twDTD.WriteLine("<!ATTLIST elem2 ");
twDTD.WriteLine("att1 ID #IMPLIED");
twDTD.WriteLine("att2 CDATA #IMPLIED");
twDTD.WriteLine("att3 CDATA #IMPLIED>");
twDTD.WriteLine("<!ATTLIST a refs IDREFS #IMPLIED>");
twDTD.Flush();
// Create Ent file
FilePathUtil.addStream("AllNodeTypes.ent", new MemoryStream());
TextWriter twENT = new StreamWriter(FilePathUtil.getStream("AllNodeTypes.ent"));
twENT.WriteLine("<!ELEMENT foo ANY>");
twENT.WriteLine("<!ENTITY % ext4 \"blah\">");
twENT.WriteLine("<!ENTITY ext3 \"%ext4;\">");
twENT.Flush();
}
public static void CreateInvalidDTDTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<?xml version=\"1.0\"?><!DOCTYPE Root [<!ELEMENT Root ANY><!ELEMENT E ANY><!ATTLIST E A1 NOTATION (N) #IMPLIED>]>");
tw.WriteLine("<Root><E A1=\"N\" /></Root>");
tw.Flush();
tw.Dispose();
}
public static void CreateValidDTDTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<?xml version=\"1.0\"?><!DOCTYPE Root [<!ELEMENT Root ANY><!ELEMENT E ANY><!ATTLIST E IMAGE_FORMAT (bmp|jpg|gif) #IMPLIED>]>");
tw.Write("<Root><E A1=\"gif\" /></Root>");
tw.Flush();
tw.Dispose();
}
public static void CreateWellFormedDTDTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.Write("<!DOCTYPE foo [<!ELEMENT foo (e1, e2, e3)><!ENTITY bar \"<e1> <e4 /> </e1> <e2> that </e2>\">");
tw.Write("<!ELEMENT e1 (e4)><!ELEMENT e2 ANY><!ELEMENT e3 ANY><!ELEMENT e4 ANY>]>");
tw.Write("<foo>&bar;<e3 /></foo>");
tw.Flush();
tw.Dispose();
}
public static void CreateNonWellFormedDTDTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.Write("<!DOCTYPE foo [<!ELEMENT foo (e1, e2, e3)><!ENTITY bar \"<e1> <e4 /> </e1> <e2> that </e2></e2>\">");
tw.Write("<!ELEMENT e1 (e4)><!ELEMENT e2 ANY><!ELEMENT e3 ANY><!ELEMENT e4 ANY>]>");
tw.Write("<foo>&bar;<e3 /></foo>");
tw.Flush();
tw.Dispose();
}
public static void CreateInvWellFormedDTDTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.Write("<!DOCTYPE foo [<!ELEMENT foo (e1, e2, e3)><!ENTITY bar \"<e1> this </e1> <e2> that </e2>\">");
tw.Write("<!ELEMENT e1 (e4)><!ELEMENT e2 ANY><!ELEMENT e3 ANY><!ELEMENT e4 ANY>]>");
tw.Write("<foo>&bar;<e3 /></foo>");
tw.Flush();
tw.Dispose();
}
public static void CreateInvalidXMLXDRTestFile(string strFileName)
{
// Create XDR before
CreateXDRTestFile(pValidXDR);
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<?xml version=\"1.0\" ?><e:Root xmlns:e=\"x-schema:xdrfile.xml\">");
tw.WriteLine("<e:e1>Element 1</e:e1></e:Root>");
tw.Flush();
tw.Dispose();
}
public static void CreateXDRXMLTestFile(string strFileName)
{
// Create XDR before
CreateXDRTestFile(pValidXDR);
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<bar xmlns=\"x-schema:XdrFile.xml\"> <tt /> <tt /></bar>");
tw.Flush();
tw.Dispose();
}
public static void CreateXDRTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<Schema xmlns=\"uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882\"><ElementType content=\"empty\" name=\"tt\"></ElementType>");
tw.WriteLine("<ElementType content=\"eltOnly\" order=\"seq\" name=\"bar\" model=\"closed\"><element type=\"tt\" /><element type=\"tt\" /></ElementType>");
tw.WriteLine("</Schema>");
tw.Flush();
tw.Dispose();
}
public static void CreateInvalidNamespaceTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<NAMESPACE0 xmlns:bar=\"1\"><bar1:check>Namespace=1</bar1:check></NAMESPACE0>");
tw.Flush();
tw.Dispose();
}
public static void CreateNamespaceTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<DOCNAMESPACE>");
tw.WriteLine("<NAMESPACE0 xmlns:bar=\"1\"><bar:check>Namespace=1</bar:check></NAMESPACE0>");
tw.WriteLine("<NAMESPACE1 xmlns:bar=\"1\"><a><b><c><d><bar:check>Namespace=1</bar:check></d></c></b></a></NAMESPACE1>");
tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>");
tw.WriteLine("<EMPTY_NAMESPACE bar:Attr0=\"0\" xmlns:bar=\"1\" />");
tw.WriteLine("<EMPTY_NAMESPACE1 Attr0=\"0\" xmlns=\"14\" />");
tw.WriteLine("<NAMESPACE2 xmlns:bar=\"1\"><a><b><c xmlns:bar=\"2\"><d><bar:check>Namespace=2</bar:check></d></c></b></a></NAMESPACE2>");
tw.WriteLine("<NAMESPACE3 xmlns=\"1\"><a xmlns:a=\"2\" xmlns:b=\"3\" xmlns:c=\"4\"><b xmlns:d=\"5\" xmlns:e=\"6\" xmlns:f='7'><c xmlns:d=\"8\" xmlns:e=\"9\" xmlns:f=\"10\">");
tw.WriteLine("<d xmlns:g=\"11\" xmlns:h=\"12\"><check>Namespace=1</check><testns xmlns=\"100\"><check100>Namespace=100</check100></testns><check1>Namespace=1</check1><d:check8>Namespace=8</d:check8></d></c><d:check5>Namespace=5</d:check5></b></a>");
tw.WriteLine("<a13 a:check=\"Namespace=13\" xmlns:a=\"13\" /><check14 xmlns=\"14\">Namespace=14</check14></NAMESPACE3>");
tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>");
tw.WriteLine("</DOCNAMESPACE>");
tw.Flush();
tw.Dispose();
}
public static void CreateXmlLangTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<PGROUP>");
tw.WriteLine("<PERSONA>DROMIO OF EPHESUS</PERSONA>");
tw.WriteLine("<PERSONA>DROMIO OF SYRACUSE</PERSONA>");
tw.WriteLine("<XMLLANG0 xml:lang=\"en-US\">What color is it?</XMLLANG0>");
tw.Write("<XMLLANG1 xml:lang=\"en-GB\">What color is it?<a><b><c>Language Test</c><PERSONA>DROMIO OF EPHESUS</PERSONA></b></a></XMLLANG1>");
tw.WriteLine("<NOXMLLANG />");
tw.WriteLine("<EMPTY_XMLLANG Attr0=\"0\" xml:lang=\"en-US\" />");
tw.WriteLine("<XMLLANG2 xml:lang=\"en-US\">What color is it?<TITLE><!-- this is a comment--></TITLE><XMLLANG1 xml:lang=\"en-GB\">Testing language<XMLLANG0 xml:lang=\"en-US\">What color is it?</XMLLANG0>haha </XMLLANG1>hihihi</XMLLANG2>");
tw.WriteLine("<DONEXMLLANG />");
tw.WriteLine("</PGROUP>");
tw.Flush();
tw.Dispose();
}
public static void CreateXmlSpaceTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<PGROUP>");
tw.WriteLine("<PERSONA>DROMIO OF EPHESUS</PERSONA>");
tw.WriteLine("<PERSONA>DROMIO OF SYRACUSE</PERSONA>");
tw.WriteLine("<XMLSPACE1 xml:space=\'default\'>< ></XMLSPACE1>");
tw.Write("<XMLSPACE2 xml:space=\'preserve\'>< ><a><b><c>Space Test</c><PERSONA>DROMIO OF SYRACUSE</PERSONA></b></a></XMLSPACE2>");
tw.WriteLine("<NOSPACE />");
tw.WriteLine("<EMPTY_XMLSPACE Attr0=\"0\" xml:space=\'default\' />");
tw.WriteLine("<XMLSPACE2A xml:space=\'default\'>< <XMLSPACE3 xml:space=\'preserve\'> < > <XMLSPACE4 xml:space=\'default\'> < > </XMLSPACE4> test </XMLSPACE3> ></XMLSPACE2A>");
tw.WriteLine("<GRPDESCR>twin brothers, and attendants on the two Antipholuses.</GRPDESCR>");
tw.WriteLine("</PGROUP>");
tw.Flush();
tw.Dispose();
}
public static void CreateJunkTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
string str = new string('Z', (1 << 20) - 1);
tw.Write(str);
tw.Flush();
tw.Dispose();
}
public static void CreateBase64TestFile(string strFileName)
{
byte[] Wbase64 = new byte[2048];
int Wbase64len = 0;
byte[] WNumOnly = new byte[1024];
int WNumOnlylen = 0;
byte[] WTextOnly = new byte[1024];
int WTextOnlylen = 0;
int i = 0;
for (i = 0; i < strBase64.Length; i++)
{
WriteToBuffer(ref Wbase64, ref Wbase64len, System.BitConverter.GetBytes(strBase64[i]));
}
for (i = 52; i < strBase64.Length; i++)
{
WriteToBuffer(ref WNumOnly, ref WNumOnlylen, System.BitConverter.GetBytes(strBase64[i]));
}
for (i = 0; i < strBase64.Length - 12; i++)
{
WriteToBuffer(ref WTextOnly, ref WTextOnlylen, System.BitConverter.GetBytes(strBase64[i]));
}
FilePathUtil.addStream(strFileName, new MemoryStream());
XmlWriter w = XmlWriter.Create(FilePathUtil.getStream(strFileName));
w.WriteStartDocument();
w.WriteDocType("Root", null, null, "<!ENTITY e 'abc'>");
w.WriteStartElement("Root");
w.WriteStartElement("ElemAll");
w.WriteBase64(Wbase64, 0, (int)Wbase64len);
w.WriteEndElement();
w.WriteStartElement("ElemEmpty");
w.WriteString(string.Empty);
w.WriteEndElement();
w.WriteStartElement("ElemNum");
w.WriteBase64(WNumOnly, 0, (int)WNumOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemText");
w.WriteBase64(WTextOnly, 0, (int)WTextOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemNumText");
w.WriteBase64(WTextOnly, 0, (int)WTextOnlylen);
w.WriteBase64(WNumOnly, 0, (int)WNumOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemLong");
for (i = 0; i < 10; i++)
w.WriteBase64(Wbase64, 0, (int)Wbase64len);
w.WriteEndElement();
w.WriteElementString("ElemErr", "a&AQID");
w.WriteStartElement("ElemMixed");
w.WriteRaw("D2BAa<MIX>abc</MIX>AQID");
w.WriteEndElement();
w.WriteEndElement();
w.Flush();
}
public static void CreateBinHexTestFile(string strFileName)
{
byte[] Wbinhex = new byte[2000];
int Wbinhexlen = 0;
byte[] WNumOnly = new byte[2000];
int WNumOnlylen = 0;
byte[] WTextOnly = new byte[2000];
int WTextOnlylen = 0;
int i = 0;
for (i = 0; i < strBinHex.Length; i++)
{
WriteToBuffer(ref Wbinhex, ref Wbinhexlen, System.BitConverter.GetBytes(strBinHex[i]));
}
for (i = 0; i < 10; i++)
{
WriteToBuffer(ref WNumOnly, ref WNumOnlylen, System.BitConverter.GetBytes(strBinHex[i]));
}
for (i = 10; i < strBinHex.Length; i++)
{
WriteToBuffer(ref WTextOnly, ref WTextOnlylen, System.BitConverter.GetBytes(strBinHex[i]));
}
FilePathUtil.addStream(strFileName, new MemoryStream());
XmlWriter w = XmlWriter.Create(FilePathUtil.getStream(strFileName));
w.WriteStartElement("Root");
w.WriteStartElement("ElemAll");
w.WriteBinHex(Wbinhex, 0, (int)Wbinhexlen);
w.WriteEndElement();
w.Flush();
w.WriteStartElement("ElemEmpty");
w.WriteString(string.Empty);
w.WriteEndElement();
w.WriteStartElement("ElemNum");
w.WriteBinHex(WNumOnly, 0, (int)WNumOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemText");
w.WriteBinHex(WTextOnly, 0, (int)WTextOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemNumText");
w.WriteBinHex(WNumOnly, 0, (int)WNumOnlylen);
w.WriteBinHex(WTextOnly, 0, (int)WTextOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemLong");
for (i = 0; i < 10; i++)
w.WriteBinHex(Wbinhex, 0, (int)Wbinhexlen);
w.WriteEndElement();
w.WriteElementString("ElemErr", "a&A2A3");
w.WriteEndElement();
w.Flush();
w.Dispose();
}
public static void CreateBigElementTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
string str = new string('Z', (1 << 20) - 1);
tw.WriteLine("<Root>");
tw.Write("<");
tw.Write(str);
tw.WriteLine("X />");
tw.Flush();
tw.Write("<");
tw.Write(str);
tw.WriteLine("Y />");
tw.WriteLine("</Root>");
tw.Flush();
tw.Dispose();
}
public static void CreateXSLTStyleSheetWCopyTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">");
tw.WriteLine("<xsl:template match=\"/\">");
tw.WriteLine("<xsl:copy-of select=\"/\" />");
tw.WriteLine("</xsl:template>");
tw.WriteLine("</xsl:stylesheet>");
tw.Flush();
tw.Dispose();
}
public static void CreateConstructorTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<?xml version=\"1.0\"?>");
tw.WriteLine("<ROOT>");
tw.WriteLine("<ATTRIBUTE3 a1='a1value' a2='a2value' a3='a3value' />");
tw.Write("</ROOT>");
tw.Flush();
tw.Dispose();
}
public static void CreateLineNumberTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<?xml version=\"1.0\" ?>");
tw.WriteLine(" <!DOCTYPE DT [");
tw.WriteLine("<!ELEMENT root ANY>");
tw.WriteLine("<!ENTITY % ext SYSTEM \"LineNumber.ent\">%ext;");
tw.WriteLine("<!ENTITY e1 'e1foo'>]>");
tw.WriteLine("<ROOT>");
tw.WriteLine(" <ELEMENT a0='a0&e1;v' a1='a1value' a2='a2&e1;v'><EMBEDDED /></ELEMENT>");
tw.WriteLine("<![CDATA[ This section contains CDATA]]>");
tw.WriteLine("<CHARENTITY>ABCCD</CHARENTITY>");
tw.WriteLine("<COMMENT><!-- comment node--></COMMENT>");
tw.WriteLine("<ENTITYREF>A&e1;B&ext3;C</ENTITYREF>");
tw.WriteLine("<?PI1?>");
tw.WriteLine("<SKIP />");
tw.WriteLine("<BASE64>9F6hJU++</BASE64>");
tw.WriteLine("<BINHEX>9F6C</BINHEX>");
tw.WriteLine("<BOOLXSD>true</BOOLXSD>");
tw.WriteLine("<BOOLXDR>true</BOOLXDR>");
tw.WriteLine("<DATE>2005-02-14</DATE>");
tw.WriteLine("<DATETIME>2005-02-14T14:25:44</DATETIME>");
tw.WriteLine("<DECIMAL>-14.25</DECIMAL>");
tw.WriteLine("<INT>-1425</INT>");
tw.WriteLine("<TIME>12:05:24</TIME>");
tw.WriteLine("<TIMESPAN>3.12:05:24</TIMESPAN>");
tw.WriteLine(" <?PI2 abc?>");
tw.WriteLine("<SIG_WHITESPACE xml:space='preserve'> </SIG_WHITESPACE>");
tw.Write("</ROOT>");
tw.Flush();
tw.Dispose();
// Create Ent file
FilePathUtil.addStream("LineNumber.ent", new MemoryStream());
TextWriter twENT = new StreamWriter(FilePathUtil.getStream("LineNumber.ent"));
twENT.WriteLine("<!ENTITY % ext4 \"blah\">");
twENT.WriteLine("<!ENTITY ext31 \"%ext4;\">");
twENT.WriteLine("<!ENTITY ext3 'zzz'>");
twENT.Flush();
twENT.Dispose();
}
public static void CreateLbNormalizationTestFile(string strFileName)
{
TextWriter tw = new StreamWriter(FilePathUtil.getStream(strFileName));
tw.WriteLine("<?xml version=\"1.0\" standalone=\"no\"?>");
tw.WriteLine("<!DOCTYPE ROOT");
tw.WriteLine("[");
tw.WriteLine("<!ENTITY ge1 SYSTEM \"{0}\">", pLbNormEnt1);
tw.WriteLine("<!ENTITY % pe SYSTEM \"{0}\">", pLbNormEnt2);
tw.WriteLine("%pe;");
tw.WriteLine("]>");
tw.WriteLine("<ROOT>&ge1;&ext1;</ROOT>");
tw.Flush();
tw.Dispose();
// Create Ent file
FilePathUtil.addStream(pLbNormEnt1, new MemoryStream());
TextWriter twENT = new StreamWriter(FilePathUtil.getStream(pLbNormEnt1));
twENT.WriteLine("<?xml version=\"1.0\"?>");
twENT.WriteLine("<E1 xml:space=\"preserve\">");
twENT.WriteLine("</E1>");
twENT.WriteLine();
twENT.Flush();
twENT.Dispose();
// Create Ent file
FilePathUtil.addStream(pLbNormEnt2, new MemoryStream());
twENT = new StreamWriter(FilePathUtil.getStream(pLbNormEnt2));
twENT.WriteLine("<!ENTITY ext1 \"<E3>");
twENT.WriteLine("</E3>\">");
twENT.WriteLine("");
twENT.WriteLine();
twENT.Flush();
twENT.Dispose();
}
public bool FindNodeType(XmlReader r, XmlNodeType _nodetype)
{
if (r.NodeType == _nodetype)
return false;
while (r.Read())
{
if (r.NodeType == XmlNodeType.EntityReference)
{
if (r.CanResolveEntity)
r.ResolveEntity();
}
if (r.NodeType == XmlNodeType.ProcessingInstruction && r.NodeType == XmlNodeType.XmlDeclaration)
{
if (string.Compare(r.Name, 0, ST_XML, 0, 3) != 0)
return true;
}
if (r.NodeType == _nodetype)
{
return true;
}
if (r.NodeType == XmlNodeType.Element && (_nodetype == XmlNodeType.Attribute))
{
if (r.MoveToFirstAttribute())
{
return true;
}
}
}
return false;
}
}
// Class Signatures used for verifying names
public class Signatures
{
private string[] _stringsExpected;
public int m_index;
public Signatures(string[] strs)
{
m_index = 0;
_stringsExpected = strs;
}
public static implicit operator Signatures(string[] strs)
{
return new Signatures(strs);
}
}
public class CustomReader : XmlReader
{
private XmlReader _tr = null;
public CustomReader(TextReader txtReader, bool isFragment)
{
if (!isFragment)
_tr = XmlReader.Create(txtReader);
else
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
_tr = XmlReader.Create(txtReader, settings);
}
}
public CustomReader(string url, bool isFragment)
{
XmlReaderSettings settings = new XmlReaderSettings();
if (!isFragment)
{
_tr = XmlReader.Create(url, settings);
}
else
{
settings.ConformanceLevel = ConformanceLevel.Fragment;
_tr = XmlReader.Create(url, settings);
}
}
public override int Depth
{
get
{
return _tr.Depth;
}
}
public override string Value
{
get
{
return _tr.Value;
}
}
public override bool MoveToElement()
{
return _tr.MoveToElement();
}
public override bool IsEmptyElement
{
get
{
return _tr.IsEmptyElement;
}
}
public override string LocalName
{
get
{
return _tr.LocalName;
}
}
public override XmlNodeType NodeType
{
get
{
return _tr.NodeType;
}
}
public override bool MoveToNextAttribute()
{
return _tr.MoveToNextAttribute();
}
public override bool MoveToFirstAttribute()
{
return _tr.MoveToFirstAttribute();
}
public override string LookupNamespace(string prefix)
{
return _tr.LookupNamespace(prefix);
}
public new void Dispose()
{
_tr.Dispose();
}
public override bool EOF
{
get
{
return _tr.EOF;
}
}
public override bool HasValue
{
get
{
return _tr.HasValue;
}
}
public override string NamespaceURI
{
get
{
return _tr.NamespaceURI;
}
}
public override bool Read()
{
return _tr.Read();
}
public override XmlNameTable NameTable
{
get
{
return _tr.NameTable;
}
}
public override bool CanResolveEntity
{
get
{
return _tr.CanResolveEntity;
}
}
public override void ResolveEntity()
{
_tr.ResolveEntity();
}
public override string GetAttribute(string name, string namespaceURI)
{
return _tr.GetAttribute(name, namespaceURI);
}
public override string GetAttribute(string name)
{
return _tr.GetAttribute(name);
}
public override string GetAttribute(int i)
{
return _tr.GetAttribute(i);
}
public override string BaseURI
{
get
{
return _tr.BaseURI;
}
}
public override bool ReadAttributeValue()
{
return _tr.ReadAttributeValue();
}
public override string Prefix
{
get
{
return _tr.Prefix;
}
}
public override bool MoveToAttribute(string name, string ns)
{
return _tr.MoveToAttribute(name, ns);
}
public override bool MoveToAttribute(string name)
{
return _tr.MoveToAttribute(name);
}
public override int AttributeCount
{
get
{
return _tr.AttributeCount;
}
}
public override ReadState ReadState
{
get
{
return _tr.ReadState;
}
}
}
public class CustomWriter : XmlWriter
{
private XmlWriter _writer = null;
private TextWriter _stream = null;
public CustomWriter(TextWriter stream, XmlWriterSettings xws)
{
_stream = stream;
_writer = XmlWriter.Create(stream, xws);
}
public override void WriteStartDocument()
{
_writer.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
_writer.WriteStartDocument(standalone);
}
public override void WriteEndDocument()
{
_writer.WriteEndDocument();
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
_writer.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
_writer.WriteStartElement(prefix, localName, ns);
}
public override void WriteEndElement()
{
_writer.WriteEndElement();
}
public override void WriteFullEndElement()
{
_writer.WriteFullEndElement();
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
_writer.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
_writer.WriteEndAttribute();
}
public override void WriteCData(string text)
{
_writer.WriteCData(text);
}
public override void WriteComment(string text)
{
_writer.WriteComment(text);
}
public override void WriteProcessingInstruction(string name, string text)
{
_writer.WriteProcessingInstruction(name, text);
}
public override void WriteEntityRef(string name)
{
_writer.WriteEntityRef(name);
}
public override void WriteCharEntity(char ch)
{
_writer.WriteCharEntity(ch);
}
public override void WriteWhitespace(string ws)
{
_writer.WriteWhitespace(ws);
}
public override void WriteString(string text)
{
_writer.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
_writer.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteChars(char[] buffer, int index, int count)
{
_writer.WriteChars(buffer, index, count);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
_writer.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
_writer.WriteRaw(data);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
_writer.WriteBase64(buffer, index, count);
}
public override WriteState WriteState
{
get
{
return _writer.WriteState;
}
}
public override XmlSpace XmlSpace
{
get
{
return _writer.XmlSpace;
}
}
public override string XmlLang
{
get
{
return _writer.XmlLang;
}
}
public new void Dispose()
{
_writer.Dispose();
_stream.Dispose();
}
public override void Flush()
{
_writer.Flush();
}
public override string LookupPrefix(string ns)
{
return _writer.LookupPrefix(ns);
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.unity3d.ui.ucore
{
public class GOButtonUCore : global::pony.unity3d.ui.TextureButton
{
public GOButtonUCore(global::haxe.lang.EmptyObject empty) : base(global::haxe.lang.EmptyObject.EMPTY)
{
unchecked
{
}
#line default
}
public GOButtonUCore() : base()
{
unchecked
{
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return new global::pony.unity3d.ui.ucore.GOButtonUCore(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return new global::pony.unity3d.ui.ucore.GOButtonUCore();
}
#line default
}
public global::UnityEngine.GameObject[] goDefs;
public global::UnityEngine.GameObject[] goOvers;
public global::UnityEngine.GameObject[] goPress;
public global::UnityEngine.GameObject glast;
public override void Start()
{
unchecked
{
#line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
object __temp_stmt718 = default(object);
#line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
{
#line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("goRestore"), ((int) (1677871622) ))) ), 0);
#line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
__temp_stmt718 = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 23 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.core.changeVisual.@add(__temp_stmt718, default(global::haxe.lang.Null<int>));
#line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
{
#line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
int _g1 = 0;
#line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
int _g = ( this.goOvers as global::System.Array ).Length;
#line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
while (( _g1 < _g ))
{
#line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
int i = _g1++;
#line 25 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
if (( this.goOvers[i] != default(global::UnityEngine.GameObject) ))
{
this.goOvers[i].active = false;
global::haxe.lang.Function __temp_stmt720 = default(global::haxe.lang.Function);
#line 27 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
{
#line 27 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::Array<object> g = new global::Array<object>(new object[]{this.goOvers[i]});
#line 27 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::Array<object> f1 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("goset"), ((int) (402393722) ))) )});
#line 27 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
__temp_stmt720 = new global::pony.unity3d.ui.ucore.GOButtonUCore_Start_27__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f1) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (g) ))) ));
}
#line 27 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
object __temp_stmt719 = global::pony._Function.Function_Impl_.@from(__temp_stmt720, 1);
#line 27 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Focus, i})).@add(global::pony.events._Listener.Listener_Impl_._fromFunction(__temp_stmt719, true), default(global::haxe.lang.Null<int>));
global::haxe.lang.Function __temp_stmt722 = default(global::haxe.lang.Function);
#line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
{
#line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::Array<object> g1 = new global::Array<object>(new object[]{this.goOvers[i]});
#line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::Array<object> f2 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("goset"), ((int) (402393722) ))) )});
#line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
__temp_stmt722 = new global::pony.unity3d.ui.ucore.GOButtonUCore_Start_28__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (g1) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f2) ))) ));
}
#line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
object __temp_stmt721 = global::pony._Function.Function_Impl_.@from(__temp_stmt722, 1);
#line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Leave, i})).@add(global::pony.events._Listener.Listener_Impl_._fromFunction(__temp_stmt721, true), default(global::haxe.lang.Null<int>));
}
}
}
#line 31 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
{
#line 31 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
int _g11 = 0;
#line 31 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
int _g2 = ( this.goPress as global::System.Array ).Length;
#line 31 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
while (( _g11 < _g2 ))
{
#line 31 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
int i1 = _g11++;
#line 31 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
if (( this.goPress[i1] != default(global::UnityEngine.GameObject) ))
{
this.goPress[i1].active = false;
global::haxe.lang.Function __temp_stmt724 = default(global::haxe.lang.Function);
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
{
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::Array<object> g2 = new global::Array<object>(new object[]{this.goPress[i1]});
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::Array<object> f3 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("goset"), ((int) (402393722) ))) )});
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
__temp_stmt724 = new global::pony.unity3d.ui.ucore.GOButtonUCore_Start_33__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f3) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (g2) ))) ));
}
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
object __temp_stmt723 = global::pony._Function.Function_Impl_.@from(__temp_stmt724, 1);
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Press, i1})).@add(global::pony.events._Listener.Listener_Impl_._fromFunction(__temp_stmt723, true), default(global::haxe.lang.Null<int>));
}
}
}
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
int _g12 = 0;
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
int _g3 = ( this.goDefs as global::System.Array ).Length;
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
while (( _g12 < _g3 ))
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
int i2 = _g12++;
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
if (( this.goDefs[i2] != default(global::UnityEngine.GameObject) ))
{
this.goDefs[i2].active = false;
global::haxe.lang.Function __temp_stmt726 = default(global::haxe.lang.Function);
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::Array<object> g3 = new global::Array<object>(new object[]{this.goDefs[i2]});
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::Array<object> f4 = new global::Array<object>(new object[]{((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("goset"), ((int) (402393722) ))) )});
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
__temp_stmt726 = new global::pony.unity3d.ui.ucore.GOButtonUCore_Start_38__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (g3) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (f4) ))) ));
}
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
object __temp_stmt725 = global::pony._Function.Function_Impl_.@from(__temp_stmt726, 1);
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.core.changeVisual.subArgs(new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Default, i2})).@add(global::pony.events._Listener.Listener_Impl_._fromFunction(__temp_stmt725, true), default(global::haxe.lang.Null<int>));
}
}
}
#line 41 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
base.Start();
}
#line default
}
public virtual void goset(global::UnityEngine.GameObject g, global::pony.events.Event e)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.restoreColor();
this.guiTexture.enabled = false;
g.active = true;
this.glast = g;
{
#line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
if (( e.parent != default(global::pony.events.Event) ))
{
#line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
e.parent.stopPropagation();
}
#line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
e._stopPropagation = true;
}
}
#line default
}
public virtual void goRestore()
{
unchecked
{
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.guiTexture.enabled = true;
if (( this.glast != default(global::UnityEngine.GameObject) ))
{
#line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.glast.active = false;
}
}
#line default
}
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
switch (hash)
{
case 368233021:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.glast = ((global::UnityEngine.GameObject) (@value) );
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return @value;
}
case 2020972603:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.goPress = ((global::UnityEngine.GameObject[]) (@value) );
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return @value;
}
case 1739840855:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.goOvers = ((global::UnityEngine.GameObject[]) (@value) );
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return @value;
}
case 1165757782:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.goDefs = ((global::UnityEngine.GameObject[]) (@value) );
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return @value;
}
default:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
switch (hash)
{
case 1677871622:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("goRestore"), ((int) (1677871622) ))) );
}
case 402393722:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("goset"), ((int) (402393722) ))) );
}
case 389604418:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Start"), ((int) (389604418) ))) );
}
case 368233021:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return this.glast;
}
case 2020972603:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return this.goPress;
}
case 1739840855:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return this.goOvers;
}
case 1165757782:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return this.goDefs;
}
default:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
switch (hash)
{
case 389604418:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return global::haxe.lang.Runtime.slowCallField(this, field, dynargs);
}
case 1677871622:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.goRestore();
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
break;
}
case 402393722:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.goset(((global::UnityEngine.GameObject) (dynargs[0]) ), ((global::pony.events.Event) (dynargs[1]) ));
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
break;
}
default:
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return base.__hx_invokeField(field, hash, dynargs);
}
}
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return default(object);
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
baseArr.push("glast");
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
baseArr.push("goPress");
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
baseArr.push("goOvers");
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
baseArr.push("goDefs");
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
{
#line 13 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.unity3d.ui.ucore
{
public class GOButtonUCore_Start_27__Fun : global::haxe.lang.Function
{
public GOButtonUCore_Start_27__Fun(global::Array<object> f1, global::Array<object> g) : base(1, 0)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.f1 = f1;
#line 27 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.g = g;
}
#line default
}
public override object __hx_invoke1_o(double __fn_float1, object __fn_dyn1)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::pony.events.Event e = ( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (((global::pony.events.Event) (((object) (__fn_float1) )) )) : (((global::pony.events.Event) (__fn_dyn1) )) );
#line 27 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return ((global::haxe.lang.Function) (this.f1[0]) ).__hx_invoke2_o(default(double), default(double), ((global::UnityEngine.GameObject) (this.g[0]) ), e);
}
#line default
}
public global::Array<object> f1;
public global::Array<object> g;
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.unity3d.ui.ucore
{
public class GOButtonUCore_Start_28__Fun : global::haxe.lang.Function
{
public GOButtonUCore_Start_28__Fun(global::Array<object> g1, global::Array<object> f2) : base(1, 0)
{
unchecked
{
#line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.g1 = g1;
#line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.f2 = f2;
}
#line default
}
public override object __hx_invoke1_o(double __fn_float1, object __fn_dyn1)
{
unchecked
{
#line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::pony.events.Event e1 = ( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (((global::pony.events.Event) (((object) (__fn_float1) )) )) : (((global::pony.events.Event) (__fn_dyn1) )) );
#line 28 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return ((global::haxe.lang.Function) (this.f2[0]) ).__hx_invoke2_o(default(double), default(double), ((global::UnityEngine.GameObject) (this.g1[0]) ), e1);
}
#line default
}
public global::Array<object> g1;
public global::Array<object> f2;
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.unity3d.ui.ucore
{
public class GOButtonUCore_Start_33__Fun : global::haxe.lang.Function
{
public GOButtonUCore_Start_33__Fun(global::Array<object> f3, global::Array<object> g2) : base(1, 0)
{
unchecked
{
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.f3 = f3;
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.g2 = g2;
}
#line default
}
public override object __hx_invoke1_o(double __fn_float1, object __fn_dyn1)
{
unchecked
{
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::pony.events.Event e2 = ( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (((global::pony.events.Event) (((object) (__fn_float1) )) )) : (((global::pony.events.Event) (__fn_dyn1) )) );
#line 33 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return ((global::haxe.lang.Function) (this.f3[0]) ).__hx_invoke2_o(default(double), default(double), ((global::UnityEngine.GameObject) (this.g2[0]) ), e2);
}
#line default
}
public global::Array<object> f3;
public global::Array<object> g2;
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.unity3d.ui.ucore
{
public class GOButtonUCore_Start_38__Fun : global::haxe.lang.Function
{
public GOButtonUCore_Start_38__Fun(global::Array<object> g3, global::Array<object> f4) : base(1, 0)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.g3 = g3;
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
this.f4 = f4;
}
#line default
}
public override object __hx_invoke1_o(double __fn_float1, object __fn_dyn1)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
global::pony.events.Event e3 = ( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (((global::pony.events.Event) (((object) (__fn_float1) )) )) : (((global::pony.events.Event) (__fn_dyn1) )) );
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/GOButtonUCore.hx"
return ((global::haxe.lang.Function) (this.f4[0]) ).__hx_invoke2_o(default(double), default(double), ((global::UnityEngine.GameObject) (this.g3[0]) ), e3);
}
#line default
}
public global::Array<object> g3;
public global::Array<object> f4;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Relay
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// HybridConnectionsOperations operations.
/// </summary>
public partial interface IHybridConnectionsOperations
{
/// <summary>
/// Lists the HybridConnection within the namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<HybridConnection>>> ListByNamespaceWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or Updates a service HybridConnection. This operation is
/// idempotent.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a HybridConnection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<HybridConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, HybridConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a HybridConnection .
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the description for the specified HybridConnection.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<HybridConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Authorization rules for a HybridConnection.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AuthorizationRule>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or Updates an authorization rule for a HybridConnection
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='parameters'>
/// The authorization rule parameters
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AuthorizationRule>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, string authorizationRuleName, AuthorizationRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a HybridConnection authorization rule
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// HybridConnection authorizationRule for a HybridConnection by name.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AuthorizationRule>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Primary and Secondary ConnectionStrings to the HybridConnection.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AuthorizationRuleKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Regenerates the Primary or Secondary ConnectionStrings to the
/// HybridConnection
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate Auth Rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AuthorizationRuleKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, string authorizationRuleName, RegenerateKeysParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the HybridConnection within the namespace.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<HybridConnection>>> ListByNamespaceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Authorization rules for a HybridConnection.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AuthorizationRule>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System.Collections;
using System.Drawing;
namespace GuruComponents.CodeEditor.CodeEditor.Syntax
{
/// <summary>
/// Parser state of a row
/// </summary>
public enum RowState
{
/// <summary>
/// the row is not parsed
/// </summary>
NotParsed = 0,
/// <summary>
/// the row is segment parsed
/// </summary>
SegmentParsed = 1,
/// <summary>
/// the row is both segment and keyword parsed
/// </summary>
AllParsed = 2
}
/// <summary>
/// The row class represents a row in a SyntaxDocument
/// </summary>
public sealed class Row : IEnumerable
{
#region General Declarations
private string mText = "";
internal WordCollection mWords = new WordCollection();
public WordCollection FormattedWords = new WordCollection();
/// <summary>
/// Segments that start on this row
/// </summary>
public SegmentCollection StartSegments = new SegmentCollection();
/// <summary>
/// Segments that ends in this row
/// </summary>
public SegmentCollection EndSegments = new SegmentCollection();
/// <summary>
/// The owner document
/// </summary>
public SyntaxDocument Document = null;
/// <summary>
/// The first collapsable segment on this row.
/// </summary>
public Segment StartSegment = null;
/// <summary>
/// The first segment that terminates on this row.
/// </summary>
public Segment EndSegment = null;
/// <summary>
///
/// </summary>
public Segment Expansion_StartSegment = null;
/// <summary>
///
/// </summary>
public Segment Expansion_EndSegment = null;
private RowState _RowState = RowState.NotParsed;
#region PUBLIC PROPERTY BACKCOLOR
private Color _BackColor = Color.Transparent;
public Color BackColor
{
get { return _BackColor; }
set { _BackColor = value; }
}
#endregion
public int Depth
{
get
{
int i = 0;
Segment s = this.StartSegment;
while (s != null)
{
if (s.Scope != null && s.Scope.CauseIndent)
i++;
s = s.Parent;
}
// if (i>0)
// i--;
if (ShouldOutdent)
i--;
return i;
}
}
public bool ShouldOutdent
{
get
{
if (this.StartSegment.EndRow == this)
{
if (this.StartSegment.Scope.CauseIndent)
return true;
}
return false;
}
}
/// <summary>
/// Collection of Image indices assigned to a row.
/// </summary>
/// <example>
/// <b>Add an image to the current row.</b>
/// <code>
/// MySyntaxBox.Caret.CurrentRow.Images.Add(3);
/// </code>
/// </example>
public ImageIndexCollection Images = new ImageIndexCollection();
/// <summary>
/// Object tag for storage of custom user data..
/// </summary>
/// <example>
/// <b>Assign custom data to a row</b>
/// <code>
/// //custom data class
/// class CustomData{
/// public int abc=123;
/// publci string def="abc";
/// }
///
/// ...
///
/// //assign custom data to a row
/// Row MyRow=MySyntaxBox.Caret.CurrentRow;
/// CustomData MyData=new CustomData();
/// MyData.abc=1337;
/// MyRow.Tag=MyData;
///
/// ...
///
/// //read custom data from a row
/// Row MyRow=MySyntaxBox.Caret.CurrentRow;
/// if (MyRow.Tag != null){
/// CustomData MyData=(CustomData)MyRow.Tag;
/// if (MyData.abc==1337){
/// //Do something...
/// }
/// }
///
///
/// </code>
/// </example>
public object Tag = null;
/// <summary>
/// The parse state of this row
/// </summary>
/// <example>
/// <b>Test if the current row is fully parsed.</b>
/// <code>
/// if (MySyntaxBox.Caret.CurrentRow.RowState==RowState.AllParsed)
/// {
/// //do something
/// }
/// </code>
/// </example>
public RowState RowState
{
get { return _RowState; }
set
{
if (value == _RowState)
return;
if (value == RowState.SegmentParsed && !InKeywordQueue)
{
this.Document.KeywordQueue.Add(this);
this.InKeywordQueue = true;
}
if ((value == RowState.AllParsed || value == RowState.NotParsed) && InKeywordQueue)
{
this.Document.KeywordQueue.Remove(this);
this.InKeywordQueue = false;
}
_RowState = value;
}
}
//----Lookuptables-----------------
// public char[] Buffer_Text =null;
// // public char[] Buffer_Separators =null;
//---------------------------------
/// <summary>
/// Returns true if the row is in the owner documents parse queue
/// </summary>
public bool InQueue = false; //is this line in the parseQueue?
/// <summary>
/// Returns true if the row is in the owner documents keyword parse queue
/// </summary>
public bool InKeywordQueue = false; //is this line in the parseQueue?
private bool mBookmarked = false; //is this line bookmarked?
private bool mBreakpoint = false; //Does this line have a breakpoint?
/// <summary>
/// For public use only
/// </summary>
public int Indent = 0; //value indicating how much this line should be indented (c style)
/// <summary>
/// For public use only
/// </summary>
public int Expansion_PixelStart = 0;
/// <summary>
/// For public use only
/// </summary>
public int Expansion_StartChar = 0;
/// <summary>
/// For public use only
/// </summary>
public int Expansion_PixelEnd = 0;
/// <summary>
/// For public use only
/// </summary>
public int Expansion_EndChar = 0;
#endregion
public void Clear()
{
mWords = new WordCollection();
}
/// <summary>
/// If the row is hidden inside a collapsed segment , call this method to make the collapsed segments expanded.
/// </summary>
public void EnsureVisible()
{
if (this.RowState == RowState.NotParsed)
return;
Segment seg = this.StartSegment;
while (seg != null)
{
seg.Expanded = true;
seg = seg.Parent;
}
this.Document.ResetVisibleRows();
}
/// <summary>
/// Gets or Sets if this row has a bookmark or not.
/// </summary>
public bool Bookmarked
{
get { return mBookmarked; }
set
{
mBookmarked = value;
if (value)
Document.InvokeBookmarkAdded(this);
else
Document.InvokeBookmarkRemoved(this);
Document.InvokeChange();
}
}
/// <summary>
/// Gets or Sets if this row has a breakpoint or not.
/// </summary>
public bool Breakpoint
{
get { return mBreakpoint; }
set
{
mBreakpoint = value;
if (value)
Document.InvokeBreakPointAdded(this);
else
Document.InvokeBreakPointRemoved(this);
Document.InvokeChange();
}
}
public Word Add(string text)
{
Word xw = new Word();
xw.Row = this;
xw.Text = text;
mWords.Add(xw);
return xw;
}
/// <summary>
/// Returns the number of words in the row.
/// (this only applied if the row is fully parsed)
/// </summary>
public int Count
{
get { return mWords.Count; }
}
/// <summary>
/// Gets or Sets the text of the row.
/// </summary>
public string Text
{
get { return mText; }
set
{
bool ParsePreview = false;
if (mText != value)
{
ParsePreview = true;
this.Document.Modified = true;
}
mText = value;
if (Document != null)
{
if (ParsePreview)
{
Document.Parser.ParsePreviewLine(Document.IndexOf(this));
this.Document.OnApplyFormatRanges(this);
}
AddToParseQueue();
}
}
}
/// <summary>
/// Adds this row to the parse queue
/// </summary>
public void AddToParseQueue()
{
if (!InQueue)
Document.ParseQueue.Add(this);
InQueue = true;
this.RowState = RowState.NotParsed;
}
/// <summary>
/// Assigns a new text to the row.
/// </summary>
/// <param name="Text"></param>
public void SetText(string Text)
{
this.Document.StartUndoCapture();
TextPoint tp = new TextPoint(0, this.Index);
TextRange tr = new TextRange();
tr.FirstColumn = 0;
tr.FirstRow = tp.Y;
tr.LastColumn = this.Text.Length;
tr.LastRow = tp.Y;
this.Document.StartUndoCapture();
//delete the current line
this.Document.PushUndoBlock(UndoAction.DeleteRange, this.Document.GetRange(tr), tr.FirstColumn, tr.FirstRow);
//alter the text
this.Document.PushUndoBlock(UndoAction.InsertRange, Text, tp.X, tp.Y);
this.Text = Text;
this.Document.EndUndoCapture();
this.Document.InvokeChange();
}
private char[] GetSeparatorBuffer(string text, string separators)
{
char[] buff = text.ToCharArray();
for (int i = 0; i < text.Length; i++)
{
char c = buff[i];
if (separators.IndexOf(c) >= 0)
buff[i] = ' ';
else
buff[i] = '.';
}
return buff;
}
/// <summary>
/// Call this method to make all words match the case of their patterns.
/// (this only applies if the row is fully parsed)
/// </summary>
public void MatchCase()
{
string s = "";
foreach (Word w in mWords)
{
s = s + w.Text;
}
mText = s;
}
/// <summary>
/// Get the Word enumerator for this row
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return mWords.GetEnumerator();
}
/// <summary>
/// Return the Word object at the specified index.
/// </summary>
public Word this[int index]
{
get
{
if (index >= 0)
return (Word) mWords[index];
else
return new Word();
}
}
/// <summary>
/// Force a segment parse on the row.
/// </summary>
public void Parse()
{
Document.ParseRow(this);
}
/// <summary>
/// Forces the parser to parse this row directly
/// </summary>
/// <param name="ParseKeywords">true if keywords and operators should be parsed</param>
public void Parse(bool ParseKeywords)
{
Document.ParseRow(this, ParseKeywords);
}
public void SetExpansionSegment()
{
this.Expansion_StartSegment = null;
this.Expansion_EndSegment = null;
foreach (Segment s in this.StartSegments)
{
if (!this.EndSegments.Contains(s))
{
this.Expansion_StartSegment = s;
break;
}
}
foreach (Segment s in this.EndSegments)
{
if (!this.StartSegments.Contains(s))
{
this.Expansion_EndSegment = s;
break;
}
}
if (this.Expansion_EndSegment != null)
this.Expansion_StartSegment = null;
}
/// <summary>
/// Returns the whitespace string at the begining of this row.
/// </summary>
/// <returns>a string containing the whitespace at the begining of this row</returns>
public string GetLeadingWhitespace()
{
string s = mText;
int i = 0;
s = s.Replace(" ", " ");
for (i = 0; i < s.Length; i++)
{
if (s.Substring(i, 1) == " ")
{
}
else
{
break;
}
}
return mText.Substring(0, i);
}
public int StartWordIndex
{
get
{
if (this.Expansion_StartSegment == null)
return 0;
// if (this.Expansion_StartSegment.StartRow != this)
// return 0;
Word w = this.Expansion_StartSegment.StartWord;
int i = 0;
foreach (Word wo in this)
{
if (wo == w)
break;
i += wo.Text.Length;
}
return i;
}
}
public Word FirstNonWsWord
{
get
{
foreach (Word w in this)
{
if (w.Type == WordType.xtWord)
return w;
}
return null;
}
}
public string GetVirtualLeadingWhitespace()
{
int i = this.StartWordIndex;
string ws = "";
foreach (char c in this.Text)
{
if (c == '\t')
ws += c;
else
ws += ' ';
i--;
if (i <= 0)
break;
}
return ws;
}
/// <summary>
/// Returns the index of this row in the owner SyntaxDocument.
/// </summary>
public int Index
{
get { return this.Document.IndexOf(this); }
}
/// <summary>
/// Returns the visible index of this row in the owner SyntaxDocument
/// </summary>
public int VisibleIndex
{
get
{
int i = this.Document.VisibleRows.IndexOf(this);
if (i == -1)
{
if (this.StartSegment != null)
{
if (this.StartSegment.StartRow != null)
{
if (this.StartSegment.StartRow != this)
return this.StartSegment.StartRow.VisibleIndex;
else
return this.Index;
}
else
return this.Index;
}
else
return this.Index;
}
else
return this.Document.VisibleRows.IndexOf(this);
}
}
/// <summary>
/// Returns the next visible row.
/// </summary>
public Row NextVisibleRow
{
get
{
int i = this.VisibleIndex;
if (i > this.Document.VisibleRows.Count)
return null;
if (i + 1 < this.Document.VisibleRows.Count)
{
return this.Document.VisibleRows[i + 1];
}
else
return null;
}
}
/// <summary>
/// Returns the next row
/// </summary>
public Row NextRow
{
get
{
int i = this.Index;
if (i + 1 <= this.Document.Lines.Length - 1)
return this.Document[i + 1];
else
return null;
}
}
/// <summary>
/// Returns the first visible row before this row.
/// </summary>
public Row PrevVisibleRow
{
get
{
int i = this.VisibleIndex;
if (i < 0)
return null;
if (i - 1 >= 0)
return this.Document.VisibleRows[i - 1];
else
return null;
}
}
/// <summary>
/// Returns true if the row is collapsed
/// </summary>
public bool IsCollapsed
{
get
{
if (this.Expansion_StartSegment != null)
if (this.Expansion_StartSegment.Expanded == false)
return true;
return false;
}
}
/// <summary>
/// Returns true if this row is the last part of a collepsed segment
/// </summary>
public bool IsCollapsedEndPart
{
get
{
if (this.Expansion_EndSegment != null)
if (this.Expansion_EndSegment.Expanded == false)
return true;
return false;
}
}
/// <summary>
/// Returns true if this row can fold
/// </summary>
public bool CanFold
{
get { return (this.Expansion_StartSegment != null && this.Expansion_StartSegment.EndRow != null && this.Document.IndexOf(this.Expansion_StartSegment.EndRow) != 0); }
}
/// <summary>
/// Gets or Sets if this row is expanded.
/// </summary>
public bool Expanded
{
get
{
if (this.CanFold)
{
return (this.Expansion_StartSegment.Expanded);
}
else
{
return false;
}
}
set
{
if (this.CanFold)
{
this.Expansion_StartSegment.Expanded = value;
}
}
}
public string ExpansionText
{
get { return this.Expansion_StartSegment.Scope.ExpansionText; }
set
{
Scope oScope = this.Expansion_StartSegment.Scope;
Scope oNewScope = new Scope();
oNewScope.CaseSensitive = oScope.CaseSensitive;
oNewScope.CauseIndent = oScope.CauseIndent;
oNewScope.DefaultExpanded = oScope.DefaultExpanded;
oNewScope.EndPatterns = oScope.EndPatterns;
oNewScope.NormalizeCase = oScope.NormalizeCase;
oNewScope.Parent = oScope.Parent;
oNewScope.SpawnBlockOnEnd = oScope.SpawnBlockOnEnd;
oNewScope.SpawnBlockOnStart = oScope.SpawnBlockOnStart;
oNewScope.Start = oScope.Start;
oNewScope.Style = oScope.Style;
oNewScope.ExpansionText = value;
this.Expansion_StartSegment.Scope = oNewScope;
this.Document.InvokeChange();
}
}
/// <summary>
/// Returns true if this row is the end part of a collapsable segment
/// </summary>
public bool CanFoldEndPart
{
get { return (this.Expansion_EndSegment != null); }
}
/// <summary>
/// For public use only
/// </summary>
public bool HasExpansionLine
{
get
{
return (this.EndSegment.Parent != null);
}
}
/// <summary>
/// Returns the last row of a collapsable segment
/// (this only applies if this row is the start row of the segment)
/// </summary>
public Row Expansion_EndRow
{
get
{
if (this.CanFold)
return this.Expansion_StartSegment.EndRow;
else
return this;
}
}
/// <summary>
/// Returns the first row of a collapsable segment
/// (this only applies if this row is the last row of the segment)
/// </summary>
public Row Expansion_StartRow
{
get
{
if (this.CanFoldEndPart)
return this.Expansion_EndSegment.StartRow;
else
return this;
}
}
/// <summary>
/// Adds a word object to this row
/// </summary>
/// <param name="word">Word object</param>
public void Add(Word word)
{
this.mWords.Add(word);
}
/// <summary>
/// For public use only
/// </summary>
public Row VirtualCollapsedRow
{
get
{
Row r = new Row();
foreach (Word w in this)
{
if (this.Expansion_StartSegment == w.Segment)
break;
r.Add(w);
}
Word wo = r.Add(this.CollapsedText);
wo.Style = new TextStyle();
wo.Style.BackColor = Color.Silver;
wo.Style.ForeColor = Color.DarkBlue;
wo.Style.Bold = true;
bool found = false;
if (this.Expansion_EndRow != null)
{
foreach (Word w in this.Expansion_EndRow)
{
if (found)
r.Add(w);
if (w == this.Expansion_EndRow.Expansion_EndSegment.EndWord)
found = true;
}
}
return r;
}
}
/// <summary>
/// Returns the text that should be displayed if the row is collapsed.
/// </summary>
public string CollapsedText
{
get
{
string str = "";
int pos = 0;
foreach (Word w in this)
{
pos += w.Text.Length;
if (w.Segment == this.Expansion_StartSegment)
{
str = this.Text.Substring(pos).Trim();
break;
}
}
if (this.Expansion_StartSegment.Scope.ExpansionText != "")
str = this.Expansion_StartSegment.Scope.ExpansionText.Replace("***", str);
return str;
}
}
/// <summary>
/// Returns the index of a specific Word object
/// </summary>
/// <param name="word">Word object to find</param>
/// <returns>index of the word in the row</returns>
public int IndexOf(Word word)
{
return mWords.IndexOf(word);
}
/// <summary>
/// For public use only
/// </summary>
/// <param name="PatternList"></param>
/// <param name="StartWord"></param>
/// <param name="IgnoreStartWord"></param>
/// <returns></returns>
public Word FindRightWordByPatternList(PatternList PatternList, Word StartWord, bool IgnoreStartWord)
{
int i = StartWord.Index;
if (IgnoreStartWord)
i++;
Word w = null;
while (i < mWords.Count)
{
w = this[i];
if (w.Pattern != null)
{
if (w.Pattern.Parent != null)
{
if (w.Pattern.Parent == PatternList && w.Type != WordType.xtSpace && w.Type != WordType.xtTab)
{
return w;
}
}
}
i++;
}
return null;
}
/// <summary>
/// For public use only
/// </summary>
/// <param name="PatternListName"></param>
/// <param name="StartWord"></param>
/// <param name="IgnoreStartWord"></param>
/// <returns></returns>
public Word FindRightWordByPatternListName(string PatternListName, Word StartWord, bool IgnoreStartWord)
{
int i = StartWord.Index;
if (IgnoreStartWord)
i++;
Word w = null;
while (i < mWords.Count)
{
w = this[i];
if (w.Pattern != null)
{
if (w.Pattern.Parent != null)
{
if (w.Pattern.Parent.Name == PatternListName && w.Type != WordType.xtSpace && w.Type != WordType.xtTab)
{
return w;
}
}
}
i++;
}
return null;
}
/// <summary>
/// For public use only
/// </summary>
/// <param name="PatternList"></param>
/// <param name="StartWord"></param>
/// <param name="IgnoreStartWord"></param>
/// <returns></returns>
public Word FindLeftWordByPatternList(PatternList PatternList, Word StartWord, bool IgnoreStartWord)
{
int i = StartWord.Index;
if (IgnoreStartWord)
i--;
Word w = null;
while (i >= 0)
{
w = this[i];
if (w.Pattern != null)
{
if (w.Pattern.Parent != null)
{
if (w.Pattern.Parent == PatternList && w.Type != WordType.xtSpace && w.Type != WordType.xtTab)
{
return w;
}
}
}
i--;
}
return null;
}
/// <summary>
/// For public use only
/// </summary>
/// <param name="PatternListName"></param>
/// <param name="StartWord"></param>
/// <param name="IgnoreStartWord"></param>
/// <returns></returns>
public Word FindLeftWordByPatternListName(string PatternListName, Word StartWord, bool IgnoreStartWord)
{
int i = StartWord.Index;
if (IgnoreStartWord)
i--;
Word w = null;
while (i >= 0)
{
w = this[i];
if (w.Pattern != null)
{
if (w.Pattern.Parent != null)
{
if (w.Pattern.Parent.Name == PatternListName && w.Type != WordType.xtSpace && w.Type != WordType.xtTab)
{
return w;
}
}
}
i--;
}
return null;
}
/// <summary>
/// For public use only
/// </summary>
/// <param name="BlockType"></param>
/// <param name="StartWord"></param>
/// <param name="IgnoreStartWord"></param>
/// <returns></returns>
public Word FindLeftWordByBlockType(BlockType BlockType, Word StartWord, bool IgnoreStartWord)
{
int i = StartWord.Index;
if (IgnoreStartWord)
i--;
Word w = null;
while (i >= 0)
{
w = this[i];
if (w.Segment.BlockType == BlockType && w.Type != WordType.xtSpace && w.Type != WordType.xtTab)
{
return w;
}
i--;
}
return null;
}
/// <summary>
/// For public use only
/// </summary>
/// <param name="BlockType"></param>
/// <param name="StartWord"></param>
/// <param name="IgnoreStartWord"></param>
/// <returns></returns>
public Word FindRightWordByBlockType(BlockType BlockType, Word StartWord, bool IgnoreStartWord)
{
int i = StartWord.Index;
if (IgnoreStartWord)
i++;
Word w = null;
while (i < mWords.Count)
{
w = this[i];
if (w.Segment.BlockType == BlockType && w.Type != WordType.xtSpace && w.Type != WordType.xtTab)
{
return w;
}
i++;
}
return null;
}
/// <summary>
/// For public use only
/// </summary>
/// <param name="BlockTypeName"></param>
/// <param name="StartWord"></param>
/// <param name="IgnoreStartWord"></param>
/// <returns></returns>
public Word FindLeftWordByBlockTypeName(string BlockTypeName, Word StartWord, bool IgnoreStartWord)
{
int i = StartWord.Index;
if (IgnoreStartWord)
i--;
Word w = null;
while (i >= 0)
{
w = this[i];
if (w.Segment.BlockType.Name == BlockTypeName && w.Type != WordType.xtSpace && w.Type != WordType.xtTab)
{
return w;
}
i--;
}
return null;
}
/// <summary>
/// For public use only
/// </summary>
/// <param name="BlockTypeName"></param>
/// <param name="StartWord"></param>
/// <param name="IgnoreStartWord"></param>
/// <returns></returns>
public Word FindRightWordByBlockTypeName(string BlockTypeName, Word StartWord, bool IgnoreStartWord)
{
int i = StartWord.Index;
if (IgnoreStartWord)
i++;
Word w = null;
while (i < mWords.Count)
{
w = this[i];
if (w.Segment.BlockType.Name == BlockTypeName && w.Type != WordType.xtSpace && w.Type != WordType.xtTab)
{
return w;
}
i++;
}
return null;
}
/// <summary>
/// Returns the row before this row.
/// </summary>
public Row PrevRow
{
get
{
int i = this.Index;
if (i - 1 >= 0)
return this.Document[i - 1];
else
return null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public abstract class Stream : MarshalByRefObject, IDisposable
{
public static readonly Stream Null = new NullStream();
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
private const int DefaultCopyBufferSize = 81920;
// To implement Async IO operations on streams that don't support async IO
private SemaphoreSlim _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
public abstract bool CanRead
{
[Pure]
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek
{
[Pure]
get;
}
public virtual bool CanTimeout
{
[Pure]
get
{
return false;
}
}
public abstract bool CanWrite
{
[Pure]
get;
}
public abstract long Length
{
get;
}
public abstract long Position
{
get;
set;
}
public virtual int ReadTimeout
{
get
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public virtual int WriteTimeout
{
get
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public Task CopyToAsync(Stream destination)
{
int bufferSize = DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// If we go down this branch, it means there are
// no bytes left in this stream.
// Ideally we would just return Task.CompletedTask here,
// but CopyToAsync(Stream, int, CancellationToken) was already
// virtual at the time this optimization was introduced. So
// if it does things like argument validation (checking if destination
// is null and throwing an exception), then await fooStream.CopyToAsync(null)
// would no longer throw if there were no bytes left. On the other hand,
// we also can't roll our own argument validation and return Task.CompletedTask,
// because it would be a breaking change if the stream's override didn't throw before,
// or in a different order. So for simplicity, we just set the bufferSize to 1
// (not 0 since the default implementation throws for 0) and forward to the virtual method.
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
return CopyToAsync(destination, bufferSize);
}
public Task CopyToAsync(Stream destination, int bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
Debug.Assert(destination != null);
Debug.Assert(bufferSize > 0);
Debug.Assert(CanRead);
Debug.Assert(destination.CanWrite);
byte[] buffer = new byte[bufferSize];
while (true)
{
int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
if (bytesRead == 0) break;
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
}
}
// Reads the bytes from the current stream and writes the bytes to
// the destination stream until all bytes are read, starting at
// the current position.
public void CopyTo(Stream destination)
{
int bufferSize = DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// No bytes left in stream
// Call the other overload with a bufferSize of 1,
// in case it's made virtual in the future
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
CopyTo(destination, bufferSize);
}
public virtual void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
byte[] buffer = new byte[bufferSize];
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
{
destination.Write(buffer, 0, read);
}
}
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Close();
}
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
public abstract void Flush();
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
protected virtual WaitHandle CreateWaitHandle()
{
return new ManualResetEvent(initialState: false);
}
public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled<int>(cancellationToken) :
Task.Factory.FromAsync(
(localBuffer, localOffset, localCount, callback, state) => ((Stream)state).BeginRead(localBuffer, localOffset, localCount, callback, state),
iar => ((Stream)iar.AsyncState).EndRead(iar),
buffer, offset, count, this);
}
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(ReadAsyncInternal(buffer, offset, count), callback, state);
public virtual int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
private Task<int> ReadAsyncInternal(Byte[] buffer, int offset, int count)
{
// To avoid a race with a stream's position pointer & generating race
// conditions with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will serialize the requests.
return EnsureAsyncActiveSemaphoreInitialized().WaitAsync().ContinueWith((completedWait, s) =>
{
Debug.Assert(completedWait.Status == TaskStatus.RanToCompletion);
var state = (Tuple<Stream, byte[], int, int>)s;
try
{
return state.Item1.Read(state.Item2, state.Item3, state.Item4); // this.Read(buffer, offset, count);
}
finally
{
state.Item1._asyncActiveSemaphore.Release();
}
}, Tuple.Create(this, buffer, offset, count), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
public Task WriteAsync(Byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled<int>(cancellationToken) :
Task.Factory.FromAsync(
(localBuffer, localOffset, localCount, callback, state) => ((Stream)state).BeginWrite(localBuffer, localOffset, localCount, callback, state),
iar => ((Stream)iar.AsyncState).EndWrite(iar),
buffer, offset, count, this);
}
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(WriteAsyncInternal(buffer, offset, count), callback, state);
public virtual void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
private Task WriteAsyncInternal(Byte[] buffer, int offset, int count)
{
// To avoid a race with a stream's position pointer & generating race
// conditions with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will serialize the requests.
return EnsureAsyncActiveSemaphoreInitialized().WaitAsync().ContinueWith((completedWait, s) =>
{
Debug.Assert(completedWait.Status == TaskStatus.RanToCompletion);
var state = (Tuple<Stream, byte[], int, int>)s;
try
{
state.Item1.Write(state.Item2, state.Item3, state.Item4); // this.Write(buffer, offset, count);
}
finally
{
state.Item1._asyncActiveSemaphore.Release();
}
}, Tuple.Create(this, buffer, offset, count), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read(byte[] buffer, int offset, int count);
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r == 0)
{
return -1;
}
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
public static Stream Synchronized(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (stream is SyncStream)
return stream;
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
protected virtual void ObjectInvariant()
{
}
private sealed class NullStream : Stream
{
internal NullStream() { }
public override bool CanRead
{
[Pure]
get
{ return true; }
}
public override bool CanWrite
{
[Pure]
get
{ return true; }
}
public override bool CanSeek
{
[Pure]
get
{ return true; }
}
public override long Length
{
get { return 0; }
}
public override long Position
{
get { return 0; }
set { }
}
public override void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// After we validate arguments this is a nop.
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments for compat, since previously this
// method was inherited from Stream, which did check its arguments.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
// Do nothing - we don't want NullStream singleton (static) to be closable
}
public override void Flush()
{
}
#pragma warning disable 1998 // async method with no await
public override async Task FlushAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
}
#pragma warning restore 1998
public override int Read(byte[] buffer, int offset, int count)
{
return 0;
}
#pragma warning disable 1998 // async method with no await
public override async Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return 0;
}
#pragma warning restore 1998
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
public override int ReadByte()
{
return -1;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
#pragma warning disable 1998 // async method with no await
public override async Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
}
#pragma warning restore 1998
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
public override void WriteByte(byte value)
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
public override void SetLength(long length)
{
}
}
// SyncStream is a wrapper around a stream that takes
// a lock for every operation making it thread safe.
private sealed class SyncStream : Stream, IDisposable
{
private Stream _stream;
internal SyncStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
_stream = stream;
}
public override bool CanRead
{
[Pure]
get { return _stream.CanRead; }
}
public override bool CanWrite
{
[Pure]
get { return _stream.CanWrite; }
}
public override bool CanSeek
{
[Pure]
get { return _stream.CanSeek; }
}
public override bool CanTimeout
{
[Pure]
get
{
return _stream.CanTimeout;
}
}
public override long Length
{
get
{
lock (_stream)
{
return _stream.Length;
}
}
}
public override long Position
{
get
{
lock (_stream)
{
return _stream.Position;
}
}
set
{
lock (_stream)
{
_stream.Position = value;
}
}
}
public override int ReadTimeout
{
get
{
return _stream.ReadTimeout;
}
set
{
_stream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return _stream.WriteTimeout;
}
set
{
_stream.WriteTimeout = value;
}
}
// In the off chance that some wrapped stream has different
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
lock (_stream)
{
try
{
_stream.Close();
}
finally
{
base.Dispose(true);
}
}
}
protected override void Dispose(bool disposing)
{
lock (_stream)
{
try
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
finally
{
base.Dispose(disposing);
}
}
}
public override void Flush()
{
lock (_stream)
_stream.Flush();
}
public override int Read(byte[] bytes, int offset, int count)
{
lock (_stream)
return _stream.Read(bytes, offset, count);
}
public override int ReadByte()
{
lock (_stream)
return _stream.ReadByte();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
//bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
//lock (_stream)
//{
// // If the Stream does have its own BeginRead implementation, then we must use that override.
// // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// // which ensures only one asynchronous operation does so with an asynchronous wait rather
// // than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// // the EndXx method for the outstanding async operation won't be able to acquire the lock on
// // _stream due to this call blocked while holding the lock.
// return overridesBeginRead ?
// _stream.BeginRead(buffer, offset, count, callback, state) :
// _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
//}
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
lock (_stream)
return _stream.EndRead(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
lock (_stream)
return _stream.Seek(offset, origin);
}
public override void SetLength(long length)
{
lock (_stream)
_stream.SetLength(length);
}
public override void Write(byte[] bytes, int offset, int count)
{
lock (_stream)
_stream.Write(bytes, offset, count);
}
public override void WriteByte(byte b)
{
lock (_stream)
_stream.WriteByte(b);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
//bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
//lock (_stream)
//{
// // If the Stream does have its own BeginWrite implementation, then we must use that override.
// // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// // which ensures only one asynchronous operation does so with an asynchronous wait rather
// // than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// // the EndXx method for the outstanding async operation won't be able to acquire the lock on
// // _stream due to this call blocked while holding the lock.
// return overridesBeginWrite ?
// _stream.BeginWrite(buffer, offset, count, callback, state) :
// _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
//}
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
lock (_stream)
_stream.EndWrite(asyncResult);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace Grauenwolf.TravellerTools.Characters
{
public class Book
{
readonly CharacterTemplates m_Templates;
internal Book(CharacterTemplates templates)
{
m_Templates = templates;
var skills = new List<SkillTemplate>();
var allSkills = new List<SkillTemplate>();
foreach (var skill in m_Templates.Skills)
{
if (skill.Name == "Jack-of-All-Trades")
continue;
allSkills.Add(new SkillTemplate(skill.Name));
if (skill.Specialty?.Length > 0)
foreach (var specialty in skill.Specialty)
{
skills.Add(new SkillTemplate(skill.Name, specialty.Name));
allSkills.Add(new SkillTemplate(skill.Name, specialty.Name));
}
else
skills.Add(new SkillTemplate(skill.Name));
}
RandomSkills = ImmutableArray.CreateRange(skills);
AllSkills = ImmutableArray.CreateRange(allSkills);
PsionicTalents = ImmutableArray.Create(
new PsionicSkillTemplate("Telepathy", 4),
new PsionicSkillTemplate("Clairvoyance", 3),
new PsionicSkillTemplate("Telekinesis", 2),
new PsionicSkillTemplate("Awareness", 1),
new PsionicSkillTemplate("Teleportation", 0)
);
}
/// <summary>
/// Gets all of the skills, including unspecialized skills. For example, both "Art" and "Art (Perform)" will be included.
/// </summary>
/// <value>All skills.</value>
public ImmutableArray<SkillTemplate> AllSkills { get; }
public ImmutableArray<PsionicSkillTemplate> PsionicTalents { get; }
/// <summary>
/// Gets the list of random skills. Skills needing specialization will be excluded. For example, "Art (Perform)" will be included but just "Art" will not.
/// </summary>
/// <value>The random skills.</value>
public ImmutableArray<SkillTemplate> RandomSkills { get; }
public static void Injury(Character character, Dice dice, Careers.CareerBase career, bool severe = false)
{
//TODO: Add medical bills support. Page 47
var medCovered = career.MedicalPaymentPercentage(character, dice);
var medCostPerPoint = (1.0M - medCovered) * 5000;
var roll = dice.D(6);
if (severe)
roll = Math.Min(roll, dice.D(6));
int strengthPoints = 0;
int dexterityPoints = 0;
int endurancePoints = 0;
int strengthPointsLost = 0;
int dexterityPointsLost = 0;
int endurancePointsLost = 0;
string logMessage = "";
switch (roll)
{
case 1:
logMessage = "Nearly killed.";
switch (dice.D(3))
{
case 1:
strengthPoints = dice.D(6);
dexterityPoints = 2;
endurancePoints = 2;
break;
case 2:
strengthPoints = 2;
dexterityPoints = dice.D(6);
endurancePoints = 2;
break;
case 3:
strengthPoints = 2;
dexterityPoints = 2;
endurancePoints = dice.D(6);
break;
}
break;
case 2:
logMessage = "Severely injured.";
switch (dice.D(3))
{
case 1:
strengthPoints = dice.D(6);
break;
case 2:
dexterityPoints = dice.D(6);
break;
case 3:
endurancePoints = dice.D(6);
break;
}
break;
case 3:
logMessage = "Lost eye or limb.";
switch (dice.D(2))
{
case 1:
strengthPoints = 2;
break;
case 2:
dexterityPoints = 2;
break;
}
break;
case 4:
logMessage = "Scarred.";
switch (dice.D(3))
{
case 1:
strengthPoints = 2;
break;
case 2:
dexterityPoints = 2;
break;
case 3:
endurancePoints = 2;
break;
}
break;
case 5:
logMessage = "Injured.";
switch (dice.D(3))
{
case 1:
strengthPoints = 1;
break;
case 2:
dexterityPoints = 1;
break;
case 3:
endurancePoints = 1;
break;
}
break;
case 6:
logMessage = "Lightly injured, no permanent damage.";
break;
}
var medicalBills = 0M;
for (int i = 0; i < strengthPoints; i++)
{
if (dice.D(10) > 1) //90% chance of healing
medicalBills += medCostPerPoint;
else
{
character.Strength -= 1;
strengthPointsLost += 1;
}
}
for (int i = 0; i < dexterityPoints; i++)
{
if (dice.D(10) > 1) //90% chance of healing
medicalBills += medCostPerPoint;
else
{
character.Dexterity -= 1;
dexterityPointsLost += 1;
}
}
for (int i = 0; i < endurancePoints; i++)
{
if (dice.D(10) > 1) //90% chance of healing
medicalBills += medCostPerPoint;
else
{
character.Endurance -= 1;
endurancePointsLost += 1;
}
}
if (strengthPointsLost == 0 && dexterityPointsLost == 0 && endurancePointsLost == 0)
logMessage += " Fully recovered.";
if (medicalBills > 0)
logMessage += $" Owe {medicalBills.ToString("N0")} for medical bills.";
character.AddHistory(logMessage);
}
public static int OddsOfSuccess(Character character, string attributeName, int target)
{
var dm = character.GetDM(attributeName);
return OddsOfSuccess(target - dm);
}
public static int OddsOfSuccess(int target)
{
if (target <= 2) return 100;
if (target == 3) return 97;
if (target == 4) return 92;
if (target == 5) return 83;
if (target == 6) return 72;
if (target == 7) return 58;
if (target == 8) return 42;
if (target == 9) return 28;
if (target == 10) return 17;
if (target == 11) return 8;
if (target == 12) return 3;
return 0;
}
public static string RollDraft(Dice dice)
{
switch (dice.D(6))
{
case 1: return "Navy";
case 2: return "Army";
case 3: return "Marine";
case 4: return "Merchant Marine";
case 5: return "Scout";
case 6: return "Law Enforcement";
}
return null;
}
public void LifeEvent(Character character, Dice dice, Careers.CareerBase career)
{
switch (dice.D(2, 6))
{
case 2:
Injury(character, dice, career);
return;
case 3:
character.AddHistory("Birth or Death involving a family member or close friend.");
return;
case 4:
character.AddHistory("A romantic relationship ends badly. Gain a Rival or Enemy.");
return;
case 5:
character.AddHistory("A romantic relationship deepens, possibly leading to marriage. Gain an Ally.");
return;
case 6:
character.AddHistory("A new romantic starts. Gain an Ally.");
return;
case 7:
character.AddHistory("Gained a contact.");
return;
case 8:
character.AddHistory("Betrayal. Convert an Ally into a Rival or Enemy.");
return;
case 9:
character.AddHistory("Moved to a new world.");
character.NextTermBenefits.QualificationDM += 1;
return;
case 10:
character.AddHistory("Good fortune");
character.BenefitRollDMs.Add(2);
return;
case 11:
if (dice.D(2) == 1)
{
character.BenefitRolls -= 1;
character.AddHistory("Victim of a crime");
}
else
{
character.AddHistory("Accused of a crime");
character.NextTermBenefits.MustEnroll = "Prisoner";
}
return;
case 12:
UnusualLifeEvent(character, dice);
return;
}
}
public void PreCareerEvents(Character character, Dice dice, Careers.CareerBase career, params string[] skills)
{
switch (dice.D(2, 6))
{
case 2:
character.AddHistory("Contacted by an underground psionic group");
character.LongTermBenefits.MayTestPsi = true;
return;
case 3:
character.AddHistory("Suffered a deep tragedy.");
character.CurrentTermBenefits.GraduationDM = -100;
return;
case 4:
character.AddHistory("A prank goes horribly wrong.");
var roll = dice.D(2, 6) + character.SocialStandingDM;
if (roll >= 8)
character.AddHistory("Gain a Rival.");
else if (roll > 2)
character.AddHistory("Gain an Enemy.");
else
character.NextTermBenefits.MustEnroll = "Prisoner";
return;
case 5:
character.AddHistory("Spent the college years partying.");
character.Skills.Add("Carouse", 1);
return;
case 6:
character.AddHistory($"Made lifelong friends. Gain {dice.D(3)} Allies.");
return;
case 7:
LifeEvent(character, dice, career);
return;
case 8:
if (dice.RollHigh(character.SocialStandingDM, 8))
{
character.AddHistory("Become leader in social movement.");
character.AddHistory("Gain an Ally and an Enemy.");
}
else
character.AddHistory("Join a social movement.");
return;
case 9:
{
var skillList = new SkillTemplateCollection(RandomSkills);
skillList.RemoveOverlap(character.Skills, 0);
if (skillList.Count > 0)
{
var skill = dice.Choose(skillList);
character.Skills.Add(skill);
character.AddHistory($"Study {skill} as a hobby.");
}
}
return;
case 10:
if (dice.RollHigh(9))
{
var skill = dice.Choose(skills);
character.Skills.Increase(skill, 1);
character.AddHistory($"Expand the field of {skill}, but gain a Rival in your former tutor.");
}
return;
case 11:
character.AddHistory("War breaks out, triggering a mandatory draft.");
if (dice.RollHigh(character.SocialStandingDM, 9))
character.AddHistory("Used social standing to avoid the draft.");
else
{
character.CurrentTermBenefits.GraduationDM -= 100;
if (dice.D(2) == 1)
{
character.AddHistory("Fled from the draft.");
character.NextTermBenefits.MustEnroll = "Drifter";
}
else
{
var roll2 = dice.D(6);
if (roll2 <= 3)
character.NextTermBenefits.MustEnroll = "Army";
else if (roll2 <= 5)
character.NextTermBenefits.MustEnroll = "Marine";
else
character.NextTermBenefits.MustEnroll = "Navy";
}
}
return;
case 12:
character.AddHistory("Widely recognized.");
character.SocialStanding += 1;
return;
}
}
public void TestPsionic(Character character, Dice dice)
{
if (character.Psi.HasValue)
return; //already tested
character.LongTermBenefits.MayTestPsi = false;
character.AddHistory("Tested for psionic powers");
character.Psi = dice.D(2, 6) - character.CurrentTerm;
if (character.Psi <= 0)
{
character.Psi = 0;
return;
}
var availableSkills = new PsionicSkillTemplateCollection(PsionicTalents);
character.PreviousPsiAttempts = 0;
//roll for every skill
while (availableSkills.Count > 0)
{
var nextSkill = dice.Pick(availableSkills);
if (nextSkill.Name == "Telepathy" && character.PreviousPsiAttempts == 0)
{
character.Skills.Add(nextSkill);
}
else
{
if ((dice.D(2, 6) + nextSkill.LearningDM + character.PsiDM - character.PreviousPsiAttempts) >= 8)
{
character.Skills.Add(nextSkill);
}
}
character.PreviousPsiAttempts += 1;
}
}
public void UnusualLifeEvent(Character character, Dice dice)
{
switch (dice.D(6))
{
case 1:
character.AddHistory("Encounter a Psionic institute.");
TestPsionic(character, dice);
return;
case 2:
character.AddHistory("Spend time with an alien race. Gain a contact.");
var skillList = new SkillTemplateCollection(SpecialtiesFor("Science"));
skillList.RemoveOverlap(character.Skills, 1);
if (skillList.Count > 0)
character.Skills.Add(dice.Choose(skillList), 1);
return;
case 3:
character.AddHistory("Find an Alien Artifact.");
return;
case 4:
character.AddHistory("Amnesia.");
return;
case 5:
character.AddHistory("Contact with Government.");
return;
case 6:
character.AddHistory("Find Ancient Technology.");
return;
}
}
internal List<SkillTemplate> SpecialtiesFor(string skillName)
{
var skill = m_Templates.Skills.FirstOrDefault(s => s.Name == skillName);
if (skill != null && skill.Specialty != null)
return skill.Specialty.Select(s => new SkillTemplate(skillName, s.Name)).ToList();
else
return new List<SkillTemplate>() { new SkillTemplate(skillName) };
}
}
}
| |
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using Plugins.CountlySDK.Models;
using Plugins.CountlySDK;
using Newtonsoft.Json;
using System.Web;
using System.Collections.Specialized;
using Newtonsoft.Json.Linq;
using Plugins.CountlySDK.Enums;
using System.Threading.Tasks;
using System.Collections;
using UnityEngine.TestTools;
using System.Linq;
using System;
namespace Tests
{
public class SessionTests
{
private readonly string _serverUrl = "https://xyz.com/";
private readonly string _appKey = "772c091355076ead703f987fee94490";
/// <summary>
/// It checks the working of session service if no 'Session' consent is given.
/// </summary>
[Test]
public async void TestSessionConsent()
{
CountlyConfiguration configuration = new CountlyConfiguration {
ServerUrl = _serverUrl,
AppKey = _appKey,
RequiresConsent = true
};
Countly.Instance.Init(configuration);
Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Clear();
Assert.IsNotNull(Countly.Instance.Session);
Assert.AreEqual(0, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
await Countly.Instance.Session.BeginSessionAsync();
Assert.AreEqual(0, Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Count);
await Countly.Instance.Session.ExtendSessionAsync();
Assert.AreEqual(0, Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Count);
await Countly.Instance.Session.EndSessionAsync();
Assert.AreEqual(0, Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Count);
}
/// <summary>
/// It validates the functionality of 'BeginSessionAsync'.
/// </summary>
[Test]
public void TestSessionBegin_Default()
{
CountlyConfiguration configuration = new CountlyConfiguration {
ServerUrl = _serverUrl,
AppKey = _appKey,
};
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Session);
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
CountlyRequestModel requestModel = Countly.Instance.Session._requestCountlyHelper._requestRepo.Dequeue();
NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData);
Assert.AreEqual("1", collection.Get("begin_session"));
Assert.IsNotNull(collection.Get("metrics"));
}
/// <summary>
/// It validates the functionality of 'BeginSessionAsync' with location values.
/// </summary>
[Test]
public void TestSessionBegin_WithLocation()
{
CountlyConfiguration configuration = new CountlyConfiguration {
ServerUrl = _serverUrl,
AppKey = _appKey,
};
configuration.SetLocation("PK", "Lahore", "10.0 , 10.0", "192.168.100.51");
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Session);
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
CountlyRequestModel requestModel = Countly.Instance.Session._requestCountlyHelper._requestRepo.Dequeue();
NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData);
Assert.AreEqual("1", collection.Get("begin_session"));
Assert.AreEqual("192.168.100.51", collection.Get("ip_address"));
Assert.AreEqual("PK", collection.Get("country_code"));
Assert.AreEqual("Lahore", collection.Get("city"));
Assert.AreEqual("10.0 , 10.0", collection.Get("location"));
Assert.IsNotNull(collection.Get("metrics"));
}
/// <summary>
/// It validates the functionality of 'BeginSessionAsync' with location disable.
/// </summary>
[Test]
public void TestSessionBegin_WithLocationDisable()
{
CountlyConfiguration configuration = new CountlyConfiguration {
ServerUrl = _serverUrl,
AppKey = _appKey,
};
configuration.DisableLocation();
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Session);
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
CountlyRequestModel requestModel = Countly.Instance.Session._requestCountlyHelper._requestRepo.Dequeue();
NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData);
Assert.AreEqual("1", collection.Get("begin_session"));
Assert.AreEqual(string.Empty, collection.Get("location"));
Assert.IsNotNull(collection.Get("metrics"));
}
/// <summary>
/// It validates the functionality of 'BeginSessionAsync' when session consent is given after init.
/// </summary>
[Test]
public void TestSessionBegin_ConsentGivenAfterInit()
{
CountlyConfiguration configuration = new CountlyConfiguration {
ServerUrl = _serverUrl,
AppKey = _appKey,
RequiresConsent = true
};
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Session);
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
Countly.Instance.Session._requestCountlyHelper._requestRepo.Clear();
Countly.Instance.Consents.GiveConsent(new Consents[] { Consents.Sessions });
//RQ will have consent change request and session begin request
Assert.AreEqual(2, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
Countly.Instance.Session._requestCountlyHelper._requestRepo.Dequeue(); // Remove consent Request
CountlyRequestModel requestModel = Countly.Instance.Session._requestCountlyHelper._requestRepo.Dequeue();
NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData);
Assert.AreEqual("1", collection.Get("begin_session"));
Assert.IsNotNull(collection.Get("metrics"));
}
/// <summary>
/// It validates the working of session service when automatic session tracking is disabled.
/// </summary>
[Test]
public void TestSessionService_WithDisableTracking()
{
CountlyConfiguration configuration = new CountlyConfiguration {
ServerUrl = _serverUrl,
AppKey = _appKey,
};
configuration.DisableAutomaticSessionTracking();
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Session);
Assert.AreEqual(0, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
}
/// <summary>
/// It validates if 'BeginSessionAsync' does call when session consent is given after init and automatic session tracking is disabled.
/// </summary>
[Test]
public void TestSessionBegin_ConsentGivenAfterInitWithDisableTracking()
{
CountlyConfiguration configuration = new CountlyConfiguration {
ServerUrl = _serverUrl,
AppKey = _appKey,
RequiresConsent = true
};
configuration.DisableAutomaticSessionTracking();
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Session);
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
Countly.Instance.Session._requestCountlyHelper._requestRepo.Clear();
Countly.Instance.Consents.GiveConsent(new Consents[] { Consents.Sessions });
//RQ will have consent change request
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
}
/// <summary>
/// It validates if 'BeginSessionAsync' does call when session consent is given after init and session had begun before.
/// </summary>
[Test]
public void TestSessionBegin_ConsentGivenAfterSessionBegin()
{
CountlyConfiguration configuration = new CountlyConfiguration {
ServerUrl = _serverUrl,
AppKey = _appKey,
RequiresConsent = true
};
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Session);
// RQ will have empty location request
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
Countly.Instance.Session._requestCountlyHelper._requestRepo.Clear();
Countly.Instance.Consents.GiveConsent(new Consents[] { Consents.Sessions });
// RQ will have Consent change request and Session begin request
Assert.AreEqual(2, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
Countly.Instance.Session._requestCountlyHelper._requestRepo.Clear();
Countly.Instance.Consents.RemoveConsent(new Consents[] { Consents.Sessions });
//RQ will have consent change request and session begin request
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
Countly.Instance.Session._requestCountlyHelper._requestRepo.Clear();
// RQ will have Consent change request and Session begin request
Countly.Instance.Consents.GiveConsent(new Consents[] { Consents.Sessions });
Assert.AreEqual(2, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
}
/// <summary>
/// It validates the request of 'ExtendSessionAsync'.
/// </summary>
[UnityTest]
public IEnumerator TestSessionExtend()
{
CountlyConfiguration configuration = new CountlyConfiguration {
ServerUrl = _serverUrl,
AppKey = _appKey,
};
System.DateTime sessionStartTime = System.DateTime.Now;
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Session);
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
CountlyRequestModel requestModel = Countly.Instance.Session._requestCountlyHelper._requestRepo.Dequeue();
NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData);
Assert.AreEqual("1", collection.Get("begin_session"));
Assert.IsNotNull(collection.Get("metrics"));
System.DateTime startTime = System.DateTime.UtcNow;
do {
yield return null;
}
while ((System.DateTime.UtcNow - startTime).TotalSeconds < 2.0);
Countly.Instance.Session.ExtendSessionAsync();
double duration = (System.DateTime.Now - sessionStartTime).TotalSeconds;
startTime = System.DateTime.UtcNow;
do {
yield return null;
}
while ((System.DateTime.UtcNow - startTime).TotalSeconds < 0.4);
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
requestModel = Countly.Instance.Session._requestCountlyHelper._requestRepo.Dequeue();
collection = HttpUtility.ParseQueryString(requestModel.RequestData);
Assert.IsNull(collection.Get("metrics"));
Assert.AreEqual("2", collection.Get("session_duration"));
Assert.GreaterOrEqual(duration, Convert.ToDouble(collection.Get("session_duration")));
}
/// <summary>
/// It validates the request of 'EndSessionAsync'.
/// </summary>
[UnityTest]
public IEnumerator TestSessionEnd()
{
CountlyConfiguration configuration = new CountlyConfiguration {
ServerUrl = _serverUrl,
AppKey = _appKey,
};
System.DateTime sessionStartTime = System.DateTime.Now;
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Session);
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
Countly.Instance.Session._requestCountlyHelper._requestRepo.Clear();
System.DateTime startTime = System.DateTime.UtcNow;
do {
yield return null;
}
while ((System.DateTime.UtcNow - startTime).TotalSeconds < 2.0);
Countly.Instance.Session.EndSessionAsync();
double duration = (System.DateTime.Now - sessionStartTime).TotalSeconds;
startTime = System.DateTime.UtcNow;
do {
yield return null;
}
while ((System.DateTime.UtcNow - startTime).TotalSeconds < 0.4);
Assert.AreEqual(1, Countly.Instance.Session._requestCountlyHelper._requestRepo.Count);
CountlyRequestModel requestModel = Countly.Instance.Session._requestCountlyHelper._requestRepo.Dequeue();
NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData);
Assert.AreEqual("1", collection.Get("end_session"));
Assert.AreEqual("2", collection.Get("session_duration"));
Assert.GreaterOrEqual(duration, Convert.ToDouble(collection.Get("session_duration")));
Assert.IsNull(collection.Get("metrics"));
}
[TearDown]
public void End()
{
Countly.Instance.ClearStorage();
UnityEngine.Object.DestroyImmediate(Countly.Instance);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
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(new Win32Exception().Message);
sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH];
Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, 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(new Win32Exception().Message);
}
//
// 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(new Win32Exception().Message);
}
// 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(new Win32Exception().Message);
}
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(nameof(action));
RunImpersonatedInternal(safeAccessTokenHandle, action);
}
public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func)
{
if (func == null)
throw new ArgumentNullException(nameof(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(new Win32Exception(hr).Message);
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(new Win32Exception().Message);
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(new Win32Exception().Message);
if (args.CurrentValue != null && !args.CurrentValue.IsInvalid)
{
if (!Interop.mincore.ImpersonateLoggedOnUser(args.CurrentValue))
Environment.FailFast(new Win32Exception().Message);
}
}
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(new Win32Exception(hr).Message);
}
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(new Win32Exception(win32ErrorCode).Message);
}
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(new Win32Exception().Message);
break;
case Interop.mincore.Errors.ERROR_INVALID_HANDLE:
throw new ArgumentException(SR.Argument_InvalidImpersonationToken);
default:
throw new SecurityException(new Win32Exception(dwErrorCode).Message);
}
return safeLocalAllocHandle;
}
protected WindowsIdentity(WindowsIdentity identity)
: base(identity, null, identity._authType, null, null)
{
if (identity == null)
throw new ArgumentNullException(nameof(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
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 Outercurve Foundation 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.Collections.Generic;
using WebsitePanel.WebPortal;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Portal.ExchangeServer.UserControls
{
public partial class Menu : WebsitePanelControlBase
{
public class MenuGroup
{
private string text;
private List<MenuItem> menuItems;
private string imageUrl;
public string Text
{
get { return text; }
set { text = value; }
}
public List<MenuItem> MenuItems
{
get { return menuItems; }
set { menuItems = value; }
}
public string ImageUrl
{
get { return imageUrl; }
set { imageUrl = value; }
}
public MenuGroup(string text, string imageUrl)
{
this.text = text;
this.imageUrl = imageUrl;
menuItems = new List<MenuItem>();
}
}
public class MenuItem
{
private string url;
private string text;
private string key;
public string Url
{
get { return url; }
set { url = value; }
}
public string Text
{
get { return text; }
set { text = value; }
}
public string Key
{
get { return key; }
set { key = value; }
}
}
private string selectedItem;
public string SelectedItem
{
get { return selectedItem; }
set { selectedItem = value; }
}
private void PrepareExchangeMenu(PackageContext cntx, List<MenuGroup> groups, string imagePath)
{
bool hideItems = false;
UserInfo user = UsersHelper.GetUser(PanelSecurity.EffectiveUserId);
if (user != null)
{
if ((user.Role == UserRole.User) & (Utils.CheckQouta(Quotas.EXCHANGE2007_ISCONSUMER, cntx)))
hideItems = true;
}
MenuGroup exchangeGroup = new MenuGroup(GetLocalizedString("Text.ExchangeGroup"), imagePath + "exchange24.png");
if (Utils.CheckQouta(Quotas.EXCHANGE2007_MAILBOXES, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("Mailboxes", "mailboxes"));
if (Utils.CheckQouta(Quotas.EXCHANGE2013_ALLOWRETENTIONPOLICY, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("ArchivingMailboxes", "archivingmailboxes"));
if (Utils.CheckQouta(Quotas.EXCHANGE2007_CONTACTS, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("Contacts", "contacts"));
if (Utils.CheckQouta(Quotas.EXCHANGE2007_DISTRIBUTIONLISTS, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("DistributionLists", "dlists"));
if (Utils.CheckQouta(Quotas.EXCHANGE2007_PUBLICFOLDERS, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("PublicFolders", "public_folders"));
if (!hideItems)
if (Utils.CheckQouta(Quotas.EXCHANGE2007_ACTIVESYNCALLOWED, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("ActiveSyncPolicy", "activesync_policy"));
if (!hideItems)
if (Utils.CheckQouta(Quotas.EXCHANGE2007_MAILBOXES, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("MailboxPlans", "mailboxplans"));
if (!hideItems)
if (Utils.CheckQouta(Quotas.EXCHANGE2013_ALLOWRETENTIONPOLICY, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("RetentionPolicy", "retentionpolicy"));
if (!hideItems)
if (Utils.CheckQouta(Quotas.EXCHANGE2013_ALLOWRETENTIONPOLICY, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("RetentionPolicyTag", "retentionpolicytag"));
if (!hideItems)
if (Utils.CheckQouta(Quotas.EXCHANGE2007_MAILBOXES, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("ExchangeDomainNames", "domains"));
if (!hideItems)
if (Utils.CheckQouta(Quotas.EXCHANGE2007_MAILBOXES, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("StorageUsage", "storage_usage"));
if (!hideItems)
if (Utils.CheckQouta(Quotas.EXCHANGE2007_DISCLAIMERSALLOWED, cntx))
exchangeGroup.MenuItems.Add(CreateMenuItem("Disclaimers", "disclaimers"));
if (exchangeGroup.MenuItems.Count > 0)
groups.Add(exchangeGroup);
}
private void PrepareOrganizationMenu(PackageContext cntx, List<MenuGroup> groups, string imagePath)
{
bool hideItems = false;
UserInfo user = UsersHelper.GetUser(PanelSecurity.EffectiveUserId);
if (user != null)
{
if ((user.Role == UserRole.User) & (Utils.CheckQouta(Quotas.EXCHANGE2007_ISCONSUMER, cntx)))
hideItems = true;
}
if (!hideItems)
{
MenuGroup organizationGroup = new MenuGroup(GetLocalizedString("Text.OrganizationGroup"), imagePath + "company24.png");
if (Utils.CheckQouta(Quotas.EXCHANGE2007_MAILBOXES, cntx) == false)
{
if (Utils.CheckQouta(Quotas.ORGANIZATION_DOMAINS, cntx))
organizationGroup.MenuItems.Add(CreateMenuItem("DomainNames", "org_domains"));
}
if (Utils.CheckQouta(Quotas.ORGANIZATION_USERS, cntx))
organizationGroup.MenuItems.Add(CreateMenuItem("Users", "users"));
if (Utils.CheckQouta(Quotas.ORGANIZATION_DELETED_USERS, cntx))
organizationGroup.MenuItems.Add(CreateMenuItem("DeletedUsers", "deleted_users"));
if (Utils.CheckQouta(Quotas.ORGANIZATION_SECURITYGROUPS, cntx))
organizationGroup.MenuItems.Add(CreateMenuItem("SecurityGroups", "secur_groups"));
if (organizationGroup.MenuItems.Count > 0)
groups.Add(organizationGroup);
}
}
private void PrepareCRMMenu(PackageContext cntx, List<MenuGroup> groups, string imagePath)
{
MenuGroup crmGroup = new MenuGroup(GetLocalizedString("Text.CRMGroup"), imagePath + "crm_16.png");
crmGroup.MenuItems.Add(CreateMenuItem("CRMOrganization", "CRMOrganizationDetails"));
crmGroup.MenuItems.Add(CreateMenuItem("CRMUsers", "CRMUsers"));
crmGroup.MenuItems.Add(CreateMenuItem("StorageLimits", "crm_storage_settings"));
if (crmGroup.MenuItems.Count > 0)
groups.Add(crmGroup);
}
private void PrepareCRMMenu2013(PackageContext cntx, List<MenuGroup> groups, string imagePath)
{
MenuGroup crmGroup = new MenuGroup(GetLocalizedString("Text.CRMGroup2013"), imagePath + "crm_16.png");
crmGroup.MenuItems.Add(CreateMenuItem("CRMOrganization", "CRMOrganizationDetails"));
crmGroup.MenuItems.Add(CreateMenuItem("CRMUsers", "CRMUsers"));
crmGroup.MenuItems.Add(CreateMenuItem("StorageLimits", "crm_storage_settings"));
if (crmGroup.MenuItems.Count > 0)
groups.Add(crmGroup);
}
private void PrepareBlackBerryMenu(PackageContext cntx, List<MenuGroup> groups, string imagePath)
{
MenuGroup bbGroup = new MenuGroup(GetLocalizedString("Text.BlackBerryGroup"), imagePath + "blackberry16.png");
bbGroup.MenuItems.Add(CreateMenuItem("BlackBerryUsers", "blackberry_users"));
if (bbGroup.MenuItems.Count > 0)
groups.Add(bbGroup);
}
private void PrepareSharePointMenu(PackageContext cntx, List<MenuGroup> groups, string imagePath, string menuItemText)
{
MenuGroup sharepointGroup =
new MenuGroup(menuItemText, imagePath + "sharepoint24.png");
sharepointGroup.MenuItems.Add(CreateMenuItem("SiteCollections", "sharepoint_sitecollections"));
sharepointGroup.MenuItems.Add(CreateMenuItem("StorageUsage", "sharepoint_storage_usage"));
sharepointGroup.MenuItems.Add(CreateMenuItem("StorageLimits", "sharepoint_storage_settings"));
groups.Add(sharepointGroup);
}
private void PrepareSharePointEnterpriseMenu(PackageContext cntx, List<MenuGroup> groups, string imagePath, string menuItemText)
{
MenuGroup sharepointGroup =
new MenuGroup(menuItemText, imagePath + "sharepoint24.png");
sharepointGroup.MenuItems.Add(CreateMenuItem("SiteCollections", "sharepoint_enterprise_sitecollections"));
sharepointGroup.MenuItems.Add(CreateMenuItem("StorageUsage", "sharepoint_enterprise_storage_usage"));
sharepointGroup.MenuItems.Add(CreateMenuItem("StorageLimits", "sharepoint_enterprise_storage_settings"));
groups.Add(sharepointGroup);
}
private void PrepareOCSMenu(PackageContext cntx, List<MenuGroup> groups, string imagePath)
{
MenuGroup ocsGroup =
new MenuGroup(GetLocalizedString("Text.OCSGroup"), imagePath + "ocs16.png");
ocsGroup.MenuItems.Add(CreateMenuItem("OCSUsers", "ocs_users"));
groups.Add(ocsGroup);
}
private void PrepareLyncMenu(PackageContext cntx, List<MenuGroup> groups, string imagePath)
{
MenuGroup lyncGroup =
new MenuGroup(GetLocalizedString("Text.LyncGroup"), imagePath + "lync16.png");
lyncGroup.MenuItems.Add(CreateMenuItem("LyncUsers", "lync_users"));
lyncGroup.MenuItems.Add(CreateMenuItem("LyncUserPlans", "lync_userplans"));
if (Utils.CheckQouta(Quotas.LYNC_FEDERATION, cntx))
lyncGroup.MenuItems.Add(CreateMenuItem("LyncFederationDomains", "lync_federationdomains"));
if (Utils.CheckQouta(Quotas.LYNC_PHONE, cntx))
lyncGroup.MenuItems.Add(CreateMenuItem("LyncPhoneNumbers", "lync_phonenumbers"));
groups.Add(lyncGroup);
}
private void PrepareEnterpriseStorageMenu(PackageContext cntx, List<MenuGroup> groups, string imagePath)
{
MenuGroup enterpriseStorageGroup =
new MenuGroup(GetLocalizedString("Text.EnterpriseStorageGroup"), imagePath + "spaces16.png");
enterpriseStorageGroup.MenuItems.Add(CreateMenuItem("EnterpriseStorageFolders", "enterprisestorage_folders"));
groups.Add(enterpriseStorageGroup);
}
private List<MenuGroup> PrepareMenu()
{
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
List<MenuGroup> groups = new List<MenuGroup>();
string imagePath = String.Concat("~/", DefaultPage.THEMES_FOLDER, "/", Page.Theme, "/", "Images/Exchange", "/");
//Organization menu group;
if (cntx.Groups.ContainsKey(ResourceGroups.HostedOrganizations))
PrepareOrganizationMenu(cntx, groups, imagePath);
//Exchange menu group;
if (cntx.Groups.ContainsKey(ResourceGroups.Exchange))
PrepareExchangeMenu(cntx, groups, imagePath);
//BlackBerry Menu
if (cntx.Groups.ContainsKey(ResourceGroups.BlackBerry))
PrepareBlackBerryMenu(cntx, groups, imagePath);
//SharePoint menu group;
if (cntx.Groups.ContainsKey(ResourceGroups.SharepointFoundationServer))
{
PrepareSharePointMenu(cntx, groups, imagePath, GetLocalizedString("Text.SharePointFoundationServerGroup"));
}
if (cntx.Groups.ContainsKey(ResourceGroups.SharepointEnterpriseServer))
{
PrepareSharePointEnterpriseMenu(cntx, groups, imagePath, GetLocalizedString("Text.SharePointEnterpriseServerGroup"));
}
//CRM Menu
if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013))
PrepareCRMMenu2013(cntx, groups, imagePath);
else if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM))
PrepareCRMMenu(cntx, groups, imagePath);
//OCS Menu
if (cntx.Groups.ContainsKey(ResourceGroups.OCS))
PrepareOCSMenu(cntx, groups, imagePath);
//Lync Menu
if (cntx.Groups.ContainsKey(ResourceGroups.Lync))
PrepareLyncMenu(cntx, groups, imagePath);
//EnterpriseStorage Menu
if (cntx.Groups.ContainsKey(ResourceGroups.EnterpriseStorage))
PrepareEnterpriseStorageMenu(cntx, groups, imagePath);
return groups;
}
protected void Page_Load(object sender, EventArgs e)
{
List<MenuGroup> groups = PrepareMenu();
/*repMenu.SelectedIndex = -1;
for(int i = 0; i < items.Count; i++)
{
if (String.Compare(SelectedItem, items[i].Key, true) == 0)
{
repMenu.SelectedIndex = i;
break;
}
}*/
// bind
repMenu.DataSource = groups;
repMenu.DataBind();
}
private MenuItem CreateMenuItem(string text, string key)
{
MenuItem item = new MenuItem();
item.Key = key;
item.Text = GetLocalizedString("Text." + text);
item.Url = HostModule.EditUrl("ItemID", PanelRequest.ItemID.ToString(), key,
"SpaceID=" + PanelSecurity.PackageId);
return item;
}
}
}
| |
// ============================================================================
// FileName: MainConsole.cs
//
// Description:
// Main console display for the demonstration SIP Proxy.
//
// Author(s):
// Aaron Clauson
//
// History:
// 13 Aug 2006 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2006-2013 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// 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 SIP Sorcery PTY LTD
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ============================================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security;
using System.ServiceProcess;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using SIPSorcery.AppServer.DialPlan;
using SIPSorcery.CRM;
using SIPSorcery.Net;
using SIPSorcery.Persistence;
using SIPSorcery.Servers;
using SIPSorcery.SIP;
using SIPSorcery.SIP.App;
using SIPSorcery.SIPNotifier;
using SIPSorcery.SIPMonitor;
using SIPSorcery.SIPProxy;
using SIPSorcery.SIPRegistrar;
using SIPSorcery.SIPRegistrationAgent;
using SIPSorcery.SSHServer;
using SIPSorcery.Sys;
using SIPSorcery.Web.Services;
using log4net;
namespace SIPSorcery.SIPAppServer
{
public class SIPAllInOneDaemon
{
private static ILog logger = SIPAppServerState.logger;
private static ILog dialPlanLogger = AppState.GetLogger("dialplan");
private XmlNode m_sipAppServerSocketsNode = SIPAppServerState.SIPAppServerSocketsNode;
private static bool m_sipProxyEnabled = (AppState.GetSection(SIPProxyState.SIPPROXY_CONFIGNODE_NAME) != null);
private static bool m_sipMonitorEnabled = (AppState.GetSection(SIPMonitorState.SIPMONITOR_CONFIGNODE_NAME) != null);
private static bool m_sipRegistrarEnabled = (AppState.GetSection(SIPRegistrarState.SIPREGISTRAR_CONFIGNODE_NAME) != null);
private static bool m_sipRegAgentEnabled = (AppState.GetSection(SIPRegAgentState.SIPREGAGENT_CONFIGNODE_NAME) != null);
private static bool m_sshServerEnabled = (AppState.GetSection(SSHServerState.SSHSERVER_CONFIGNODE_NAME) != null);
private static bool m_sipNotifierEnabled = (AppState.GetSection(SIPNotifierState.SIPNOTIFIER_CONFIGNODE_NAME) != null);
private static int m_monitorEventLoopbackPort = SIPAppServerState.MonitorLoopbackPort;
private string m_traceDirectory = SIPAppServerState.TraceDirectory;
private string m_currentDirectory = AppState.CurrentDirectory;
private string m_rubyScriptCommonPath = SIPAppServerState.RubyScriptCommonPath;
private SIPEndPoint m_outboundProxy = SIPAppServerState.OutboundProxy;
private string m_dialplanImpersonationUsername = SIPAppServerState.DialPlanEngineImpersonationUsername;
private string m_dialplanImpersonationPassword = SIPAppServerState.DialPlanEngineImpersonationPassword;
private int m_dailyCallLimit = SIPAppServerState.DailyCallLimit;
private int m_maxDialPlanExecutionLimit = SIPAppServerState.DialPlanMaxExecutionLimit;
private SIPSorceryPersistor m_sipSorceryPersistor;
private SIPMonitorEventWriter m_monitorEventWriter;
private SIPAppServerCore m_appServerCore;
private SIPCallManager m_callManager;
private SIPDialogueManager m_sipDialogueManager;
private RTCCCore m_rtccCore;
private RateBulkUpdater m_rateUpdater;
private SIPNotifyManager m_notifyManager;
private SIPProxyDaemon m_sipProxyDaemon;
private SIPMonitorDaemon m_sipMonitorDaemon;
private SIPRegAgentDaemon m_sipRegAgentDaemon;
private SIPRegistrarDaemon m_sipRegistrarDaemon;
private SIPNotifierDaemon m_sipNotifierDaemon;
private SIPSorcery.Entities.CDRDataLayer m_cdrDataLayer;
private SIPTransport m_sipTransport;
private DialPlanEngine m_dialPlanEngine;
private ServiceHost m_accessPolicyHost;
private ServiceHost m_sipProvisioningHost;
private ServiceHost m_callManagerSvcHost;
private ServiceHost m_sipNotificationsHost;
private CustomerSessionManager m_customerSessionManager;
private ISIPMonitorPublisher m_sipMonitorPublisher;
private IPAddress m_publicIPAddress;
private StorageTypes m_storageType;
private string m_connectionString;
private SIPEndPoint m_appServerEndPoint;
private string m_callManagerServiceAddress;
private bool m_monitorCalls; // If true this app server instance will monitor the sip dialogues table for expired calls to hangup.
public SIPAllInOneDaemon(StorageTypes storageType, string connectionString)
{
m_storageType = storageType;
m_connectionString = connectionString;
m_monitorCalls = true;
}
public SIPAllInOneDaemon(
StorageTypes storageType,
string connectionString,
SIPEndPoint appServerEndPoint,
string callManagerServiceAddress,
bool monitorCalls)
{
m_storageType = storageType;
m_connectionString = connectionString;
m_appServerEndPoint = appServerEndPoint;
m_callManagerServiceAddress = callManagerServiceAddress;
m_monitorCalls = monitorCalls;
}
public void Start()
{
try
{
logger.Debug("pid=" + Process.GetCurrentProcess().Id + ".");
logger.Debug("os=" + System.Environment.OSVersion + ".");
logger.Debug("current directory=" + m_currentDirectory + ".");
logger.Debug("base directory=" + AppDomain.CurrentDomain.BaseDirectory + ".");
SIPDNSManager.SIPMonitorLogEvent = FireSIPMonitorEvent;
m_sipSorceryPersistor = new SIPSorceryPersistor(m_storageType, m_connectionString);
m_customerSessionManager = new CustomerSessionManager(m_storageType, m_connectionString);
m_cdrDataLayer = new Entities.CDRDataLayer();
if (m_sipProxyEnabled)
{
m_sipProxyDaemon = new SIPProxyDaemon();
m_sipProxyDaemon.Start();
if (m_sipProxyDaemon.PublicIPAddress != null)
{
m_publicIPAddress = m_sipProxyDaemon.PublicIPAddress;
DialStringParser.PublicIPAddress = m_sipProxyDaemon.PublicIPAddress;
DialPlanScriptFacade.PublicIPAddress = m_sipProxyDaemon.PublicIPAddress;
SIPDialogueManager.PublicIPAddress = m_sipProxyDaemon.PublicIPAddress;
}
else
{
m_sipProxyDaemon.PublicIPAddressUpdated += (ipAddress) =>
{
if (ipAddress != null && (m_publicIPAddress == null || ipAddress.ToString() != m_publicIPAddress.ToString()))
{
m_publicIPAddress = ipAddress;
DialStringParser.PublicIPAddress = ipAddress;
DialPlanScriptFacade.PublicIPAddress = ipAddress;
SIPDialogueManager.PublicIPAddress = ipAddress;
}
};
}
}
if (m_sipMonitorEnabled)
{
m_sipMonitorPublisher = new SIPMonitorClientManager(null);
m_sipMonitorDaemon = new SIPMonitorDaemon(m_sipMonitorPublisher);
m_sipMonitorDaemon.Start();
}
if (m_sipRegistrarEnabled)
{
m_sipRegistrarDaemon = new SIPRegistrarDaemon(
m_sipSorceryPersistor.SIPDomainManager.GetDomain,
m_sipSorceryPersistor.SIPAccountsPersistor.Get,
m_sipSorceryPersistor.SIPRegistrarBindingPersistor,
SIPRequestAuthenticator.AuthenticateSIPRequest,
m_customerSessionManager.CustomerPersistor);
m_sipRegistrarDaemon.Start();
}
if (m_sipRegAgentEnabled)
{
m_sipRegAgentDaemon = new SIPRegAgentDaemon(
m_sipSorceryPersistor.SIPProvidersPersistor,
m_sipSorceryPersistor.SIPProviderBindingsPersistor);
m_sipRegAgentDaemon.Start();
}
if (m_sipNotifierEnabled)
{
m_sipNotifierDaemon = new SIPNotifierDaemon(
m_customerSessionManager.CustomerPersistor.Get,
m_sipSorceryPersistor.SIPDialoguePersistor.Get,
m_sipSorceryPersistor.SIPDialoguePersistor.Get,
m_sipSorceryPersistor.SIPDomainManager.GetDomain,
m_sipSorceryPersistor.SIPAccountsPersistor,
m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Get,
m_sipSorceryPersistor.SIPAccountsPersistor.Get,
m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Count,
SIPRequestAuthenticator.AuthenticateSIPRequest,
m_sipMonitorPublisher);
//new SIPMonitorUDPSink("127.0.0.1:10003"));
m_sipNotifierDaemon.Start();
}
if (m_sshServerEnabled)
{
SSHServerDaemon daemon = new SSHServerDaemon(m_customerSessionManager, m_sipMonitorPublisher); // Uses memory to transfer events.
//SSHServerDaemon daemon = new SSHServerDaemon(m_customerSessionManager, new SIPMonitorUDPSink("127.0.0.1:10002"));
daemon.Start();
}
#region Initialise the SIP Application Server and its logging mechanisms including CDRs.
logger.Debug("Initiating SIP Application Server Agent.");
// Send events from this process to the monitoring socket.
if (m_monitorEventLoopbackPort != 0)
{
m_monitorEventWriter = new SIPMonitorEventWriter(m_monitorEventLoopbackPort);
}
if (m_cdrDataLayer != null)
{
SIPCDR.CDRCreated += m_cdrDataLayer.Add;
SIPCDR.CDRAnswered += m_cdrDataLayer.Update;
SIPCDR.CDRHungup += m_cdrDataLayer.Update;
SIPCDR.CDRUpdated += m_cdrDataLayer.Update;
}
#region Initialise the SIPTransport layers.
m_sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine(), true);
if (m_appServerEndPoint != null)
{
if (m_appServerEndPoint.Protocol == SIPProtocolsEnum.udp)
{
logger.Debug("Using single SIP transport socket for App Server " + m_appServerEndPoint.ToString() + ".");
m_sipTransport.AddSIPChannel(new SIPUDPChannel(m_appServerEndPoint.GetIPEndPoint()));
}
else if (m_appServerEndPoint.Protocol == SIPProtocolsEnum.tcp)
{
logger.Debug("Using single SIP transport socket for App Server " + m_appServerEndPoint.ToString() + ".");
m_sipTransport.AddSIPChannel(new SIPTCPChannel(m_appServerEndPoint.GetIPEndPoint()));
}
else
{
throw new ApplicationException("The SIP End Point of " + m_appServerEndPoint + " cannot be used with the App Server transport layer.");
}
}
else if (m_sipAppServerSocketsNode != null)
{
m_sipTransport.AddSIPChannel(SIPTransportConfig.ParseSIPChannelsNode(m_sipAppServerSocketsNode));
}
else
{
throw new ApplicationException("The SIP App Server could not be started, no SIP sockets have been configured.");
}
m_sipTransport.SIPRequestInTraceEvent += LogSIPRequestIn;
m_sipTransport.SIPRequestOutTraceEvent += LogSIPRequestOut;
m_sipTransport.SIPResponseInTraceEvent += LogSIPResponseIn;
m_sipTransport.SIPResponseOutTraceEvent += LogSIPResponseOut;
m_sipTransport.SIPBadRequestInTraceEvent += LogSIPBadRequestIn;
m_sipTransport.SIPBadResponseInTraceEvent += LogSIPBadResponseIn;
#endregion
m_dialPlanEngine = new DialPlanEngine(
m_sipTransport,
m_sipSorceryPersistor.SIPDomainManager.GetDomain,
FireSIPMonitorEvent,
m_sipSorceryPersistor,
//m_sipSorceryPersistor.SIPAccountsPersistor,
//m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Get,
//m_sipSorceryPersistor.SIPDialPlanPersistor,
//m_sipSorceryPersistor.SIPDialoguePersistor,
m_outboundProxy,
m_rubyScriptCommonPath,
m_dialplanImpersonationUsername,
m_dialplanImpersonationPassword,
m_maxDialPlanExecutionLimit);
m_sipDialogueManager = new SIPDialogueManager(
m_sipTransport,
m_outboundProxy,
FireSIPMonitorEvent,
m_sipSorceryPersistor.SIPDialoguePersistor,
m_sipSorceryPersistor.SIPCDRPersistor,
SIPRequestAuthenticator.AuthenticateSIPRequest,
m_sipSorceryPersistor.SIPAccountsPersistor.Get,
m_sipSorceryPersistor.SIPDomainManager.GetDomain);
m_callManager = new SIPCallManager(
m_sipTransport,
m_outboundProxy,
FireSIPMonitorEvent,
m_sipDialogueManager,
m_sipSorceryPersistor.SIPDialoguePersistor,
m_sipSorceryPersistor.SIPCDRPersistor,
m_dialPlanEngine,
m_sipSorceryPersistor.SIPDialPlanPersistor.Get,
m_sipSorceryPersistor.SIPAccountsPersistor.Get,
m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Get,
m_sipSorceryPersistor.SIPProvidersPersistor.Get,
m_sipSorceryPersistor.SIPDomainManager.GetDomain,
m_customerSessionManager.CustomerPersistor,
m_sipSorceryPersistor.SIPDialPlanPersistor,
m_traceDirectory,
m_monitorCalls,
m_dailyCallLimit);
m_callManager.Start();
m_appServerCore = new SIPAppServerCore(
m_sipTransport,
m_sipSorceryPersistor.SIPDomainManager.GetDomain,
m_sipSorceryPersistor.SIPAccountsPersistor.Get,
FireSIPMonitorEvent,
m_callManager,
m_sipDialogueManager,
SIPRequestAuthenticator.AuthenticateSIPRequest,
m_outboundProxy);
m_rtccCore = new RTCCCore(
FireSIPMonitorEvent,
m_sipDialogueManager,
m_sipSorceryPersistor.SIPDialoguePersistor);
m_rtccCore.Start();
m_rateUpdater = new RateBulkUpdater(FireSIPMonitorEvent);
m_rateUpdater.Start();
#endregion
#region Initialise WCF services.
try
{
if (WCFUtility.DoesWCFServiceExist(typeof(SIPProvisioningWebService).FullName.ToString()))
{
if (m_sipSorceryPersistor == null)
{
logger.Warn("Provisioning hosted service could not be started as Persistor object was null.");
}
else
{
SIPProviderBindingSynchroniser sipProviderBindingSynchroniser = new SIPProviderBindingSynchroniser(m_sipSorceryPersistor.SIPProviderBindingsPersistor);
m_sipSorceryPersistor.SIPProvidersPersistor.Added += sipProviderBindingSynchroniser.SIPProviderAdded;
m_sipSorceryPersistor.SIPProvidersPersistor.Updated += sipProviderBindingSynchroniser.SIPProviderUpdated;
m_sipSorceryPersistor.SIPProvidersPersistor.Deleted += sipProviderBindingSynchroniser.SIPProviderDeleted;
ProvisioningServiceInstanceProvider instanceProvider = new ProvisioningServiceInstanceProvider(
m_sipSorceryPersistor.SIPAccountsPersistor,
m_sipSorceryPersistor.SIPDialPlanPersistor,
m_sipSorceryPersistor.SIPProvidersPersistor,
m_sipSorceryPersistor.SIPProviderBindingsPersistor,
m_sipSorceryPersistor.SIPRegistrarBindingPersistor,
m_sipSorceryPersistor.SIPDialoguePersistor,
m_sipSorceryPersistor.SIPCDRPersistor,
m_customerSessionManager,
m_sipSorceryPersistor.SIPDomainManager,
FireSIPMonitorEvent,
0,
false);
m_sipProvisioningHost = new ServiceHost(typeof(SIPProvisioningWebService));
m_sipProvisioningHost.Description.Behaviors.Add(instanceProvider);
m_sipProvisioningHost.Open();
if (m_sipRegAgentDaemon == null)
{
m_sipRegAgentDaemon = new SIPRegAgentDaemon(
m_sipSorceryPersistor.SIPProvidersPersistor,
m_sipSorceryPersistor.SIPProviderBindingsPersistor);
}
logger.Debug("Provisioning hosted service successfully started on " + m_sipProvisioningHost.BaseAddresses[0].AbsoluteUri + ".");
}
}
}
catch (Exception excp)
{
logger.Warn("Exception starting Provisioning hosted service. " + excp.Message);
}
try
{
if (WCFUtility.DoesWCFServiceExist(typeof(CrossDomainService).FullName.ToString()))
{
m_accessPolicyHost = new ServiceHost(typeof(CrossDomainService));
m_accessPolicyHost.Open();
logger.Debug("CrossDomain hosted service successfully started on " + m_accessPolicyHost.BaseAddresses[0].AbsoluteUri + ".");
}
}
catch (Exception excp)
{
logger.Warn("Exception starting CrossDomain hosted service. " + excp.Message);
}
try
{
if (WCFUtility.DoesWCFServiceExist(typeof(CallManagerServices).FullName.ToString()))
{
CallManagerServiceInstanceProvider callManagerSvcInstanceProvider = new CallManagerServiceInstanceProvider(m_callManager, m_sipDialogueManager);
Uri callManagerBaseAddress = null;
if (m_callManagerServiceAddress != null)
{
logger.Debug("Adding service address to Call Manager Service " + m_callManagerServiceAddress + ".");
callManagerBaseAddress = new Uri(m_callManagerServiceAddress);
}
if (callManagerBaseAddress != null)
{
m_callManagerSvcHost = new ServiceHost(typeof(CallManagerServices), callManagerBaseAddress);
}
else
{
m_callManagerSvcHost = new ServiceHost(typeof(CallManagerServices));
}
m_callManagerSvcHost.Description.Behaviors.Add(callManagerSvcInstanceProvider);
m_callManagerSvcHost.Open();
logger.Debug("CallManager hosted service successfully started on " + m_callManagerSvcHost.BaseAddresses[0].AbsoluteUri + ".");
}
}
catch (Exception excp)
{
logger.Warn("Exception starting CallManager hosted service. " + excp.Message);
}
if (WCFUtility.DoesWCFServiceExist(typeof(SIPNotifierService).FullName.ToString()))
{
if (m_sipMonitorPublisher != null)
{
try
{
SIPNotifierService notifierService = new SIPNotifierService(m_sipMonitorPublisher, m_customerSessionManager);
m_sipNotificationsHost = new ServiceHost(notifierService);
m_sipNotificationsHost.Open();
logger.Debug("SIPNotificationsService hosted service successfully started on " + m_sipNotificationsHost.BaseAddresses[0].AbsoluteUri + ".");
}
catch (Exception excp)
{
logger.Warn("Exception starting SIPNotificationsService hosted service. " + excp.Message);
}
}
}
#endregion
}
catch (Exception excp)
{
logger.Error("Exception SIPAppServerDaemon Start. " + excp.Message);
throw excp;
}
}
public void Stop()
{
try
{
logger.Debug("SIP Application Server stopping...");
DNSManager.Stop();
m_dialPlanEngine.StopScriptMonitoring = true;
if (m_accessPolicyHost != null)
{
m_accessPolicyHost.Close();
}
if (m_sipProvisioningHost != null)
{
m_sipProvisioningHost.Close();
}
if (m_callManagerSvcHost != null)
{
m_callManagerSvcHost.Close();
}
if (m_sipNotificationsHost != null)
{
m_sipNotificationsHost.Close();
}
if (m_callManager != null)
{
m_callManager.Stop();
}
if (m_rtccCore != null)
{
m_rtccCore.Stop();
}
if (m_notifyManager != null)
{
m_notifyManager.Stop();
}
if (m_monitorEventWriter != null)
{
m_monitorEventWriter.Close();
}
if (m_sipProxyDaemon != null)
{
m_sipProxyDaemon.Stop();
}
if (m_sipMonitorDaemon != null)
{
m_sipMonitorDaemon.Stop();
}
if (m_sipRegistrarDaemon != null)
{
m_sipRegistrarDaemon.Stop();
}
if (m_sipNotifierDaemon != null)
{
m_sipNotifierDaemon.Stop();
}
if (m_sipRegAgentDaemon != null)
{
m_sipRegAgentDaemon.Stop();
}
if (m_sipNotifierDaemon != null)
{
m_sipNotifierDaemon.Stop();
}
// Shutdown the SIPTransport layer.
m_sipTransport.Shutdown();
m_sipSorceryPersistor.StopCDRWrites = true;
logger.Debug("SIP Application Server stopped.");
}
catch (Exception excp)
{
logger.Error("Exception SIPAppServerDaemon Stop." + excp.Message);
}
}
#region Logging functions.
private void FireSIPMonitorEvent(SIPMonitorEvent sipMonitorEvent)
{
try
{
if (sipMonitorEvent != null && m_monitorEventWriter != null)
{
if (sipMonitorEvent is SIPMonitorConsoleEvent)
{
SIPMonitorConsoleEvent consoleEvent = sipMonitorEvent as SIPMonitorConsoleEvent;
if (consoleEvent.ServerType == SIPMonitorServerTypesEnum.RegisterAgent ||
(consoleEvent.EventType != SIPMonitorEventTypesEnum.FullSIPTrace &&
consoleEvent.EventType != SIPMonitorEventTypesEnum.SIPTransaction &&
consoleEvent.EventType != SIPMonitorEventTypesEnum.Timing &&
consoleEvent.EventType != SIPMonitorEventTypesEnum.UnrecognisedMessage &&
consoleEvent.EventType != SIPMonitorEventTypesEnum.ContactRegisterInProgress &&
consoleEvent.EventType != SIPMonitorEventTypesEnum.Monitor))
{
string eventUsername = (sipMonitorEvent.Username.IsNullOrBlank()) ? null : " " + sipMonitorEvent.Username;
dialPlanLogger.Debug("as (" + DateTime.Now.ToString("mm:ss:fff") + eventUsername + "): " + sipMonitorEvent.Message);
}
if (consoleEvent.EventType != SIPMonitorEventTypesEnum.SIPTransaction)
{
m_monitorEventWriter.Send(sipMonitorEvent);
}
}
else
{
m_monitorEventWriter.Send(sipMonitorEvent);
}
}
}
catch (Exception excp)
{
logger.Error("Exception FireSIPMonitorEvent. " + excp.Message);
}
}
private void LogSIPRequestIn(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, SIPRequest sipRequest)
{
string message = "App Svr Received: " + localSIPEndPoint.ToString() + "<-" + endPoint.ToString() + "\r\n" + sipRequest.ToString();
//logger.Debug("as: request in " + sipRequest.Method + " " + localSIPEndPoint.ToString() + "<-" + endPoint.ToString() + ", callid=" + sipRequest.Header.CallId + ".");
string fromUser = (sipRequest.Header.From != null && sipRequest.Header.From.FromURI != null) ? sipRequest.Header.From.FromURI.User : "Error on From header";
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, message, fromUser, localSIPEndPoint, endPoint));
}
private void LogSIPRequestOut(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, SIPRequest sipRequest)
{
string message = "App Svr Sent: " + localSIPEndPoint.ToString() + "->" + endPoint.ToString() + "\r\n" + sipRequest.ToString();
//logger.Debug("as: request out " + sipRequest.Method + " " + localSIPEndPoint.ToString() + "->" + endPoint.ToString() + ", callid=" + sipRequest.Header.CallId + ".");
string fromUser = (sipRequest.Header.From != null && sipRequest.Header.From.FromURI != null) ? sipRequest.Header.From.FromURI.User : "Error on From header";
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, message, fromUser, localSIPEndPoint, endPoint));
}
private void LogSIPResponseIn(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, SIPResponse sipResponse)
{
string message = "App Svr Received: " + localSIPEndPoint.ToString() + "<-" + endPoint.ToString() + "\r\n" + sipResponse.ToString();
//logger.Debug("as: response in " + sipResponse.Header.CSeqMethod + " " + localSIPEndPoint.ToString() + "<-" + endPoint.ToString() + ", callid=" + sipResponse.Header.CallId + ".");
string fromUser = (sipResponse.Header.From != null && sipResponse.Header.From.FromURI != null) ? sipResponse.Header.From.FromURI.User : "Error on From header";
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, message, fromUser, localSIPEndPoint, endPoint));
}
private void LogSIPResponseOut(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, SIPResponse sipResponse)
{
string message = "App Svr Sent: " + localSIPEndPoint.ToString() + "->" + endPoint.ToString() + "\r\n" + sipResponse.ToString();
//logger.Debug("as: response out " + sipResponse.Header.CSeqMethod + " " + localSIPEndPoint.ToString() + "->" + endPoint.ToString() + ", callid=" + sipResponse.Header.CallId + ".");
string fromUser = (sipResponse.Header.From != null && sipResponse.Header.From.FromURI != null) ? sipResponse.Header.From.FromURI.User : "Error on From header";
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, message, fromUser, localSIPEndPoint, endPoint));
}
private void LogSIPBadRequestIn(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, string sipMessage, SIPValidationFieldsEnum errorField, string rawMessage)
{
string errorMessage = "App Svr Bad Request Received: " + localSIPEndPoint + "<-" + endPoint.ToString() + ", " + errorField + ". " + sipMessage;
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.BadSIPMessage, errorMessage, null));
if (rawMessage != null)
{
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, errorMessage + "\r\n" + rawMessage, null));
}
}
private void LogSIPBadResponseIn(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, string sipMessage, SIPValidationFieldsEnum errorField, string rawMessage)
{
string errorMessage = "App Svr Bad Response Received: " + localSIPEndPoint + "<-" + endPoint.ToString() + ", " + errorField + ". " + sipMessage;
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.BadSIPMessage, errorMessage, null));
if (rawMessage != null)
{
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, errorMessage + "\r\n" + rawMessage, null));
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Management.StreamAnalytics;
using Microsoft.Azure.Management.StreamAnalytics.Models;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Xunit;
namespace StreamAnalytics.Tests
{
public class StreamingJobTests : TestBase
{
[Fact]
public async Task StreamingJobOperationsTest_JobShell()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string resourceGroupName = TestUtilities.GenerateName("sjrg");
string jobName = TestUtilities.GenerateName("sj");
var resourceManagementClient = this.GetResourceManagementClient(context);
var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context);
string expectedJobResourceId = TestHelper.GetJobResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName);
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation });
StreamingJob streamingJob = new StreamingJob()
{
Tags = new Dictionary<string, string>()
{
{ "key1", "value1" },
{ "randomKey", "randomValue" },
{ "key3", "value3" }
},
Location = TestHelper.DefaultLocation,
EventsOutOfOrderPolicy = EventsOutOfOrderPolicy.Drop,
EventsOutOfOrderMaxDelayInSeconds = 5,
EventsLateArrivalMaxDelayInSeconds = 16,
OutputErrorPolicy = OutputErrorPolicy.Drop,
DataLocale = "en-US",
CompatibilityLevel = CompatibilityLevel.OneFullStopZero,
Sku = new Microsoft.Azure.Management.StreamAnalytics.Models.Sku()
{
Name = SkuName.Standard
},
Inputs = new List<Input>(),
Outputs = new List<Output>(),
Functions = new List<Function>()
};
// PUT job
var putResponse = await streamAnalyticsManagementClient.StreamingJobs.CreateOrReplaceWithHttpMessagesAsync(streamingJob, resourceGroupName, jobName);
ValidationHelper.ValidateStreamingJob(streamingJob, putResponse.Body, false);
Assert.Equal(expectedJobResourceId, putResponse.Body.Id);
Assert.Equal(jobName, putResponse.Body.Name);
Assert.Equal(TestHelper.StreamingJobFullResourceType, putResponse.Body.Type);
Assert.Equal("Succeeded", putResponse.Body.ProvisioningState);
Assert.Equal("Created", putResponse.Body.JobState);
// Verify GET request returns expected job
var getResponse = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName, "inputs,outputs,transformation,functions");
ValidationHelper.ValidateStreamingJob(putResponse.Body, getResponse.Body, true);
// ETag should be the same
Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag);
// PATCH job
var streamingJobPatch = new StreamingJob()
{
EventsOutOfOrderMaxDelayInSeconds = 21,
EventsLateArrivalMaxDelayInSeconds = 13
};
putResponse.Body.EventsOutOfOrderMaxDelayInSeconds = streamingJobPatch.EventsOutOfOrderMaxDelayInSeconds;
putResponse.Body.EventsLateArrivalMaxDelayInSeconds = streamingJobPatch.EventsLateArrivalMaxDelayInSeconds;
putResponse.Body.Inputs = null;
putResponse.Body.Outputs = null;
putResponse.Body.Functions = null;
var patchResponse = await streamAnalyticsManagementClient.StreamingJobs.UpdateWithHttpMessagesAsync(streamingJobPatch, resourceGroupName, jobName);
ValidationHelper.ValidateStreamingJob(putResponse.Body, patchResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag);
putResponse.Body.Inputs = new List<Input>();
putResponse.Body.Outputs = new List<Output>();
putResponse.Body.Functions = new List<Function>();
// Run another GET job to verify that it returns the newly updated properties as well
getResponse = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName, "inputs,outputs,transformation,functions");
ValidationHelper.ValidateStreamingJob(putResponse.Body, getResponse.Body, true);
Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag);
Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag);
// List job and verify that the job shows up in the list
var listByRgResponse = streamAnalyticsManagementClient.StreamingJobs.ListByResourceGroup(resourceGroupName, "inputs,outputs,transformation,functions");
Assert.Single(listByRgResponse);
ValidationHelper.ValidateStreamingJob(putResponse.Body, listByRgResponse.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listByRgResponse.Single().Etag);
var listReponse = streamAnalyticsManagementClient.StreamingJobs.List("inputs, outputs, transformation, functions");
Assert.Single(listReponse);
ValidationHelper.ValidateStreamingJob(putResponse.Body, listReponse.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listReponse.Single().Etag);
// Delete job
streamAnalyticsManagementClient.StreamingJobs.Delete(resourceGroupName, jobName);
// Verify that list operation returns an empty list after deleting the job
listByRgResponse = streamAnalyticsManagementClient.StreamingJobs.ListByResourceGroup(resourceGroupName, "inputs,outputs,transformation,functions");
Assert.Empty(listByRgResponse);
listReponse = streamAnalyticsManagementClient.StreamingJobs.List("inputs, outputs, transformation, functions");
Assert.Empty(listReponse);
}
}
[Fact(Skip = "ReRecord due to CR change")]
public async Task StreamingJobOperationsTest_FullJob()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string resourceGroupName = TestUtilities.GenerateName("sjrg");
string jobName = TestUtilities.GenerateName("sj");
string inputName = "inputtest";
string transformationName = "transformationtest";
string outputName = "outputtest";
var resourceManagementClient = this.GetResourceManagementClient(context);
var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context);
string expectedJobResourceId = TestHelper.GetJobResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName);
string expectedInputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.InputsResourceType, inputName);
string expectedTransformationResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.TransformationResourceType, transformationName);
string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName);
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation });
StorageAccount storageAccount = new StorageAccount()
{
AccountName = TestHelper.AccountName,
AccountKey = TestHelper.AccountKey
};
Input input = new Input(id: expectedInputResourceId)
{
Name = inputName,
Properties = new StreamInputProperties()
{
Serialization = new JsonSerialization()
{
Encoding = Encoding.UTF8
},
Datasource = new BlobStreamInputDataSource()
{
StorageAccounts = new[] { storageAccount },
Container = TestHelper.Container,
PathPattern = "",
}
}
};
AzureSqlDatabaseOutputDataSource azureSqlDatabase = new AzureSqlDatabaseOutputDataSource()
{
Server = TestHelper.Server,
Database = TestHelper.Database,
User = TestHelper.User,
Password = TestHelper.Password,
Table = TestHelper.SqlTableName
};
Output output = new Output(id: expectedOutputResourceId)
{
Name = outputName,
Datasource = azureSqlDatabase
};
StreamingJob streamingJob = new StreamingJob()
{
Tags = new Dictionary<string, string>()
{
{ "key1", "value1" },
{ "randomKey", "randomValue" },
{ "key3", "value3" }
},
Location = TestHelper.DefaultLocation,
EventsOutOfOrderPolicy = EventsOutOfOrderPolicy.Drop,
EventsOutOfOrderMaxDelayInSeconds = 0,
EventsLateArrivalMaxDelayInSeconds = 5,
OutputErrorPolicy = OutputErrorPolicy.Drop,
DataLocale = "en-US",
CompatibilityLevel = "1.0",
Sku = new Microsoft.Azure.Management.StreamAnalytics.Models.Sku()
{
Name = SkuName.Standard
},
Inputs = new List<Input>() { input },
Transformation = new Transformation(id: expectedTransformationResourceId)
{
Name = transformationName,
Query = "Select Id, Name from inputtest",
StreamingUnits = 1
},
Outputs = new List<Output>() { output },
Functions = new List<Function>()
};
// PUT job
var putResponse = await streamAnalyticsManagementClient.StreamingJobs.CreateOrReplaceWithHttpMessagesAsync(streamingJob, resourceGroupName, jobName);
// Null out because secrets are not returned in responses
storageAccount.AccountKey = null;
azureSqlDatabase.Password = null;
ValidationHelper.ValidateStreamingJob(streamingJob, putResponse.Body, false);
Assert.Equal(expectedJobResourceId, putResponse.Body.Id);
Assert.Equal(jobName, putResponse.Body.Name);
Assert.Equal(TestHelper.StreamingJobFullResourceType, putResponse.Body.Type);
//Assert.True(putResponse.Body.CreatedDate > DateTime.UtcNow.AddMinutes(-1));
Assert.Equal("Succeeded", putResponse.Body.ProvisioningState);
Assert.Equal("Created", putResponse.Body.JobState);
// Verify GET request returns expected job
var getResponse = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName, "inputs,outputs,transformation,functions");
ValidationHelper.ValidateStreamingJob(putResponse.Body, getResponse.Body, true);
// ETag should be the same
Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag);
// PATCH job
var streamingJobPatch = new StreamingJob()
{
EventsOutOfOrderPolicy = EventsOutOfOrderPolicy.Adjust,
OutputErrorPolicy = OutputErrorPolicy.Stop
};
putResponse.Body.EventsOutOfOrderPolicy = streamingJobPatch.EventsOutOfOrderPolicy;
putResponse.Body.OutputErrorPolicy = streamingJobPatch.OutputErrorPolicy;
putResponse.Body.Functions = null;
streamingJob.EventsOutOfOrderPolicy = streamingJobPatch.EventsOutOfOrderPolicy;
streamingJob.OutputErrorPolicy = streamingJobPatch.OutputErrorPolicy;
streamingJob.Inputs = null;
streamingJob.Transformation = null;
streamingJob.Outputs = null;
streamingJob.Functions = null;
var patchResponse = await streamAnalyticsManagementClient.StreamingJobs.UpdateWithHttpMessagesAsync(streamingJobPatch, resourceGroupName, jobName);
ValidationHelper.ValidateStreamingJob(streamingJob, patchResponse.Body, false);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag);
putResponse.Body.Functions = new List<Function>();
// Run another GET job to verify that it returns the newly updated properties as well
getResponse = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName, "inputs,outputs,transformation,functions");
ValidationHelper.ValidateStreamingJob(putResponse.Body, getResponse.Body, true);
Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag);
Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag);
// List job and verify that the job shows up in the list
var listByRgResponse = streamAnalyticsManagementClient.StreamingJobs.ListByResourceGroup(resourceGroupName, "inputs,outputs,transformation,functions");
Assert.Single(listByRgResponse);
ValidationHelper.ValidateStreamingJob(putResponse.Body, listByRgResponse.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listByRgResponse.Single().Etag);
var listReponse = streamAnalyticsManagementClient.StreamingJobs.List("inputs, outputs, transformation, functions");
Assert.Single(listReponse);
ValidationHelper.ValidateStreamingJob(putResponse.Body, listReponse.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listReponse.Single().Etag);
// Start job
StartStreamingJobParameters startStreamingJobParameters = new StartStreamingJobParameters()
{
OutputStartMode = OutputStartMode.LastOutputEventTime
};
CloudException cloudException = Assert.Throws<CloudException>(() => streamAnalyticsManagementClient.StreamingJobs.Start(resourceGroupName, jobName, startStreamingJobParameters));
Assert.Equal((HttpStatusCode)422, cloudException.Response.StatusCode);
Assert.Contains("LastOutputEventTime must be available when OutputStartMode is set to LastOutputEventTime. Please make sure at least one output event has been processed.", cloudException.Response.Content);
startStreamingJobParameters.OutputStartMode = OutputStartMode.CustomTime;
startStreamingJobParameters.OutputStartTime = new DateTime(2012, 12, 12, 12, 12, 12, DateTimeKind.Utc);
putResponse.Body.OutputStartMode = startStreamingJobParameters.OutputStartMode;
putResponse.Body.OutputStartTime = startStreamingJobParameters.OutputStartTime;
streamingJob.OutputStartMode = startStreamingJobParameters.OutputStartMode;
streamingJob.OutputStartTime = startStreamingJobParameters.OutputStartTime;
streamAnalyticsManagementClient.StreamingJobs.Start(resourceGroupName, jobName, startStreamingJobParameters);
// Check that job started
var getResponseAfterStart = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName);
Assert.Equal("Succeeded", getResponseAfterStart.Body.ProvisioningState);
Assert.True(getResponseAfterStart.Body.JobState == "Running" || getResponseAfterStart.Body.JobState == "Degraded");
Assert.Null(getResponseAfterStart.Body.Inputs);
Assert.Null(getResponseAfterStart.Body.Transformation);
Assert.Null(getResponseAfterStart.Body.Outputs);
Assert.Null(getResponseAfterStart.Body.Functions);
ValidationHelper.ValidateStreamingJob(streamingJob, getResponseAfterStart.Body, false);
Assert.NotEqual(putResponse.Headers.ETag, getResponseAfterStart.Headers.ETag);
Assert.NotEqual(patchResponse.Headers.ETag, getResponseAfterStart.Headers.ETag);
// Check diagnostics
var inputListResponse = streamAnalyticsManagementClient.Inputs.ListByStreamingJob(resourceGroupName, jobName, "*");
Assert.NotNull(inputListResponse);
Assert.Single(inputListResponse);
var inputFromList = inputListResponse.Single();
Assert.NotNull(inputFromList.Properties.Diagnostics);
Assert.Equal(2, inputFromList.Properties.Diagnostics.Conditions.Count());
Assert.NotNull(inputFromList.Properties.Diagnostics.Conditions[0].Since);
DateTime.Parse(inputFromList.Properties.Diagnostics.Conditions[0].Since);
Assert.Equal(@"INP-3", inputFromList.Properties.Diagnostics.Conditions[0].Code);
Assert.Equal(@"Could not deserialize the input event(s) from resource 'https://$testAccountName$.blob.core.windows.net/state/states1.csv' as Json. Some possible reasons: 1) Malformed events 2) Input source configured with incorrect serialization format", inputFromList.Properties.Diagnostics.Conditions[0].Message);
// Stop job
streamAnalyticsManagementClient.StreamingJobs.Stop(resourceGroupName, jobName);
// Check that job stopped
var getResponseAfterStop = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName, "inputs,outputs,transformation,functions");
Assert.Equal("Succeeded", getResponseAfterStop.Body.ProvisioningState);
Assert.Equal("Stopped", getResponseAfterStop.Body.JobState);
ValidationHelper.ValidateStreamingJob(putResponse.Body, getResponseAfterStop.Body, false);
Assert.NotEqual(putResponse.Headers.ETag, getResponseAfterStop.Headers.ETag);
Assert.NotEqual(patchResponse.Headers.ETag, getResponseAfterStop.Headers.ETag);
Assert.NotEqual(getResponseAfterStart.Headers.ETag, getResponseAfterStop.Headers.ETag);
// Delete job
streamAnalyticsManagementClient.StreamingJobs.Delete(resourceGroupName, jobName);
// Verify that list operation returns an empty list after deleting the job
listByRgResponse = streamAnalyticsManagementClient.StreamingJobs.ListByResourceGroup(resourceGroupName, "inputs,outputs,transformation,functions");
Assert.Empty(listByRgResponse);
listReponse = streamAnalyticsManagementClient.StreamingJobs.List("inputs, outputs, transformation, functions");
Assert.Empty(listReponse);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace DrillTime.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Prism.Windows.Mvvm;
using Prism.Windows.Tests.Mocks;
using Prism.Windows.AppModel;
using Prism.Windows.Navigation;
using Prism.Windows.Tests.Utilities;
namespace Prism.Windows.Tests
{
[TestClass]
public class FrameNavigationServiceFixture
{
[TestMethod]
public async Task Navigate_To_Valid_Page()
{
await DispatcherHelper.ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
bool result = navigationService.Navigate("Mock", 1);
Assert.IsTrue(result);
Assert.IsNotNull(frame.Content);
Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
Assert.AreEqual(1, ((MockPage)frame.Content).PageParameter);
});
}
[TestMethod]
public async Task Navigate_To_Invalid_Page()
{
await DispatcherHelper.ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(string), sessionStateService);
bool result = navigationService.Navigate("Mock", 1);
Assert.IsFalse(result);
Assert.IsNull(frame.Content);
});
}
[TestMethod]
public async Task NavigateToCurrentViewModel_Calls_VieModel_OnNavigatedTo()
{
await DispatcherHelper.ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
bool viewModelNavigatedToCalled = false;
var viewModel = new MockPageViewModel();
viewModel.OnNavigatedFromCommand = (a, b) => Assert.IsTrue(true);
viewModel.OnNavigatedToCommand = (parameter, navigationMode, frameState) =>
{
Assert.AreEqual(NavigationMode.New, navigationMode);
viewModelNavigatedToCalled = true;
};
// Set up the viewModel to the Page we navigated
frame.NavigatedTo += (sender, e) =>
{
var view = frame.Content as FrameworkElement;
view.DataContext = viewModel;
};
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
navigationService.Navigate("Mock", 1);
Assert.IsTrue(viewModelNavigatedToCalled);
});
}
[TestMethod]
public async Task NavigateFromCurrentViewModel_Calls_VieModel_OnNavigatedFrom()
{
await DispatcherHelper.ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
bool viewModelNavigatedFromCalled = false;
var viewModel = new MockPageViewModel();
viewModel.OnNavigatedFromCommand = (frameState, suspending) =>
{
Assert.IsFalse(suspending);
viewModelNavigatedFromCalled = true;
};
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
// Initial navigatio
navigationService.Navigate("page0", 0);
// Set up the frame's content with a Page
var view = new MockPage();
view.DataContext = viewModel;
frame.Content = view;
// Navigate to fire the NavigatedToCurrentViewModel
navigationService.Navigate("page1", 1);
Assert.IsTrue(viewModelNavigatedFromCalled);
});
}
[TestMethod]
public async Task Suspending_Calls_VieModel_OnNavigatedFrom()
{
await DispatcherHelper.ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
navigationService.Navigate("Mock", 1);
var viewModel = new MockPageViewModel();
viewModel.OnNavigatedFromCommand = (frameState, suspending) =>
{
Assert.IsTrue(suspending);
};
var page = (MockPage)frame.Content;
page.DataContext = viewModel;
navigationService.Suspending();
});
}
[TestMethod]
public async Task Resuming_Calls_ViewModel_OnNavigatedTo()
{
await DispatcherHelper.ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
navigationService.Navigate("Mock", 1);
var viewModel = new MockPageViewModel();
viewModel.OnNavigatedToCommand = (navigationParameter, navigationMode, frameState) =>
{
Assert.AreEqual(NavigationMode.Refresh, navigationMode);
};
var page = (MockPage)frame.Content;
page.DataContext = viewModel;
navigationService.RestoreSavedNavigation();
});
}
[TestMethod]
public async Task GoBack_When_CanGoBack()
{
await DispatcherHelper.ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
bool resultFirstNavigation = navigationService.Navigate("MockPage", 1);
Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
Assert.AreEqual(1, ((MockPage)frame.Content).PageParameter);
Assert.IsFalse(navigationService.CanGoBack());
bool resultSecondNavigation = navigationService.Navigate("Mock", 2);
Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
Assert.AreEqual(2, ((MockPage)frame.Content).PageParameter);
Assert.IsTrue(navigationService.CanGoBack());
navigationService.GoBack();
Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
Assert.AreEqual(1, ((MockPage)frame.Content).PageParameter);
Assert.IsFalse(navigationService.CanGoBack());
});
}
[TestMethod]
public async Task ViewModelOnNavigatedFromCalled_WithItsOwnStateDictionary()
{
await DispatcherHelper.ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
var frameSessionState = new Dictionary<string, object>();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => frameSessionState;
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPageWithViewModel), sessionStateService);
navigationService.Navigate("Page1", 1);
Assert.AreEqual(1, frameSessionState.Count, "VM 1 state only");
navigationService.Navigate("Page2", 2);
Assert.AreEqual(2, frameSessionState.Count, "VM 1 and 2");
navigationService.Navigate("Page1", 1);
Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 1 again.");
navigationService.Navigate("Page3", 3);
Assert.AreEqual(4, frameSessionState.Count, "VM 1, 2, 1, and 3");
});
}
[TestMethod]
public async Task RestoreSavedNavigation_ClearsOldForwardNavigation()
{
await DispatcherHelper.ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
var frameSessionState = new Dictionary<string, object>();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => frameSessionState;
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPageWithViewModel), sessionStateService);
navigationService.Navigate("Page1", 1);
Assert.AreEqual(1, frameSessionState.Count, "VM 1 state only");
navigationService.Navigate("Page2", 2);
Assert.AreEqual(2, frameSessionState.Count, "VM 1 and 2");
navigationService.Navigate("Page3", 3);
Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 3");
navigationService.GoBack();
Assert.AreEqual(2, ((Dictionary<string, object>)frameSessionState["ViewModel-2"]).Count);
Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 3");
navigationService.Navigate("Page4", 4);
Assert.AreEqual(0, ((Dictionary<string,object>)frameSessionState["ViewModel-2"]).Count);
Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 4");
});
}
[TestMethod]
public async Task PageTokenThatCannotBeResolved_ThrowsMeaningfulException()
{
await DispatcherHelper.ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
var frameSessionState = new Dictionary<string, object>();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => frameSessionState;
Func<string, Type> unresolvablePageTokenReturnsNull = pageToken => null;
var navigationService = new FrameNavigationService(frame, unresolvablePageTokenReturnsNull, sessionStateService);
Assert.ThrowsException<ArgumentException>(
() => navigationService.Navigate("anything", 1)
);
});
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace AccessTokenMvcWebApp.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// File generated by hadoop record compiler. Do not edit.
/**
* 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.Linq;
using Org.Apache.Jute;
using log4net;
namespace Org.Apache.Zookeeper.Data
{
public class StatPersisted : IRecord, IComparable
{
private static ILog log = LogManager.GetLogger(typeof(StatPersisted));
public StatPersisted() {
}
public StatPersisted(
long czxid
,
long mzxid
,
long ctime
,
long mtime
,
int version
,
int cversion
,
int aversion
,
long ephemeralOwner
,
long pzxid
) {
Czxid=czxid;
Mzxid=mzxid;
Ctime=ctime;
Mtime=mtime;
Version=version;
Cversion=cversion;
Aversion=aversion;
EphemeralOwner=ephemeralOwner;
Pzxid=pzxid;
}
public long Czxid { get; set; }
public long Mzxid { get; set; }
public long Ctime { get; set; }
public long Mtime { get; set; }
public int Version { get; set; }
public int Cversion { get; set; }
public int Aversion { get; set; }
public long EphemeralOwner { get; set; }
public long Pzxid { get; set; }
public void Serialize(IOutputArchive a_, String tag) {
a_.StartRecord(this,tag);
a_.WriteLong(Czxid,"czxid");
a_.WriteLong(Mzxid,"mzxid");
a_.WriteLong(Ctime,"ctime");
a_.WriteLong(Mtime,"mtime");
a_.WriteInt(Version,"version");
a_.WriteInt(Cversion,"cversion");
a_.WriteInt(Aversion,"aversion");
a_.WriteLong(EphemeralOwner,"ephemeralOwner");
a_.WriteLong(Pzxid,"pzxid");
a_.EndRecord(this,tag);
}
public void Deserialize(IInputArchive a_, String tag) {
a_.StartRecord(tag);
Czxid=a_.ReadLong("czxid");
Mzxid=a_.ReadLong("mzxid");
Ctime=a_.ReadLong("ctime");
Mtime=a_.ReadLong("mtime");
Version=a_.ReadInt("version");
Cversion=a_.ReadInt("cversion");
Aversion=a_.ReadInt("aversion");
EphemeralOwner=a_.ReadLong("ephemeralOwner");
Pzxid=a_.ReadLong("pzxid");
a_.EndRecord(tag);
}
public override String ToString() {
try {
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using(ZooKeeperNet.IO.EndianBinaryWriter writer =
new ZooKeeperNet.IO.EndianBinaryWriter(ZooKeeperNet.IO.EndianBitConverter.Big, ms, System.Text.Encoding.UTF8)){
BinaryOutputArchive a_ =
new BinaryOutputArchive(writer);
a_.StartRecord(this,string.Empty);
a_.WriteLong(Czxid,"czxid");
a_.WriteLong(Mzxid,"mzxid");
a_.WriteLong(Ctime,"ctime");
a_.WriteLong(Mtime,"mtime");
a_.WriteInt(Version,"version");
a_.WriteInt(Cversion,"cversion");
a_.WriteInt(Aversion,"aversion");
a_.WriteLong(EphemeralOwner,"ephemeralOwner");
a_.WriteLong(Pzxid,"pzxid");
a_.EndRecord(this,string.Empty);
ms.Position = 0;
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
} } catch (Exception ex) {
log.Error(ex);
}
return "ERROR";
}
public void Write(ZooKeeperNet.IO.EndianBinaryWriter writer) {
BinaryOutputArchive archive = new BinaryOutputArchive(writer);
Serialize(archive, string.Empty);
}
public void ReadFields(ZooKeeperNet.IO.EndianBinaryReader reader) {
BinaryInputArchive archive = new BinaryInputArchive(reader);
Deserialize(archive, string.Empty);
}
public int CompareTo (object obj) {
StatPersisted peer = (StatPersisted) obj;
if (peer == null) {
throw new InvalidOperationException("Comparing different types of records.");
}
int ret = 0;
ret = (Czxid == peer.Czxid)? 0 :((Czxid<peer.Czxid)?-1:1);
if (ret != 0) return ret;
ret = (Mzxid == peer.Mzxid)? 0 :((Mzxid<peer.Mzxid)?-1:1);
if (ret != 0) return ret;
ret = (Ctime == peer.Ctime)? 0 :((Ctime<peer.Ctime)?-1:1);
if (ret != 0) return ret;
ret = (Mtime == peer.Mtime)? 0 :((Mtime<peer.Mtime)?-1:1);
if (ret != 0) return ret;
ret = (Version == peer.Version)? 0 :((Version<peer.Version)?-1:1);
if (ret != 0) return ret;
ret = (Cversion == peer.Cversion)? 0 :((Cversion<peer.Cversion)?-1:1);
if (ret != 0) return ret;
ret = (Aversion == peer.Aversion)? 0 :((Aversion<peer.Aversion)?-1:1);
if (ret != 0) return ret;
ret = (EphemeralOwner == peer.EphemeralOwner)? 0 :((EphemeralOwner<peer.EphemeralOwner)?-1:1);
if (ret != 0) return ret;
ret = (Pzxid == peer.Pzxid)? 0 :((Pzxid<peer.Pzxid)?-1:1);
if (ret != 0) return ret;
return ret;
}
public override bool Equals(object obj) {
StatPersisted peer = (StatPersisted) obj;
if (peer == null) {
return false;
}
if (Object.ReferenceEquals(peer,this)) {
return true;
}
bool ret = false;
ret = (Czxid==peer.Czxid);
if (!ret) return ret;
ret = (Mzxid==peer.Mzxid);
if (!ret) return ret;
ret = (Ctime==peer.Ctime);
if (!ret) return ret;
ret = (Mtime==peer.Mtime);
if (!ret) return ret;
ret = (Version==peer.Version);
if (!ret) return ret;
ret = (Cversion==peer.Cversion);
if (!ret) return ret;
ret = (Aversion==peer.Aversion);
if (!ret) return ret;
ret = (EphemeralOwner==peer.EphemeralOwner);
if (!ret) return ret;
ret = (Pzxid==peer.Pzxid);
if (!ret) return ret;
return ret;
}
public override int GetHashCode() {
int result = 17;
int ret = GetType().GetHashCode();
result = 37*result + ret;
ret = (int)Czxid;
result = 37*result + ret;
ret = (int)Mzxid;
result = 37*result + ret;
ret = (int)Ctime;
result = 37*result + ret;
ret = (int)Mtime;
result = 37*result + ret;
ret = (int)Version;
result = 37*result + ret;
ret = (int)Cversion;
result = 37*result + ret;
ret = (int)Aversion;
result = 37*result + ret;
ret = (int)EphemeralOwner;
result = 37*result + ret;
ret = (int)Pzxid;
result = 37*result + ret;
return result;
}
public static string Signature() {
return "LStatPersisted(lllliiill)";
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// eCases Messages Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SECMSGDataSet : EduHubDataSet<SECMSG>
{
/// <inheritdoc />
public override string Name { get { return "SECMSG"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SECMSGDataSet(EduHubContext Context)
: base(Context)
{
Index_ID = new Lazy<Dictionary<int, SECMSG>>(() => this.ToDictionary(i => i.ID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SECMSG" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SECMSG" /> fields for each CSV column header</returns>
internal override Action<SECMSG, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SECMSG, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "ID":
mapper[i] = (e, v) => e.ID = int.Parse(v);
break;
case "MESSAGE":
mapper[i] = (e, v) => e.MESSAGE = v;
break;
case "LAST_EDITED":
mapper[i] = (e, v) => e.LAST_EDITED = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "CREATOR":
mapper[i] = (e, v) => e.CREATOR = v;
break;
case "EXPIRY":
mapper[i] = (e, v) => e.EXPIRY = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SECMSG" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SECMSG" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SECMSG" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SECMSG}"/> of entities</returns>
internal override IEnumerable<SECMSG> ApplyDeltaEntities(IEnumerable<SECMSG> Entities, List<SECMSG> DeltaEntities)
{
HashSet<int> Index_ID = new HashSet<int>(DeltaEntities.Select(i => i.ID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.ID;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_ID.Remove(entity.ID);
if (entity.ID.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, SECMSG>> Index_ID;
#endregion
#region Index Methods
/// <summary>
/// Find SECMSG by ID field
/// </summary>
/// <param name="ID">ID value used to find SECMSG</param>
/// <returns>Related SECMSG entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SECMSG FindByID(int ID)
{
return Index_ID.Value[ID];
}
/// <summary>
/// Attempt to find SECMSG by ID field
/// </summary>
/// <param name="ID">ID value used to find SECMSG</param>
/// <param name="Value">Related SECMSG entity</param>
/// <returns>True if the related SECMSG entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByID(int ID, out SECMSG Value)
{
return Index_ID.Value.TryGetValue(ID, out Value);
}
/// <summary>
/// Attempt to find SECMSG by ID field
/// </summary>
/// <param name="ID">ID value used to find SECMSG</param>
/// <returns>Related SECMSG entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SECMSG TryFindByID(int ID)
{
SECMSG value;
if (Index_ID.Value.TryGetValue(ID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SECMSG table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SECMSG]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SECMSG](
[ID] int IDENTITY NOT NULL,
[MESSAGE] varchar(MAX) NULL,
[LAST_EDITED] datetime NULL,
[CREATOR] varchar(128) NULL,
[EXPIRY] datetime NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [SECMSG_Index_ID] PRIMARY KEY CLUSTERED (
[ID] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="SECMSGDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="SECMSGDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SECMSG"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SECMSG"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SECMSG> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_ID = new List<int>();
foreach (var entity in Entities)
{
Index_ID.Add(entity.ID);
}
builder.AppendLine("DELETE [dbo].[SECMSG] WHERE");
// Index_ID
builder.Append("[ID] IN (");
for (int index = 0; index < Index_ID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// ID
var parameterID = $"@p{parameterIndex++}";
builder.Append(parameterID);
command.Parameters.Add(parameterID, SqlDbType.Int).Value = Index_ID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SECMSG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SECMSG data set</returns>
public override EduHubDataSetDataReader<SECMSG> GetDataSetDataReader()
{
return new SECMSGDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SECMSG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SECMSG data set</returns>
public override EduHubDataSetDataReader<SECMSG> GetDataSetDataReader(List<SECMSG> Entities)
{
return new SECMSGDataReader(new EduHubDataSetLoadedReader<SECMSG>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SECMSGDataReader : EduHubDataSetDataReader<SECMSG>
{
public SECMSGDataReader(IEduHubDataSetReader<SECMSG> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 8; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // ID
return Current.ID;
case 1: // MESSAGE
return Current.MESSAGE;
case 2: // LAST_EDITED
return Current.LAST_EDITED;
case 3: // CREATOR
return Current.CREATOR;
case 4: // EXPIRY
return Current.EXPIRY;
case 5: // LW_DATE
return Current.LW_DATE;
case 6: // LW_TIME
return Current.LW_TIME;
case 7: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // MESSAGE
return Current.MESSAGE == null;
case 2: // LAST_EDITED
return Current.LAST_EDITED == null;
case 3: // CREATOR
return Current.CREATOR == null;
case 4: // EXPIRY
return Current.EXPIRY == null;
case 5: // LW_DATE
return Current.LW_DATE == null;
case 6: // LW_TIME
return Current.LW_TIME == null;
case 7: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // ID
return "ID";
case 1: // MESSAGE
return "MESSAGE";
case 2: // LAST_EDITED
return "LAST_EDITED";
case 3: // CREATOR
return "CREATOR";
case 4: // EXPIRY
return "EXPIRY";
case 5: // LW_DATE
return "LW_DATE";
case 6: // LW_TIME
return "LW_TIME";
case 7: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "ID":
return 0;
case "MESSAGE":
return 1;
case "LAST_EDITED":
return 2;
case "CREATOR":
return 3;
case "EXPIRY":
return 4;
case "LW_DATE":
return 5;
case "LW_TIME":
return 6;
case "LW_USER":
return 7;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
#region Copyright & license notice
/*
* Copyright: Copyright (c) 2007 Amazon Technologies, Inc.
* License: Apache License, Version 2.0
*/
#endregion
using System;
using System.Net;
using System.IO;
using System.Configuration;
using System.Reflection;
using Amazon.WebServices.MechanicalTurk.Advanced;
namespace Amazon.WebServices.MechanicalTurk
{
/// <summary>
/// Holds the client configuration necessary to communicate with the mechanical turk webservice.
/// A <c>MTurkConfig</c> instance must be passed to the <see cref="SimpleClient"/> or
/// <see cref="MTurkClient"/> instance to establish connectivity.
/// <para>
/// The <c>DefaultInstance</c> can be used when the configuration is retrieved from the application
/// configuration file. If the configuration is stored elsewhere, a separate <c>MTurkConfig</c> instance
/// must be instantiated and passed to the requester.
/// </para>
/// </summary>
public class MTurkConfig
{
#region Properties
/// <summary>
/// Additional key-value-pairs that can be passed into the SDK when the configuration
/// was not loaded from the application configuration file
/// </summary>
private System.Collections.Specialized.StringDictionary _context;
private System.Collections.Specialized.StringDictionary Context
{
get { return _context; }
}
private string _serviceEndpoint;
/// <summary>
/// Web service endpoint for Mechanical Turk
/// </summary>
public string ServiceEndpoint {
get { return _serviceEndpoint; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Cannot accept null or empty URL for service endpoint");
}
try
{
Uri uri = new Uri(value);
}
catch (UriFormatException uriEx)
{
throw new ArgumentException("Invalid service endpoint URI", uriEx);
}
MTurkLog.Debug("Configuring service endpoint: {0}", value);
_serviceEndpoint = value;
}
}
private string _accessKeyId;
/// <summary>
/// Access Key ID of Amazon Web Services account
/// </summary>
public string AccessKeyId {
get { return _accessKeyId; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Access key ID may not be null or empty");
}
if (_signer == null)
{
// create signer only if not already assigned
// this signer is overridden when secret access key is set
_signer = new HMACSigner(value);
}
_accessKeyId = value;
}
}
private string _secretAccessKey;
/// <summary>
/// Secret Access key for Amazon Web Services account matching the <see cref="AccessKeyId"/>
/// </summary>
public string SecretAccessKey {
get { return _secretAccessKey; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Secret access key may not be null or empty");
}
if (string.IsNullOrEmpty(_secretAccessKey) || !string.Equals(_secretAccessKey, value))
{
// create signer for this access key
_signer = new HMACSigner(value);
}
_secretAccessKey = value;
}
}
private string _websiteURL;
/// <summary>
/// Returns the worker website associated with the configured endpoint
/// </summary>
public string WebsiteURL
{
get { return (this._websiteURL); }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Cannot accept null or empty URL for worker website URL");
}
try
{
Uri uri = new Uri(value);
}
catch (UriFormatException uriEx)
{
throw new ArgumentException("Invalid worker website URI", uriEx);
}
MTurkLog.Debug("Configuring website URL: {0}", value);
_websiteURL = value;
}
}
private System.Net.IWebProxy _proxy = System.Net.WebRequest.DefaultWebProxy;
/// <summary>
/// Proxy used when SDK application sits behind firewall
/// </summary>
public System.Net.IWebProxy Proxy
{
get { return (this._proxy); }
set
{
if (value != null)
{
MTurkLog.Debug("Configuring proxy {0}", value);
}
this._proxy = value;
}
}
private bool _ensureQuestionsAreXmlWrappedBeforeSending=true;
/// <summary>
/// If true (default), makes sure that questions (e.g. to create a HIT)
/// are wrapped as XML prior to sending the request
/// </summary>
/// <remarks>
/// If a HIT question is not wrapped in XML (e.g. by using <see cref="QuestionUtil"/>),
/// then this option implicitly wrappes the question as single freetext question.
/// If this behaviour is undesired, it can be turned off by setting the
/// <c>MechanicalTurk.MiscOptions.EnsureQuestionsAreXmlWrapped</c> key in the
/// application configuration to <c>false</c>.
/// </remarks>
public bool EnsureQuestionsAreXmlWrappedBeforeSending
{
get { return (this._ensureQuestionsAreXmlWrappedBeforeSending); }
set
{
MTurkLog.Debug("Ensure question XML wrapping: {0}", value);
this._ensureQuestionsAreXmlWrappedBeforeSending = value;
}
}
private bool _validateQuestionBeforeSending=false;
/// <summary>
/// If true (default is false), then questions will be validated prior to sending
/// a request (such as CreateHIT).
/// </summary>
/// <remarks>
/// To enable this feature set the <c>MechanicalTurk.MiscOptions.EnsureQuestionValidity</c>
/// key in the application configuration to <c>true</c>.
/// </remarks>
public bool ValidateQuestionBeforeSending
{
get { return (this._validateQuestionBeforeSending); }
set
{
MTurkLog.Debug("Ensure question validation: {0}", value);
this._validateQuestionBeforeSending = value;
}
}
private int _maxRetryDelay=8000;
/// <summary>
/// Maximum time in milliseconds allowed for a retry attempt after throttling errors occured
/// </summary>
/// <remarks>
/// When testing against the Mechanical Turk Sandbox, the service endpoint may reject a request
/// because of service throttling. The SDK will retry to deliver the request as long as the
/// value for <c>MaxRetryDelay</c> is not exceeded.
/// </remarks>
public int MaxRetryDelay
{
get { return (this._maxRetryDelay); }
set { this._maxRetryDelay = value; }
}
private HMACSigner _signer;
internal HMACSigner Signer
{
get { return _signer; }
}
#endregion
#region Class properties
/// <summary>
/// The configuration used in the current thread
/// </summary>
[ThreadStatic]
private static MTurkConfig _currentInstance;
internal static MTurkConfig CurrentInstance
{
get { return _currentInstance; }
set { _currentInstance = value; }
}
private static string _sdkVersion = "MTurkDotNetSDK/" + typeof(MTurkConfig).Assembly.GetName().Version.ToString(4) + ",";
/// <summary>
/// Current version of the SDK
/// </summary>
public static string SdkVersion
{
get { return _sdkVersion; }
}
#endregion
#region Constructors
/// <summary>
/// Instantiates the client configuration by reading the application configuration file (app.config).
/// </summary>
/// <remarks>
/// The following values are read from the application configuration file:
/// <list type="bullet">
/// <item>
/// <term>MechanicalTurk.ServiceEndpoint</term>
/// <description>
/// The service endpoint receiving and processing mturk requests. Defaults to the sandbox endpoint at
/// <c>https://mechanicalturk.sandbox.amazonaws.com?Service=AWSMechanicalTurkRequester</c>
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.AccessKeyId</term>
/// <description>Required: The access key ID for the Amazon Web Services account</description>
/// </item>
/// <item>
/// <term>MechanicalTurk.SecretAccessKey</term>
/// <description>Required: The secret access key for the Amazon Web Services account</description>
/// </item>
/// <item>
/// <term>MechanicalTurk.Log.Level</term>
/// <description>The log level for SDK log messages (<see cref="ILog"/> for details). Defaults to 2 (Info)</description>
/// </item>
/// <item>
/// <term>MechanicalTurk.Proxy.Url</term>
/// <description>
/// Proxy URL (only necessary when used through a web proxy that requires authentication)
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.Proxy.User</term>
/// <description>
/// User name for proxy credentials (only necessary when used through a web proxy that
/// requires authentication)
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.Proxy.Password</term>
/// <description>
/// Password for proxy credentials (only necessary when used through a web proxy
/// that requires authentication)
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.Proxy.Domain</term>
/// <description>
/// User domain for proxy credentials (only necessary when used through a web proxy
/// that requires authentication)
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.MiscOptions.EnsureQuestionsAreXmlWrapped</term>
/// <description>
/// If set to true (default), ensures that questions are wrapped as XML when sent to
/// Mechanical Turk.
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.MiscOptions.EnsureQuestionValidity</term>
/// <description>
/// If set to true (default is false), ensures that questions are validated before
/// they are sent to Mechanical Turk
/// </description>
/// </item>
/// </list>
/// </remarks>
public MTurkConfig()
{
string configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
MTurkLog.Info("Loading config from " + configFile);
if (!File.Exists(configFile))
{
throw new IOException(string.Format("Cannot find Mechanical turk configuration file at '{0}'", configFile));
}
Init();
}
/// <summary>
/// Instantiates the client configuration by reading the application configuration from the context passed.
/// </summary>
/// <param name="context">Configuration with the following values:
/// <list type="bullet">
/// <item>
/// <term>MechanicalTurk.ServiceEndpoint</term>
/// <description>
/// The service endpoint receiving and processing mturk requests. Defaults to the sandbox endpoint at
/// <c>https://mechanicalturk.sandbox.amazonaws.com?Service=AWSMechanicalTurkRequester</c>
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.AccessKeyId</term>
/// <description>Required: The access key ID for the Amazon Web Services account</description>
/// </item>
/// <item>
/// <term>MechanicalTurk.SecretAccessKey</term>
/// <description>Required: The secret access key for the Amazon Web Services account</description>
/// </item>
/// <item>
/// <term>MechanicalTurk.Log.Level</term>
/// <description>The log level for SDK log messages (<see cref="ILog"/> for details). Defaults to 2 (Info)</description>
/// </item>
/// <item>
/// <term>MechanicalTurk.Proxy.Url</term>
/// <description>
/// Proxy URL (only necessary when used through a web proxy that requires authentication)
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.Proxy.User</term>
/// <description>
/// User name for proxy credentials (only necessary when used through a web proxy that
/// requires authentication)
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.Proxy.Password</term>
/// <description>
/// Password for proxy credentials (only necessary when used through a web proxy
/// that requires authentication)
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.Proxy.Domain</term>
/// <description>
/// User domain for proxy credentials (only necessary when used through a web proxy
/// that requires authentication)
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.MiscOptions.EnsureQuestionsAreXmlWrapped</term>
/// <description>
/// If set to true (default), ensures that questions are wrapped as XML when sent to
/// Mechanical Turk.
/// </description>
/// </item>
/// <item>
/// <term>MechanicalTurk.MiscOptions.EnsureQuestionValidity</term>
/// <description>
/// If set to true (default is false), ensures that questions are validated before
/// they are sent to Mechanical Turk
/// </description>
/// </item>
/// </list>
/// </param>
public MTurkConfig(System.Collections.Specialized.StringDictionary context)
{
_context = context;
Init();
}
/// <summary>
/// Instantiates a client for a service endpoint, access key ID and secret access key.
/// </summary>
/// <param name="serviceEndpoint">The service endpoint receiving and processing mturk
/// requests. If null, defaults to the sandbox endpoint at
/// <c>https://mechanicalturk.sandbox.amazonaws.com?Service=AWSMechanicalTurkRequester</c></param>
/// <param name="accessKeyId">Required: The access key ID for the Amazon Web Services account</param>
/// <param name="secretAccessKey">Required: The secret access key for the Amazon Web Services account</param>
public MTurkConfig(string serviceEndpoint, string accessKeyId, string secretAccessKey)
{
System.Collections.Specialized.StringDictionary ctx = new System.Collections.Specialized.StringDictionary();
ctx.Add("MechanicalTurk.ServiceEndpoint", serviceEndpoint);
ctx.Add("MechanicalTurk.AccessKeyId", accessKeyId);
ctx.Add("MechanicalTurk.SecretAccessKey", secretAccessKey);
_context = ctx;
Init();
}
#endregion
private void Init()
{
// log level
string logLevel = GetConfig("MechanicalTurk.Log.Level", "2");
byte level = 2;
if (!byte.TryParse(logLevel, out level))
{
MTurkLog.Warn("Invalid log level specified in configuration file ({0}). Defaulting to 'INFO'", logLevel);
}
MTurkLog.Level = level;
// AWS settings
string s = GetConfig("MechanicalTurk.ServiceEndpoint", null);
if (string.IsNullOrEmpty(s))
{
this.ServiceEndpoint = "https://mechanicalturk.sandbox.amazonaws.com?Service=AWSMechanicalTurkRequester";
}
else
{
this.ServiceEndpoint = s;
}
AccessKeyId = GetConfig("MechanicalTurk.AccessKeyId", null);
SecretAccessKey = GetConfig("MechanicalTurk.SecretAccessKey", null);
// Proxy settings when connecting through a proxy that requires authentication
string proxyURL = GetConfig("MechanicalTurk.Proxy.Url", null);
if (!string.IsNullOrEmpty(proxyURL))
{
Proxy = new WebProxy(proxyURL);
}
// set default credentials
Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
string proxyUser = GetConfig("MechanicalTurk.Proxy.User", null);
string proxyPassword = GetConfig("MechanicalTurk.Proxy.Password", null);
string proxyDomain = GetConfig("MechanicalTurk.Proxy.Domain", null);
if (!string.IsNullOrEmpty(proxyUser) && !string.IsNullOrEmpty(proxyPassword))
{
// override default credentials
Proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword, proxyDomain);
}
// worker website
string url = GetConfig("MechanicalTurk.Url", null);
if (url != null)
{
this.WebsiteURL = url;
}
else
{
if (this.ServiceEndpoint.ToLower().IndexOf("sandbox") != -1)
{
this.WebsiteURL = "http://workersandbox.mturk.com";
}
else
{
this.WebsiteURL = "http://www.mturk.com";
}
}
// question settings: Implicitly wrap questions
string wrap = GetConfig("MechanicalTurk.MiscOptions.EnsureQuestionsAreXmlWrapped", null);
if (wrap != null)
{
this.EnsureQuestionsAreXmlWrappedBeforeSending = wrap.ToLower().Equals("true");
}
// question settings: Implicitly validate
string validate = GetConfig("MechanicalTurk.MiscOptions.EnsureQuestionValidity", null);
if (validate != null)
{
this.ValidateQuestionBeforeSending = validate.ToLower().Equals("true");
}
// retry delay for sandbox throttling
MaxRetryDelay = int.Parse(GetConfig("MechanicalTurk.MaxRetryDelay", "8000"));
MTurkLog.Info("Initialized configuration for '{0}'", this.ServiceEndpoint);
}
/// <summary>
/// Returns a value from the configuration
/// </summary>
/// <param name="key">Configuration key</param>
/// <param name="defaultValue">Value returned, if no value is configured for the
/// requested key</param>
/// <returns>Configured value (or default)</returns>
public string GetConfig(string key, string defaultValue)
{
if (key == null)
{
throw new ArgumentNullException("key", "Can't get configuration value for null key");
}
string ret = (Context == null) ? ConfigurationManager.AppSettings.Get(key) : Context[key];
if (ret == null)
{
ret = defaultValue;
}
if (ret != null)
{
ret = ret.Trim();
}
return ret;
}
/// <summary>
/// Returns the URL, where the HIT can be viewed at the worker website or "n/a" if HIT was not
/// yet created or loaded.
/// </summary>
/// <param name="hitTypeID">The HIT type ID of an existing HIT</param>
public string GetPreviewURL(string hitTypeID)
{
if (string.IsNullOrEmpty(hitTypeID))
{
return "n/a";
}
else
{
return string.Format("{0}/mturk/preview?groupId={1}", this.WebsiteURL, hitTypeID);
}
}
/// <summary>
/// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </returns>
public override string ToString()
{
return string.Format("Url: {0}, AWS Info: {1}, Proxy: {2}",
this.ServiceEndpoint,
this.AccessKeyId.GetHashCode(),
this.Proxy != null);
}
}
}
| |
using System;
using Spring.Expressions.Parser.antlr.debug;
using Stream = System.IO.Stream;
using TextReader = System.IO.TextReader;
using StringBuilder = System.Text.StringBuilder;
using Hashtable = System.Collections.Hashtable;
using Assembly = System.Reflection.Assembly;
using EventHandlerList = System.ComponentModel.EventHandlerList;
using BitSet = Spring.Expressions.Parser.antlr.collections.impl.BitSet;
namespace Spring.Expressions.Parser.antlr
{
/*ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/license.html
*
* $Id:$
*/
//
// ANTLR C# Code Generator by Micheal Jordan
// Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com
// Anthony Oguntimehin
//
// With many thanks to Eric V. Smith from the ANTLR list.
//
public abstract class CharScanner : TokenStream, ICharScannerDebugSubject
{
internal const char NO_CHAR = (char) (0);
public static readonly char EOF_CHAR = Char.MaxValue;
// Used to store event delegates
private EventHandlerList events_ = new EventHandlerList();
protected internal EventHandlerList Events
{
get { return events_; }
}
// The unique keys for each event that CharScanner [objects] can generate
internal static readonly object EnterRuleEventKey = new object();
internal static readonly object ExitRuleEventKey = new object();
internal static readonly object DoneEventKey = new object();
internal static readonly object ReportErrorEventKey = new object();
internal static readonly object ReportWarningEventKey = new object();
internal static readonly object NewLineEventKey = new object();
internal static readonly object MatchEventKey = new object();
internal static readonly object MatchNotEventKey = new object();
internal static readonly object MisMatchEventKey = new object();
internal static readonly object MisMatchNotEventKey = new object();
internal static readonly object ConsumeEventKey = new object();
internal static readonly object LAEventKey = new object();
internal static readonly object SemPredEvaluatedEventKey = new object();
internal static readonly object SynPredStartedEventKey = new object();
internal static readonly object SynPredFailedEventKey = new object();
internal static readonly object SynPredSucceededEventKey = new object();
protected internal StringBuilder text; // text of current token
protected bool saveConsumedInput = true; // does consume() save characters?
/// <summary>Used for creating Token instances.</summary>
protected TokenCreator tokenCreator;
/// <summary>Used for caching lookahead characters.</summary>
protected char cached_LA1;
protected char cached_LA2;
protected bool caseSensitive = true;
protected bool caseSensitiveLiterals = true;
protected Hashtable literals; // set by subclass
/*Tab chars are handled by tab() according to this value; override
* method to do anything weird with tabs.
*/
protected internal int tabsize = 8;
protected internal IToken returnToken_ = null; // used to return tokens w/o using return val.
protected internal LexerSharedInputState inputState;
/*Used during filter mode to indicate that path is desired.
* A subsequent scan error will report an error as usual if
* acceptPath=true;
*/
protected internal bool commitToPath = false;
/*Used to keep track of indentdepth for traceIn/Out */
protected internal int traceDepth = 0;
public CharScanner()
{
text = new StringBuilder();
setTokenCreator(new CommonToken.CommonTokenCreator());
}
public CharScanner(InputBuffer cb) : this()
{
inputState = new LexerSharedInputState(cb);
cached_LA2 = inputState.input.LA(2);
cached_LA1 = inputState.input.LA(1);
}
public CharScanner(LexerSharedInputState sharedState) : this()
{
inputState = sharedState;
if (inputState != null)
{
cached_LA2 = inputState.input.LA(2);
cached_LA1 = inputState.input.LA(1);
}
}
public event TraceEventHandler EnterRule
{
add { Events.AddHandler(EnterRuleEventKey, value); }
remove { Events.RemoveHandler(EnterRuleEventKey, value); }
}
public event TraceEventHandler ExitRule
{
add { Events.AddHandler(ExitRuleEventKey, value); }
remove { Events.RemoveHandler(ExitRuleEventKey, value); }
}
public event TraceEventHandler Done
{
add { Events.AddHandler(DoneEventKey, value); }
remove { Events.RemoveHandler(DoneEventKey, value); }
}
public event MessageEventHandler ErrorReported
{
add { Events.AddHandler(ReportErrorEventKey, value); }
remove { Events.RemoveHandler(ReportErrorEventKey, value); }
}
public event MessageEventHandler WarningReported
{
add { Events.AddHandler(ReportWarningEventKey, value); }
remove { Events.RemoveHandler(ReportWarningEventKey, value); }
}
public event NewLineEventHandler HitNewLine
{
add { Events.AddHandler(NewLineEventKey, value); }
remove { Events.RemoveHandler(NewLineEventKey, value); }
}
public event MatchEventHandler MatchedChar
{
add { Events.AddHandler(MatchEventKey, value); }
remove { Events.RemoveHandler(MatchEventKey, value); }
}
public event MatchEventHandler MatchedNotChar
{
add { Events.AddHandler(MatchNotEventKey, value); }
remove { Events.RemoveHandler(MatchNotEventKey, value); }
}
public event MatchEventHandler MisMatchedChar
{
add { Events.AddHandler(MisMatchEventKey, value); }
remove { Events.RemoveHandler(MisMatchEventKey, value); }
}
public event MatchEventHandler MisMatchedNotChar
{
add { Events.AddHandler(MisMatchNotEventKey, value); }
remove { Events.RemoveHandler(MisMatchNotEventKey, value); }
}
public event TokenEventHandler ConsumedChar
{
add { Events.AddHandler(ConsumeEventKey, value); }
remove { Events.RemoveHandler(ConsumeEventKey, value); }
}
public event TokenEventHandler CharLA
{
add { Events.AddHandler(LAEventKey, value); }
remove { Events.RemoveHandler(LAEventKey, value); }
}
public event SemanticPredicateEventHandler SemPredEvaluated
{
add { Events.AddHandler(SemPredEvaluatedEventKey, value); }
remove { Events.RemoveHandler(SemPredEvaluatedEventKey, value); }
}
public event SyntacticPredicateEventHandler SynPredStarted
{
add { Events.AddHandler(SynPredStartedEventKey, value); }
remove { Events.RemoveHandler(SynPredStartedEventKey, value); }
}
public event SyntacticPredicateEventHandler SynPredFailed
{
add { Events.AddHandler(SynPredFailedEventKey, value); }
remove { Events.RemoveHandler(SynPredFailedEventKey, value); }
}
public event SyntacticPredicateEventHandler SynPredSucceeded
{
add { Events.AddHandler(SynPredSucceededEventKey, value); }
remove { Events.RemoveHandler(SynPredSucceededEventKey, value); }
}
// From interface TokenStream
public virtual IToken nextToken() { return null; }
public virtual void append(char c)
{
if (saveConsumedInput)
{
text.Append(c);
}
}
public virtual void append(string s)
{
if (saveConsumedInput)
{
text.Append(s);
}
}
public virtual void commit()
{
inputState.input.commit();
}
public virtual void recover(RecognitionException ex, BitSet tokenSet)
{
consume();
consumeUntil(tokenSet);
}
public virtual void consume()
{
if (inputState.guessing == 0)
{
if (caseSensitive)
{
append(cached_LA1);
}
else
{
// use input.LA(), not LA(), to get original case
// CharScanner.LA() would toLower it.
append(inputState.input.LA(1));
}
if (cached_LA1 == '\t')
{
tab();
}
else
{
inputState.column++;
}
}
if (caseSensitive)
{
cached_LA1 = inputState.input.consume();
cached_LA2 = inputState.input.LA(2);
}
else
{
cached_LA1 = toLower(inputState.input.consume());
cached_LA2 = toLower(inputState.input.LA(2));
}
}
/*Consume chars until one matches the given char */
public virtual void consumeUntil(int c)
{
while ((EOF_CHAR != cached_LA1) && (c != cached_LA1))
{
consume();
}
}
/*Consume chars until one matches the given set */
public virtual void consumeUntil(BitSet bset)
{
while (cached_LA1 != EOF_CHAR && !bset.member(cached_LA1))
{
consume();
}
}
public virtual bool getCaseSensitive()
{
return caseSensitive;
}
public bool getCaseSensitiveLiterals()
{
return caseSensitiveLiterals;
}
public virtual int getColumn()
{
return inputState.column;
}
public virtual void setColumn(int c)
{
inputState.column = c;
}
public virtual bool getCommitToPath()
{
return commitToPath;
}
public virtual string getFilename()
{
return inputState.filename;
}
public virtual InputBuffer getInputBuffer()
{
return inputState.input;
}
public virtual LexerSharedInputState getInputState()
{
return inputState;
}
public virtual void setInputState(LexerSharedInputState state)
{
inputState = state;
}
public virtual int getLine()
{
return inputState.line;
}
/*return a copy of the current text buffer */
public virtual string getText()
{
return text.ToString();
}
public virtual IToken getTokenObject()
{
return returnToken_;
}
public virtual char LA(int i)
{
if (i == 1)
{
return cached_LA1;
}
if (i == 2)
{
return cached_LA2;
}
if (caseSensitive)
{
return inputState.input.LA(i);
}
else
{
return toLower(inputState.input.LA(i));
}
}
protected internal virtual IToken makeToken(int t)
{
IToken newToken = null;
bool typeCreated;
try
{
newToken = tokenCreator.Create();
if (newToken != null)
{
newToken.Type = t;
newToken.setColumn(inputState.tokenStartColumn);
newToken.setLine(inputState.tokenStartLine);
// tracking real start line now: newToken.setLine(inputState.line);
newToken.setFilename(inputState.filename);
}
typeCreated = true;
}
catch
{
typeCreated = false;
}
if (!typeCreated)
{
panic("Can't create Token object '" + tokenCreator.TokenTypeName + "'");
newToken = Token.badToken;
}
return newToken;
}
public virtual int mark()
{
return inputState.input.mark();
}
public virtual void match(char c)
{
match((int) c);
}
public virtual void match(int c)
{
if (cached_LA1 != c)
{
throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), false, this);
}
consume();
}
public virtual void match(BitSet b)
{
if (!b.member(cached_LA1))
{
throw new MismatchedCharException(cached_LA1, b, false, this);
}
consume();
}
public virtual void match(string s)
{
int len = s.Length;
for (int i = 0; i < len; i++)
{
if (cached_LA1 != s[i])
{
throw new MismatchedCharException(cached_LA1, s[i], false, this);
}
consume();
}
}
public virtual void matchNot(char c)
{
matchNot((int) c);
}
public virtual void matchNot(int c)
{
if (cached_LA1 == c)
{
throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), true, this);
}
consume();
}
public virtual void matchRange(int c1, int c2)
{
if (cached_LA1 < c1 || cached_LA1 > c2)
{
throw new MismatchedCharException(cached_LA1, Convert.ToChar(c1), Convert.ToChar(c2), false, this);
}
consume();
}
public virtual void matchRange(char c1, char c2)
{
matchRange((int) c1, (int) c2);
}
public virtual void newline()
{
inputState.line++;
inputState.column = 1;
}
/*advance the current column number by an appropriate amount
* according to tab size. This method is called from consume().
*/
public virtual void tab()
{
int c = getColumn();
int nc = (((c - 1) / tabsize) + 1) * tabsize + 1; // calculate tab stop
setColumn(nc);
}
public virtual void setTabSize(int size)
{
tabsize = size;
}
public virtual int getTabSize()
{
return tabsize;
}
public virtual void panic()
{
//Console.Error.WriteLine("CharScanner: panic");
//Environment.Exit(1);
panic("");
}
/// <summary>
/// This method is executed by ANTLR internally when it detected an illegal
/// state that cannot be recovered from.
/// The previous implementation of this method called <see cref="Environment.Exit"/>
/// and writes directly to <see cref="Console.Error"/>, which is usually not
/// appropriate when a translator is embedded into a larger application.
/// </summary>
/// <param name="s">Error message.</param>
public virtual void panic(string s)
{
//Console.Error.WriteLine("CharScanner; panic: " + s);
//Environment.Exit(1);
throw new ANTLRPanicException("CharScanner::panic: " + s);
}
/*Parser error-reporting function can be overridden in subclass */
public virtual void reportError(RecognitionException ex)
{
Console.Error.WriteLine(ex);
}
/*Parser error-reporting function can be overridden in subclass */
public virtual void reportError(string s)
{
if (getFilename() == null)
{
Console.Error.WriteLine("error: " + s);
}
else
{
Console.Error.WriteLine(getFilename() + ": error: " + s);
}
}
/*Parser warning-reporting function can be overridden in subclass */
public virtual void reportWarning(string s)
{
if (getFilename() == null)
{
Console.Error.WriteLine("warning: " + s);
}
else
{
Console.Error.WriteLine(getFilename() + ": warning: " + s);
}
}
public virtual void refresh()
{
if (caseSensitive)
{
cached_LA2 = inputState.input.LA(2);
cached_LA1 = inputState.input.LA(1);
}
else
{
cached_LA2 = toLower(inputState.input.LA(2));
cached_LA1 = toLower(inputState.input.LA(1));
}
}
public virtual void resetState(InputBuffer ib)
{
text.Length = 0;
traceDepth = 0;
inputState.resetInput(ib);
refresh();
}
public void resetState(Stream s)
{
resetState(new ByteBuffer(s));
}
public void resetState(TextReader tr)
{
resetState(new CharBuffer(tr));
}
public virtual void resetText()
{
text.Length = 0;
inputState.tokenStartColumn = inputState.column;
inputState.tokenStartLine = inputState.line;
}
public virtual void rewind(int pos)
{
inputState.input.rewind(pos);
//setColumn(inputState.tokenStartColumn);
if (caseSensitive)
{
cached_LA2 = inputState.input.LA(2);
cached_LA1 = inputState.input.LA(1);
}
else
{
cached_LA2 = toLower(inputState.input.LA(2));
cached_LA1 = toLower(inputState.input.LA(1));
}
}
public virtual void setCaseSensitive(bool t)
{
caseSensitive = t;
if (caseSensitive)
{
cached_LA2 = inputState.input.LA(2);
cached_LA1 = inputState.input.LA(1);
}
else
{
cached_LA2 = toLower(inputState.input.LA(2));
cached_LA1 = toLower(inputState.input.LA(1));
}
}
public virtual void setCommitToPath(bool commit)
{
commitToPath = commit;
}
public virtual void setFilename(string f)
{
inputState.filename = f;
}
public virtual void setLine(int line)
{
inputState.line = line;
}
public virtual void setText(string s)
{
resetText();
text.Append(s);
}
public virtual void setTokenObjectClass(string cl)
{
this.tokenCreator = new ReflectionBasedTokenCreator(this, cl);
}
public virtual void setTokenCreator(TokenCreator tokenCreator)
{
this.tokenCreator = tokenCreator;
}
// Test the token text against the literals table
// Override this method to perform a different literals test
public virtual int testLiteralsTable(int ttype)
{
string tokenText = text.ToString();
if ( (tokenText == null) || (tokenText == string.Empty) )
return ttype;
else
{
object typeAsObject = literals[tokenText];
return (typeAsObject == null) ? ttype : ((int) typeAsObject);
}
}
/*Test the text passed in against the literals table
* Override this method to perform a different literals test
* This is used primarily when you want to test a portion of
* a token.
*/
public virtual int testLiteralsTable(string someText, int ttype)
{
if ( (someText == null) || (someText == string.Empty) )
return ttype;
else
{
object typeAsObject = literals[someText];
return (typeAsObject == null) ? ttype : ((int) typeAsObject);
}
}
// Override this method to get more specific case handling
public virtual char toLower(int c)
{
return Char.ToLower(Convert.ToChar(c), System.Globalization.CultureInfo.InvariantCulture);
}
public virtual void traceIndent()
{
for (int i = 0; i < traceDepth; i++)
Console.Out.Write(" ");
}
public virtual void traceIn(string rname)
{
traceDepth += 1;
traceIndent();
Console.Out.WriteLine("> lexer " + rname + "; c==" + LA(1));
}
public virtual void traceOut(string rname)
{
traceIndent();
Console.Out.WriteLine("< lexer " + rname + "; c==" + LA(1));
traceDepth -= 1;
}
/*This method is called by YourLexer.nextToken() when the lexer has
* hit EOF condition. EOF is NOT a character.
* This method is not called if EOF is reached during
* syntactic predicate evaluation or during evaluation
* of normal lexical rules, which presumably would be
* an IOException. This traps the "normal" EOF condition.
*
* uponEOF() is called after the complete evaluation of
* the previous token and only if your parser asks
* for another token beyond that last non-EOF token.
*
* You might want to throw token or char stream exceptions
* like: "Heh, premature eof" or a retry stream exception
* ("I found the end of this file, go back to referencing file").
*/
public virtual void uponEOF()
{
}
private class ReflectionBasedTokenCreator : TokenCreator
{
protected ReflectionBasedTokenCreator() {}
public ReflectionBasedTokenCreator(CharScanner owner, string tokenTypeName)
{
this.owner = owner;
SetTokenType(tokenTypeName);
}
private CharScanner owner;
/// <summary>
/// The fully qualified name of the Token type to create.
/// </summary>
private string tokenTypeName;
/// <summary>
/// Type object used as a template for creating tokens by reflection.
/// </summary>
private Type tokenTypeObject;
/// <summary>
/// Returns the fully qualified name of the Token type that this
/// class creates.
/// </summary>
private void SetTokenType(string tokenTypeName)
{
this.tokenTypeName = tokenTypeName;
foreach (Assembly assem in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
tokenTypeObject = assem.GetType(tokenTypeName);
if (tokenTypeObject != null)
{
break;
}
}
catch
{
throw new TypeLoadException("Unable to load Type for Token class '" + tokenTypeName + "'");
}
}
if (tokenTypeObject==null)
throw new TypeLoadException("Unable to load Type for Token class '" + tokenTypeName + "'");
}
/// <summary>
/// Returns the fully qualified name of the Token type that this
/// class creates.
/// </summary>
public override string TokenTypeName
{
get
{
return tokenTypeName;
}
}
/// <summary>
/// Constructs a <see cref="Token"/> instance.
/// </summary>
public override IToken Create()
{
IToken newToken = null;
try
{
newToken = (Token) Activator.CreateInstance(tokenTypeObject);
}
catch
{
// supress exception
}
return newToken;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Used to enumerate the commands on the system that match the specified
/// command name.
/// </summary>
internal class CommandPathSearch : IEnumerable<string>, IEnumerator<string>
{
[TraceSource("CommandSearch", "CommandSearch")]
private static PSTraceSource s_tracer = PSTraceSource.GetTracer("CommandSearch", "CommandSearch");
/// <summary>
/// Constructs a command searching enumerator that resolves the location
/// of a command using the PATH environment variable.
/// </summary>
/// <param name="patterns">
/// The patterns to search for in the path.
/// </param>
/// <param name="lookupPaths">
/// The paths to directories in which to lookup the command.
/// </param>
/// <param name="context">
/// The execution context for the current engine instance.
/// </param>
internal CommandPathSearch(
IEnumerable<string> patterns,
IEnumerable<string> lookupPaths,
ExecutionContext context)
{
Init(patterns, lookupPaths, context);
}
internal CommandPathSearch(
string commandName,
IEnumerable<string> lookupPaths,
ExecutionContext context,
Collection<string> acceptableCommandNames,
bool useFuzzyMatch = false)
{
_useFuzzyMatch = useFuzzyMatch;
string[] commandPatterns;
if (acceptableCommandNames != null)
{
// The name passed in is not a pattern. To minimize enumerating the file system, we
// turn the command name into a pattern and then match against extensions in PATHEXT.
// The old code would enumerate the file system many more times, once per possible extension.
if (Platform.IsWindows)
{
commandPatterns = new[] { commandName + ".*" };
}
else
{
// Porting note: on non-Windows platforms, we want to always allow just 'commandName'
// as an acceptable command name. However, we also want to allow commands to be
// called with the .ps1 extension, so that 'script.ps1' can be called by 'script'.
commandPatterns = new[] { commandName, commandName + ".ps1" };
}
_postProcessEnumeratedFiles = CheckAgainstAcceptableCommandNames;
_acceptableCommandNames = acceptableCommandNames;
}
else
{
commandPatterns = new[] { commandName };
_postProcessEnumeratedFiles = JustCheckExtensions;
}
Init(commandPatterns, lookupPaths, context);
_orderedPathExt = CommandDiscovery.PathExtensionsWithPs1Prepended;
}
private void Init(IEnumerable<string> commandPatterns, IEnumerable<string> searchPath, ExecutionContext context)
{
// Note, discovery must be set before resolving the current directory
_context = context;
_patterns = commandPatterns;
_lookupPaths = new LookupPathCollection(searchPath);
ResolveCurrentDirectoryInLookupPaths();
this.Reset();
}
/// <summary>
/// Ensures that all the paths in the lookupPaths member are absolute
/// file system paths.
/// </summary>
private void ResolveCurrentDirectoryInLookupPaths()
{
var indexesToRemove = new SortedDictionary<int, int>();
int removalListCount = 0;
string fileSystemProviderName = _context.ProviderNames.FileSystem;
SessionStateInternal sessionState = _context.EngineSessionState;
// Only use the directory if it gets resolved by the FileSystemProvider
bool isCurrentDriveValid =
sessionState.CurrentDrive != null &&
sessionState.CurrentDrive.Provider.NameEquals(fileSystemProviderName) &&
sessionState.IsProviderLoaded(fileSystemProviderName);
string environmentCurrentDirectory = Directory.GetCurrentDirectory();
LocationGlobber pathResolver = _context.LocationGlobber;
// Loop through the relative paths and resolve them
foreach (int index in _lookupPaths.IndexOfRelativePath())
{
string resolvedDirectory = null;
string resolvedPath = null;
CommandDiscovery.discoveryTracer.WriteLine(
"Lookup directory \"{0}\" appears to be a relative path. Attempting resolution...",
_lookupPaths[index]);
if (isCurrentDriveValid)
{
try
{
ProviderInfo provider;
resolvedPath =
pathResolver.GetProviderPath(
_lookupPaths[index],
out provider);
}
catch (ProviderInvocationException providerInvocationException)
{
CommandDiscovery.discoveryTracer.WriteLine(
"The relative path '{0}', could not be resolved because the provider threw an exception: '{1}'",
_lookupPaths[index],
providerInvocationException.Message);
}
catch (InvalidOperationException)
{
CommandDiscovery.discoveryTracer.WriteLine(
"The relative path '{0}', could not resolve a home directory for the provider",
_lookupPaths[index]);
}
// Note, if the directory resolves to multiple paths, only the first is used.
if (!string.IsNullOrEmpty(resolvedPath))
{
CommandDiscovery.discoveryTracer.TraceError(
"The relative path resolved to: {0}",
resolvedPath);
resolvedDirectory = resolvedPath;
}
else
{
CommandDiscovery.discoveryTracer.WriteLine(
"The relative path was not a file system path. {0}",
_lookupPaths[index]);
}
}
else
{
CommandDiscovery.discoveryTracer.TraceWarning(
"The current drive is not set, using the process current directory: {0}",
environmentCurrentDirectory);
resolvedDirectory = environmentCurrentDirectory;
}
// If we successfully resolved the path, make sure it is unique. Remove
// any duplicates found after the first occurrence of the path.
if (resolvedDirectory != null)
{
int existingIndex = _lookupPaths.IndexOf(resolvedDirectory);
if (existingIndex != -1)
{
if (existingIndex > index)
{
// The relative path index is less than the explicit path,
// so remove the explicit path.
indexesToRemove.Add(removalListCount++, existingIndex);
_lookupPaths[index] = resolvedDirectory;
}
else
{
// The explicit path index is less than the relative path
// index, so remove the relative path.
indexesToRemove.Add(removalListCount++, index);
}
}
else
{
// Change the relative path to the resolved path.
_lookupPaths[index] = resolvedDirectory;
}
}
else
{
// The directory couldn't be resolved so remove it from the
// lookup paths.
indexesToRemove.Add(removalListCount++, index);
}
}
// Now remove all the duplicates starting from the back of the collection.
// As each element is removed, elements that follow are moved up to occupy
// the emptied index.
for (int removeIndex = indexesToRemove.Count; removeIndex > 0; --removeIndex)
{
int indexToRemove = indexesToRemove[removeIndex - 1];
_lookupPaths.RemoveAt(indexToRemove);
}
}
/// <summary>
/// Gets an instance of a command enumerator.
/// </summary>
/// <returns>
/// An instance of this class as IEnumerator.
/// </returns>
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
return this;
}
/// <summary>
/// Gets an instance of a command enumerator.
/// </summary>
/// <returns>
/// An instance of this class as IEnumerator.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
/// <summary>
/// Moves the enumerator to the next command match.
/// </summary>
/// <returns>
/// true if there was another command that matches, false otherwise.
/// </returns>
public bool MoveNext()
{
bool result = false;
if (_justReset)
{
_justReset = false;
if (!_patternEnumerator.MoveNext())
{
s_tracer.TraceError("No patterns were specified");
return false;
}
if (!_lookupPathsEnumerator.MoveNext())
{
s_tracer.TraceError("No lookup paths were specified");
return false;
}
GetNewDirectoryResults(_patternEnumerator.Current, _lookupPathsEnumerator.Current);
}
do // while lookupPathsEnumerator is valid
{
do // while patternEnumerator is valid
{
// Try moving to the next path in the current results
if (!_currentDirectoryResultsEnumerator.MoveNext())
{
s_tracer.WriteLine("Current directory results are invalid");
// Since a path was not found in the current result,
// advance the pattern and try again
if (!_patternEnumerator.MoveNext())
{
s_tracer.WriteLine("Current patterns exhausted in current directory: {0}", _lookupPathsEnumerator.Current);
break;
}
// Get the results of the next pattern
GetNewDirectoryResults(_patternEnumerator.Current, _lookupPathsEnumerator.Current);
}
else
{
s_tracer.WriteLine("Next path found: {0}", _currentDirectoryResultsEnumerator.Current);
result = true;
break;
}
// Since we have reset the results, loop again to find the next result.
} while (true);
if (result)
{
break;
}
// Since the path was not found in the current results, and all patterns were exhausted,
// advance the path and continue
if (!_lookupPathsEnumerator.MoveNext())
{
s_tracer.WriteLine("All lookup paths exhausted, no more matches can be found");
break;
}
// Reset the pattern enumerator and get new results using the new lookup path
_patternEnumerator = _patterns.GetEnumerator();
if (!_patternEnumerator.MoveNext())
{
s_tracer.WriteLine("All patterns exhausted, no more matches can be found");
break;
}
GetNewDirectoryResults(_patternEnumerator.Current, _lookupPathsEnumerator.Current);
} while (true);
return result;
}
/// <summary>
/// Resets the enumerator to before the first command match.
/// </summary>
public void Reset()
{
_lookupPathsEnumerator = _lookupPaths.GetEnumerator();
_patternEnumerator = _patterns.GetEnumerator();
_currentDirectoryResults = Utils.EmptyArray<string>();
_currentDirectoryResultsEnumerator = _currentDirectoryResults.GetEnumerator();
_justReset = true;
}
/// <summary>
/// Gets the path to the current command match.
/// </summary>
/// <value></value>
/// <exception cref="InvalidOperationException">
/// The enumerator is positioned before the first element of
/// the collection or after the last element.
/// </exception>
string IEnumerator<string>.Current
{
get
{
if (_currentDirectoryResults == null)
{
throw PSTraceSource.NewInvalidOperationException();
}
return _currentDirectoryResultsEnumerator.Current;
}
}
object IEnumerator.Current
{
get
{
return ((IEnumerator<string>)this).Current;
}
}
/// <summary>
/// Required by the IEnumerator generic interface.
/// Resets the searcher.
/// </summary>
public void Dispose()
{
Reset();
GC.SuppressFinalize(this);
}
#region private members
/// <summary>
/// Gets the matching files in the specified directories and resets
/// the currentDirectoryResultsEnumerator to this new set of results.
/// </summary>
/// <param name="pattern">
/// The pattern used to find the matching files in the specified directory.
/// </param>
/// <param name="directory">
/// The path to the directory to find the files in.
/// </param>
private void GetNewDirectoryResults(string pattern, string directory)
{
IEnumerable<string> result = null;
try
{
CommandDiscovery.discoveryTracer.WriteLine("Looking for {0} in {1}", pattern, directory);
// Get the matching files in the directory
if (Directory.Exists(directory))
{
// Win8 bug 92113: Directory.GetFiles() regressed in NET4
// Directory.GetFiles(directory, ".") used to return null with CLR 2.
// but with CLR4 it started acting like "*". This is a appcompat bug in CLR4
// but they cannot fix it as CLR4 is already RTMd by the time this was reported.
// If they revert it, it will become a CLR4 appcompat issue. So, using the workaround
// to forcefully use null if pattern is "."
if (pattern.Length != 1 || pattern[0] != '.')
{
if (_useFuzzyMatch)
{
var files = new List<string>();
var matchingFiles = Directory.EnumerateFiles(directory);
foreach (string file in matchingFiles)
{
if (FuzzyMatcher.IsFuzzyMatch(Path.GetFileName(file), pattern))
{
files.Add(file);
}
}
result = _postProcessEnumeratedFiles != null
? _postProcessEnumeratedFiles(files.ToArray())
: files;
}
else
{
var matchingFiles = Directory.EnumerateFiles(directory, pattern);
result = _postProcessEnumeratedFiles != null
? _postProcessEnumeratedFiles(matchingFiles.ToArray())
: matchingFiles;
}
}
}
}
catch (ArgumentException)
{
// The pattern contained illegal file system characters
}
catch (IOException)
{
// A directory specified in the lookup path was not
// accessible
}
catch (UnauthorizedAccessException)
{
// A directory specified in the lookup path was not
// accessible
}
catch (NotSupportedException)
{
// A directory specified in the lookup path was not
// accessible
}
_currentDirectoryResults = result ?? Utils.EmptyArray<string>();
_currentDirectoryResultsEnumerator = _currentDirectoryResults.GetEnumerator();
}
private IEnumerable<string> CheckAgainstAcceptableCommandNames(string[] fileNames)
{
var baseNames = fileNames.Select(Path.GetFileName).ToArray();
// Result must be ordered by PATHEXT order of precedence.
// acceptableCommandNames is in this order, so
// Porting note: allow files with executable bit on non-Windows platforms
Collection<string> result = null;
if (baseNames.Length > 0)
{
foreach (var name in _acceptableCommandNames)
{
for (int i = 0; i < baseNames.Length; i++)
{
if (name.Equals(baseNames[i], StringComparison.OrdinalIgnoreCase)
|| (!Platform.IsWindows && Platform.NonWindowsIsExecutable(name)))
{
if (result == null)
result = new Collection<string>();
result.Add(fileNames[i]);
break;
}
}
}
}
return result;
}
private IEnumerable<string> JustCheckExtensions(string[] fileNames)
{
// Warning: pretty duplicated code
// Result must be ordered by PATHEXT order of precedence.
// Porting note: allow files with executable bit on non-Windows platforms
Collection<string> result = null;
foreach (var allowedExt in _orderedPathExt)
{
foreach (var fileName in fileNames)
{
if (fileName.EndsWith(allowedExt, StringComparison.OrdinalIgnoreCase)
|| (!Platform.IsWindows && Platform.NonWindowsIsExecutable(fileName)))
{
if (result == null)
result = new Collection<string>();
result.Add(fileName);
}
}
}
return result;
}
/// <summary>
/// The directory paths in which to look for commands.
/// This is derived from the PATH environment variable.
/// </summary>
private LookupPathCollection _lookupPaths;
/// <summary>
/// The enumerator for the lookup paths.
/// </summary>
private IEnumerator<string> _lookupPathsEnumerator;
/// <summary>
/// The list of results matching the pattern in the current
/// path lookup directory. Resets to null.
/// </summary>
private IEnumerable<string> _currentDirectoryResults;
/// <summary>
/// The enumerator for the list of results.
/// </summary>
private IEnumerator<string> _currentDirectoryResultsEnumerator;
/// <summary>
/// The command name to search for.
/// </summary>
private IEnumerable<string> _patterns;
/// <summary>
/// The enumerator for the patterns.
/// </summary>
private IEnumerator<string> _patternEnumerator;
/// <summary>
/// A reference to the execution context for this runspace.
/// </summary>
private ExecutionContext _context;
/// <summary>
/// When reset is called, this gets set to true. Once MoveNext
/// is called, this gets set to false.
/// </summary>
private bool _justReset;
/// <summary>
/// If not null, called with the enumerated files for further processing.
/// </summary>
private Func<string[], IEnumerable<string>> _postProcessEnumeratedFiles;
private string[] _orderedPathExt;
private Collection<string> _acceptableCommandNames;
private bool _useFuzzyMatch = false;
#endregion private members
}
}
| |
// =============================================================
// BytesRoad.NetSuit : A free network library for .NET platform
// =============================================================
//
// Copyright (C) 2004-2005 BytesRoad Software
//
// Project Info: http://www.bytesroad.com/NetSuit/
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ==========================================================================
// Changed by: NRPG
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using BytesRoad.Net.Sockets.Advanced;
namespace BytesRoad.Net.Sockets
{
internal enum AuthMethod
{
None,
UsernamePassword,
NoAcceptable
}
internal enum ATYP
{
IPv4 = 1,
DomName = 3,
IPv6 = 4
}
/// <summary>
/// Summary description for Socket_Socks5.
/// </summary>
internal class Socket_Socks5 : SocketBase
{
#region Async classes
class ReadVerifyReply_SO : AsyncResultBase
{
byte[] _phase1Data = new byte[5];
byte[] _reply = null;
internal ReadVerifyReply_SO(AsyncCallback cb, object state)
: base(cb, state)
{
}
internal byte[] Phase1Data
{
get { return _phase1Data; }
}
internal byte[] Reply
{
get { return _reply; }
set { _reply = value; }
}
}
class UsernamePassword_SO : AsyncResultBase
{
byte[] _reply = new byte[2];
internal UsernamePassword_SO(AsyncCallback cb, object state)
: base(cb, state)
{
}
internal byte[] Reply
{
get { return _reply; }
}
}
class DoAuthentication_SO : AsyncResultBase
{
internal DoAuthentication_SO(AsyncCallback cb, object state)
: base(cb, state)
{
}
}
class ReadWhole_SO : AsyncResultBase
{
byte[] _buffer;
int _offset;
int _size;
int _read = 0;
internal ReadWhole_SO(
byte[] buffer,
int offset,
int size,
AsyncCallback cb,
object state)
: base(cb, state)
{
_buffer = buffer;
_offset = offset;
_size = size;
}
internal byte[] Buffer
{
get { return _buffer; }
}
internal int Read
{
get { return _read; }
set { _read = value; }
}
internal int Size
{
get { return _size; }
}
internal int Offset
{
get { return _offset; }
}
}
class Negotiation_SO : AsyncResultBase
{
byte[] _reply = new byte[2];
bool _useCredentials;
internal Negotiation_SO(
bool useCredentials,
AsyncCallback cb,
object state) : base(cb, state)
{
_useCredentials = useCredentials;
}
internal byte[] Reply
{
get { return _reply; }
}
internal bool UseCredentials
{
get { return _useCredentials; }
set { _useCredentials = value; }
}
}
class Connect_SO : AsyncResultBase
{
EndPoint _remoteEndPoint;
int _readBytes = 0;
int _hostPort = -1;
string _hostName = null;
internal Connect_SO(
EndPoint remoteEndPoint,
string hostName,
int hostPort,
AsyncCallback cb,
object state) : base(cb, state)
{
_remoteEndPoint = remoteEndPoint;
_hostPort = hostPort;
_hostName = hostName;
}
internal int HostPort
{
get { return _hostPort; }
}
internal string HostName
{
get { return _hostName; }
}
internal EndPoint RemoteEndPoint
{
get { return _remoteEndPoint; }
set { _remoteEndPoint = value; }
}
internal int ReadBytes
{
get { return _readBytes; }
set { _readBytes = value; }
}
}
class Bind_SO : AsyncResultBase
{
Socket_Socks5 _baseSocket;
int _readBytes = 0;
IPAddress _proxyIP = null;
internal Bind_SO(
Socket_Socks5 baseSocket,
AsyncCallback cb,
object state) : base(cb, state)
{
_baseSocket = baseSocket;
}
internal Socket_Socks5 BaseSocket
{
get { return _baseSocket; }
}
internal int ReadBytes
{
get { return _readBytes; }
set { _readBytes = value; }
}
internal IPAddress ProxyIP
{
get { return _proxyIP; }
set { _proxyIP = value; }
}
}
class Accept_SO : AsyncResultBase
{
int _readBytes = 0;
internal Accept_SO(
AsyncCallback cb,
object state) : base(cb, state)
{
}
internal int ReadBytes
{
get { return _readBytes; }
set { _readBytes = value; }
}
}
#endregion
// policy switches
bool _resolveHostEnabled = true;
// remote host information
string _remoteHost = null;
int _remotePort = -1;
// End points
EndPoint _localEndPoint = null;
EndPoint _remoteEndPoint = null;
internal Socket_Socks5(
string proxyServer,
int proxyPort,
byte[] proxyUser,
byte[] proxyPassword)
: base(proxyServer, proxyPort, proxyUser, proxyPassword)
{
}
#region Attributes
override internal ProxyType ProxyType
{
get { return ProxyType.Socks5; }
}
override internal EndPoint LocalEndPoint
{
get { return _localEndPoint; }
}
override internal EndPoint RemoteEndPoint
{
get { return _remoteEndPoint; }
}
#endregion
#region Helper functions
IPEndPoint ExtractReplyAddr(byte[] reply)
{
byte atyp = reply[3];
if(atyp != (byte)ATYP.IPv4)
{
string msg = string.Format("Socks5: Address type in reply is unknown ({0}).", atyp);
throw new ArgumentException(msg, "reply");
}
int port = (reply[8] << 8) | reply[9];
long ip = (reply[7] << 24) |
(reply[6] << 16) |
(reply[5] << 8) |
(reply[4]);
ip &= 0xFFFFFFFF;
return new IPEndPoint(new IPAddress(ip), port);
}
byte[] PrepareCmd(EndPoint remoteEP, byte cmdVal)
{
if(null == remoteEP)
throw new ArgumentNullException("remoteEP", "The value cannot be null.");
byte[] cmd = new byte[10];
IPEndPoint ip = (IPEndPoint)remoteEP;
//------------------------------
// Compose header
//
cmd[0] = 5; // version
cmd[1] = cmdVal; // command
cmd[2] = 0; // reserved
cmd[3] = 1; // ATYPE - 1 for address as IP4
//------------------------------
// Store IP address
//
long ipAddr = ip.Address.Address;
cmd[4] = (byte)((ipAddr & 0x000000FF));
cmd[5] = (byte)((ipAddr & 0x0000FF00) >> 8);
cmd[6] = (byte)((ipAddr & 0x00FF0000) >> 16);
cmd[7] = (byte)((ipAddr & 0xFF000000) >> 24);
//------------------------------
// Store port
cmd[8] = (byte)((ip.Port & 0xFF00) >> 8);
cmd[9] = (byte)(ip.Port & 0xFF);
return cmd;
}
byte[] PrepareCmd(string remoteHost, int remotePort, byte cmdVal)
{
if(null == remoteHost)
throw new ArgumentNullException("remoteHost", "The value cannot be null.");
int hostLength = remoteHost.Length;
if(hostLength > 255)
throw new ArgumentException("Name of destination host cannot be more then 255 characters.", "remoteHost");
byte[] cmd = new byte[4 + 1 + hostLength + 2];
//----------------------------------
// Compose header
//
cmd[0] = 5; // version
cmd[1] = cmdVal; // command
cmd[2] = 0; // reserved
cmd[3] = 3; // domain name as address
//----------------------------------
// Store host name as address
//
cmd[4] = (byte)hostLength;
byte[] name = Encoding.Default.GetBytes(remoteHost);
Array.Copy(name, 0, cmd, 5, hostLength);
//----------------------------------
// Store the port
//
cmd[5 + hostLength] = (byte)((remotePort & 0xFF00) >> 8);
cmd[5 + hostLength + 1] = (byte)(remotePort & 0xFF);
return cmd;
}
byte[] PrepareBindCmd(Socket_Socks5 baseSocket)
{
if(null != baseSocket.RemoteEndPoint)
return PrepareCmd(baseSocket.RemoteEndPoint, 2);
else if(null != baseSocket._remoteHost)
return PrepareCmd(baseSocket._remoteHost, baseSocket._remotePort, 2);
else
throw new InvalidOperationException("Unable to prepare bind command because of insufficient information.");
}
byte[] PrepareConnectCmd(EndPoint remoteEP, string hostName, int hostPort)
{
if(null != remoteEP)
return PrepareCmd(remoteEP, 1);
else if(null != hostName)
return PrepareCmd(hostName, hostPort, 1);
else
throw new InvalidOperationException("Unable to prepare connect command because of insufficient information.");
}
#endregion
#region ReadWhole functions
void ReadWhole(byte[] buffer, int offset, int size)
{
int read = 0;
while(read < size)
read += NStream.Read(buffer, offset + read, size - read);
}
IAsyncResult BeginReadWhole(
byte[] buffer,
int offset,
int size,
AsyncCallback cb,
object state)
{
ReadWhole_SO stateObj = null;
stateObj = new ReadWhole_SO(buffer, offset, size, cb, state);
NStream.BeginRead(buffer, offset, size,
new AsyncCallback(ReadWhole_Read_End),
stateObj);
return stateObj;
}
void ReadWhole_Read_End(IAsyncResult ar)
{
ReadWhole_SO stateObj = (ReadWhole_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
stateObj.Read += NStream.EndRead(ar);
if(stateObj.Read < stateObj.Size)
{
NStream.BeginRead(
stateObj.Buffer,
stateObj.Offset + stateObj.Read,
stateObj.Size - stateObj.Read,
new AsyncCallback(ReadWhole_Read_End),
stateObj);
}
else
{
stateObj.SetCompleted();
}
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void EndReadWhole(IAsyncResult ar)
{
VerifyAsyncResult(ar, typeof(ReadWhole_SO));
HandleAsyncEnd(ar, false);
}
#endregion
#region Negotiation functions
#region Username/password negotiation
void Validate_UsernamePasswordReply(byte[] reply)
{
if(1 != reply[0])
{
string msg = string.Format("Socks5: Unknown reply format for username/password authentication ({0}).", reply[0]);
throw new ProtocolViolationException(msg);
}
if(0 != reply[1])
{
string msg = string.Format("Socks5: Username/password authentication failed ({0}).", reply[1]);
msg.ToString();
throw new SocketException(SockErrors.WSAECONNREFUSED);
}
}
byte[] Prepare_UsernamePasswordCmd()
{
if(null == _proxyUser)
throw new ArgumentNullException("ProxyUser", "The value cannot be null.");
int userLength = _proxyUser.Length;
if(userLength > 255)
throw new ArgumentException("Proxy user name cannot be more then 255 characters.", "ProxyUser");
int passwordLength = 0;
if(null != _proxyPassword)
{
passwordLength = _proxyPassword.Length;
if(passwordLength > 255)
throw new ArgumentException("Proxy password cannot be more then 255 characters.", "ProxyPassword");
}
byte[] cmd = new byte[1 + 1 + userLength + 1 + passwordLength];
//------------------------------
// Compose the header
cmd[0] = 1; // version
//------------------------------
// Store user name
cmd[1] = (byte)userLength;
Array.Copy(_proxyUser, 0, cmd, 2, userLength);
//------------------------------
// Store password if exists
cmd[2 + userLength] = (byte)passwordLength;
if(passwordLength > 0)
Array.Copy(_proxyPassword, 0, cmd, 3 + userLength, passwordLength);
return cmd;
}
void SubNegotiation_UsernamePassword()
{
//---------------------------------------
// Prepare authentication information
byte[] cmd = Prepare_UsernamePasswordCmd();
//---------------------------------------
// Send authentication information
NStream.Write(cmd, 0, cmd.Length);
//---------------------------------------
// Read the response
byte[] res = new byte[2];
ReadWhole(res, 0, 2);
//---------------------------------------
// Validate server response
Validate_UsernamePasswordReply(res);
}
IAsyncResult BeginSubNegotiation_UsernamePassword(
AsyncCallback cb,
object state)
{
//---------------------------------------
// Prepare authentication information
byte[] cmd = Prepare_UsernamePasswordCmd();
UsernamePassword_SO stateObj = new UsernamePassword_SO(cb, state);
//---------------------------------------
// Send authentication information
NStream.BeginWrite(
cmd,
0,
cmd.Length,
new AsyncCallback(SubUsernamePassword_Write_End),
stateObj);
return stateObj;
}
void SubUsernamePassword_Write_End(IAsyncResult ar)
{
UsernamePassword_SO stateObj = (UsernamePassword_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
NStream.EndWrite(ar);
//---------------------------------------
// Send authentication information
BeginReadWhole(
stateObj.Reply,
0,
2,
new AsyncCallback(SubUsernamePassword_Read_End),
stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void SubUsernamePassword_Read_End(IAsyncResult ar)
{
UsernamePassword_SO stateObj = (UsernamePassword_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
EndReadWhole(ar);
//---------------------------------------
// Validate server response
Validate_UsernamePasswordReply(stateObj.Reply);
}
catch(Exception e)
{
stateObj.Exception = e;
}
stateObj.SetCompleted();
}
void EndSubNegotiation_UsernamePassword(IAsyncResult ar)
{
VerifyAsyncResult(ar, typeof(UsernamePassword_SO));
HandleAsyncEnd(ar, true);
}
#endregion
AuthMethod ExtractAuthMethod(byte[] reply)
{
//------------------------------------
// Check the reply header
if(reply[0] != 5)
{
string msg = string.Format("Socks5 server returns reply with unknown version ({0}).", reply[0]);
throw new ProtocolViolationException(msg);
}
//------------------------------------
// Dispatch method chosen to particular
// sub negotiation or throw the
// exception.
//
byte method = reply[1];
if(0 == method) // no authentication required
{
return AuthMethod.None;
}
else if(2 == method) // Username/password
{
return AuthMethod.UsernamePassword;
}
else if(0xFF == method) // no acceptable methods
{
return AuthMethod.NoAcceptable;
}
else
{
// it is a violation of protocol
string msg = string.Format("Socks5 server requires not declared authentication method ({0}).", method);
throw new ProtocolViolationException(msg);
}
}
void DoAuthentication(AuthMethod method)
{
if(AuthMethod.None == method)
return;
if(AuthMethod.UsernamePassword == method)
{
SubNegotiation_UsernamePassword();
}
else if(AuthMethod.NoAcceptable == method)
{
// throw new AuthFailedException("No acceptable methods.");
throw new SocketException(SockErrors.WSAECONNREFUSED);
}
else
{
// throw invalid operation because
// method is unknown and execution should be stoped proir
// this point
throw new InvalidOperationException("Unknown authentication requested.");
}
}
IAsyncResult BeginDoAuthentication(
AuthMethod method,
AsyncCallback cb,
object state)
{
DoAuthentication_SO stateObj = new DoAuthentication_SO(cb, state);
if(AuthMethod.UsernamePassword == method)
{
BeginSubNegotiation_UsernamePassword(
new AsyncCallback(SubNegotiation_UsernamePassword_End),
stateObj);
}
else if(AuthMethod.NoAcceptable == method)
{
// throw new AuthFailedException("No acceptable methods.");
throw new SocketException(SockErrors.WSAECONNREFUSED);
}
else if(AuthMethod.None != method)
{
throw new InvalidOperationException("Unknown authentication requested.");
}
else
{
stateObj.SetCompleted();
}
return stateObj;
}
void SubNegotiation_UsernamePassword_End(IAsyncResult ar)
{
DoAuthentication_SO stateObj = (DoAuthentication_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
EndSubNegotiation_UsernamePassword(ar);
}
catch(Exception e)
{
stateObj.Exception = e;
}
stateObj.SetCompleted();
}
void EndDoAuthentication(IAsyncResult ar)
{
VerifyAsyncResult(ar, typeof(DoAuthentication_SO));
HandleAsyncEnd(ar, false);
}
byte[] PrepareNegotiationCmd(bool useCredentials)
{
byte[] cmd = null;
if(useCredentials)
{
cmd = new byte[4];
cmd[0] = 5; // version
cmd[1] = 2; // number of supported methods
cmd[2] = 0; // no authentication
cmd[3] = 2; // username/password
}
else
{
cmd = new byte[3];
cmd[0] = 5; // version
cmd[1] = 1; // number of supported methods
cmd[2] = 0; // no authentication
}
return cmd;
}
void Negotiate()
{
bool useCredentials = PreAuthenticate;
if(null == _proxyUser)
useCredentials = false;
AuthMethod authMethod;
while(true)
{
//----------------------------------------------
// Send negotiation request
byte[] cmd = PrepareNegotiationCmd(useCredentials);
NStream.Write(cmd, 0, cmd.Length);
//----------------------------------------------
// Read negotiation reply with supported methods
byte[] reply = new byte[2];
ReadWhole(reply, 0, 2);
//----------------------------------------------
// Extract demanded authentication method
authMethod = ExtractAuthMethod(reply);
if((AuthMethod.NoAcceptable == authMethod) &&
!useCredentials &&
(null != _proxyUser))
{
useCredentials = true;
continue;
}
break;
}
//-------------------------------------------
// Run appropriate authentication if required
DoAuthentication(authMethod);
}
IAsyncResult BeginNegotiate(AsyncCallback callback, object state)
{
bool useCredentials = PreAuthenticate;
if(null == _proxyUser)
useCredentials = false;
Negotiation_SO stateObj = new Negotiation_SO(
useCredentials,
callback,
state);
//-----------------------------------
// Send negotiation request
byte[] cmd = PrepareNegotiationCmd(stateObj.UseCredentials);
NStream.BeginWrite(
cmd,
0,
cmd.Length,
new AsyncCallback(Negotiate_Write_End),
stateObj);
return stateObj;
}
void Negotiate_Write_End(IAsyncResult ar)
{
Negotiation_SO stateObj = (Negotiation_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
NStream.EndWrite(ar);
//-----------------------------------
// Read negotiation reply with
// supported methods
//
BeginReadWhole(
stateObj.Reply,
0,
2,
new AsyncCallback(Negotiate_ReadWhole_End),
stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Negotiate_ReadWhole_End(IAsyncResult ar)
{
Negotiation_SO stateObj = (Negotiation_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
EndReadWhole(ar);
//----------------------------------------------
// Extract demanded authentication method
AuthMethod authMethod = ExtractAuthMethod(stateObj.Reply);
if((AuthMethod.NoAcceptable == authMethod) &&
!stateObj.UseCredentials &&
(null != _proxyUser))
{
stateObj.UseCredentials = true;
//-----------------------------------
// Send negotiation request
byte[] cmd = PrepareNegotiationCmd(stateObj.UseCredentials);
NStream.BeginWrite(
cmd,
0,
cmd.Length,
new AsyncCallback(Negotiate_Write_End),
stateObj);
}
else
{
//-----------------------------------
// Run appropriate authentication
// method
BeginDoAuthentication(
authMethod,
new AsyncCallback(Negotiate_DoAuth_End),
stateObj);
}
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Negotiate_DoAuth_End(IAsyncResult ar)
{
Negotiation_SO stateObj = (Negotiation_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
EndDoAuthentication(ar);
}
catch(Exception e)
{
stateObj.Exception = e;
}
stateObj.SetCompleted();
}
void EndNegotiate(IAsyncResult ar)
{
VerifyAsyncResult(ar, typeof(Negotiation_SO));
HandleAsyncEnd(ar, false);
}
#endregion
#region ReadVerifyReply functions
void CheckReplyVer(byte[] reply)
{
if(5 != reply[0])
{
string msg = string.Format("Socks5: Unknown format of reply ({0}).", reply[0]);
throw new ProtocolViolationException(msg);
}
}
void CheckReplyForError(byte[] reply)
{
byte rep = reply[1];
if(0 == rep)
return;
string msg;
if(1 == rep)
msg = "Socks5: General SOCKS server failure.";
else if(2 == rep)
msg = "Socks5: Connection not allowed by rule set.";
else if(3 == rep)
msg = "Socks5: Network unreachable.";
else if(4 == rep)
msg = "Socks5: Host unreachable.";
else if(5 == rep)
msg = "Socks5: Connection refused.";
else if(6 == rep)
msg = "Socks5: TTL expired.";
else if(7 == rep)
msg = "Socks5: Command not supported.";
else if(8 == rep)
msg = "Socks5: Address type not supported.";
else
msg = string.Format("Socks5: Reply code is unknown ({0}).", rep);
msg.ToString();
throw new SocketException(SockErrors.WSAECONNREFUSED);
// throw new ProxyErrorException(msg);
}
int GetAddrFieldLength(byte[] reply)
{
byte atyp = reply[3];
if(1 == atyp) // IP4 address?
return 4;
else if(3 == atyp) // domain name?
return 1 + reply[4];
else if(4 == atyp)
return 16;
else
{
string msg = string.Format("Socks5: Unknown address type in reply ({0}).", atyp);
throw new ProtocolViolationException(msg);
}
}
int VerifyReplyAndGetLeftBytes(byte[] reply)
{
//----------------------------------
// Check reply version
CheckReplyVer(reply);
//------------------------------------------
// Check for error condition
CheckReplyForError(reply);
//------------------------------------------
// Calculate number of bytes left to read:
// address length - 1(because one byte from
// address field was read in phase 1) + port
return GetAddrFieldLength(reply) - 1 + 2;
}
byte[] ReadVerifyReply()
{
//-----------------------------------
// Phase 1. Read 5 bytes
byte[] phase1Data = new byte[5];
ReadWhole(phase1Data, 0, 5);
int leftBytes = VerifyReplyAndGetLeftBytes(phase1Data);
//-----------------------------------
// Phase 2. Read left data
byte[] reply = new byte[5 + leftBytes];
phase1Data.CopyTo(reply, 0);
ReadWhole(reply, 5, leftBytes);
return reply;
}
IAsyncResult BeginReadVerifyReply(AsyncCallback cb, object state)
{
ReadVerifyReply_SO stateObj = new ReadVerifyReply_SO(cb, state);
BeginReadWhole(stateObj.Phase1Data, 0, 5,
new AsyncCallback(Phase1_End), stateObj);
return stateObj;
}
void Phase1_End(IAsyncResult ar)
{
ReadVerifyReply_SO stateObj = (ReadVerifyReply_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
EndReadWhole(ar);
int leftBytes = VerifyReplyAndGetLeftBytes(stateObj.Phase1Data);
//-----------------------------------
// Phase 2. Read left data
stateObj.Reply = new byte[5 + leftBytes];
stateObj.Phase1Data.CopyTo(stateObj.Reply, 0);
BeginReadWhole(stateObj.Reply, 5, leftBytes,
new AsyncCallback(Phase2_End), stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Phase2_End(IAsyncResult ar)
{
ReadVerifyReply_SO stateObj = (ReadVerifyReply_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
EndReadWhole(ar);
}
catch(Exception e)
{
stateObj.Exception = e;
}
stateObj.SetCompleted();
}
byte[] EndReadVerifyReply(IAsyncResult ar)
{
VerifyAsyncResult(ar, typeof(ReadVerifyReply_SO));
HandleAsyncEnd(ar, false);
return ((ReadVerifyReply_SO)ar).Reply;
}
#endregion
#region Accept functions (overriden)
override internal SocketBase Accept()
{
CheckDisposed();
SetProgress(true);
try
{
byte[] reply = ReadVerifyReply();
_remoteEndPoint = ExtractReplyAddr(reply);
}
finally
{
SetProgress(false);
}
return this;
}
override internal IAsyncResult BeginAccept(
AsyncCallback callback,
object state)
{
CheckDisposed();
Accept_SO stateObj = null;
SetProgress(true);
try
{
stateObj = new Accept_SO(callback, state);
//------------------------------------
// Read the second response from proxy server.
//
BeginReadVerifyReply(new AsyncCallback(Accept_Read_End), stateObj);
}
catch
{
SetProgress(false);
throw;
}
return stateObj;
}
void Accept_Read_End(IAsyncResult ar)
{
Accept_SO stateObj = (Accept_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
byte[] reply = EndReadVerifyReply(ar);
_remoteEndPoint = ExtractReplyAddr(reply);
}
catch(Exception e)
{
stateObj.Exception = e;
}
stateObj.SetCompleted();
}
override internal SocketBase EndAccept(IAsyncResult asyncResult)
{
VerifyAsyncResult(asyncResult, typeof(Accept_SO), "EndAccept");
HandleAsyncEnd(asyncResult, true);
return this;
}
#endregion
#region Connect functions (overriden)
override internal void Connect(string hostName, int hostPort)
{
if(null == hostName)
throw new ArgumentNullException("hostName", "The value cannot be null.");
if(hostPort < IPEndPoint.MinPort || hostPort > IPEndPoint.MaxPort)
throw new ArgumentOutOfRangeException("hostPort", "Value, specified for the port is out of the valid range.");
Connect(null, hostName, hostPort);
}
override internal void Connect(EndPoint remoteEP)
{
if(null == remoteEP)
throw new ArgumentNullException("remoteEP", "The value cannot be null.");
Connect(remoteEP, null, -1);
}
void Connect(EndPoint remoteEP, string hostName, int hostPort)
{
CheckDisposed();
SetProgress(true);
try
{
if(null == remoteEP)
{
if(_resolveHostEnabled)
{
IPHostEntry host = GetHostByName(hostName);
if(null != host)
remoteEP = ConstructEndPoint(host, hostPort);
}
if((null == hostName) && (null == remoteEP))
throw new ArgumentNullException("hostName", "The value cannot be null.");
}
//------------------------------------
// Get end point for the proxy server
//
IPHostEntry proxyEntry = GetHostByName(_proxyServer);
if(null == proxyEntry)
throw new SocketException(SockErrors.WSAHOST_NOT_FOUND);
// throw new HostNotFoundException("Unable to resolve proxy name.");
IPEndPoint proxyEndPoint = ConstructEndPoint(proxyEntry, _proxyPort);
//------------------------------------------
// Connect to proxy server
//
_socket.Connect(proxyEndPoint);
//------------------------------------------
// Negotiate user
Negotiate();
//------------------------------------------
// Send CONNECT command
//
byte[] cmd = PrepareConnectCmd(remoteEP, hostName, hostPort);
NStream.Write(cmd, 0, cmd.Length);
//------------------------------------------
// Read and verify reply from proxy the server.
//
byte[] reply = ReadVerifyReply();
_localEndPoint = ExtractReplyAddr(reply);
_remoteEndPoint = remoteEP;
//---------------------------------------
// I we unable to resolve remote host then
// store information - it will required
// later for BIND command.
if(null == remoteEP)
{
_remotePort = hostPort;
_remoteHost = hostName;
}
}
finally
{
SetProgress(false);
}
}
override internal IAsyncResult BeginConnect(
string hostName,
int hostPort,
AsyncCallback callback,
object state)
{
CheckDisposed();
if(null == hostName)
throw new ArgumentNullException("hostName", "The value cannot be null.");
if(hostPort < IPEndPoint.MinPort || hostPort > IPEndPoint.MaxPort)
throw new ArgumentOutOfRangeException("hostPort", "Value, specified for the port is out of the valid range.");
Connect_SO stateObj = null;
SetProgress(true);
try
{
stateObj = new Connect_SO(null, hostName, hostPort, callback, state);
if(_resolveHostEnabled)
{
//--------------------------------------
// Trying to resolve host name locally
BeginGetHostByName(
hostName,
new AsyncCallback(Connect_GetHost_Host_End),
stateObj);
}
else
{
//-------------------------------------
// Get end point for the proxy server
//
BeginGetHostByName(
_proxyServer,
new AsyncCallback(Connect_GetHost_Proxy_End),
stateObj);
}
}
catch(Exception e)
{
SetProgress(false);
throw e;
}
return stateObj;
}
void Connect_GetHost_Host_End(IAsyncResult ar)
{
Connect_SO stateObj = (Connect_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
IPHostEntry host = EndGetHostByName(ar);
if(null != host)
stateObj.RemoteEndPoint = ConstructEndPoint(host, stateObj.HostPort);
//------------------------------------
// Get end point for the proxy server
//
BeginGetHostByName(
_proxyServer,
new AsyncCallback(Connect_GetHost_Proxy_End),
stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
override internal IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
{
CheckDisposed();
if(null == remoteEP)
throw new ArgumentNullException("remoteEP", "The value cannot be null.");
Connect_SO stateObj = null;
SetProgress(true);
try
{
stateObj = new Connect_SO(remoteEP, null, -1, callback, state);
//------------------------------------
// Get end point for the proxy server
//
BeginGetHostByName(
_proxyServer,
new AsyncCallback(Connect_GetHost_Proxy_End),
stateObj);
}
catch(Exception ex)
{
SetProgress(false);
throw ex;
}
return stateObj;
}
void Connect_GetHost_Proxy_End(IAsyncResult ar)
{
Connect_SO stateObj = (Connect_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
IPHostEntry host = EndGetHostByName(ar);
if(null == host)
throw new SocketException(SockErrors.WSAHOST_NOT_FOUND);
// throw new HostNotFoundException("Unable to resolve proxy name.");
IPEndPoint proxyEndPoint = ConstructEndPoint(host, _proxyPort);
//------------------------------------
// Connect to proxy server
//
_socket.BeginConnect(
proxyEndPoint,
new AsyncCallback(Connect_Connect_End),
stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Connect_Connect_End(IAsyncResult ar)
{
Connect_SO stateObj = (Connect_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
_socket.EndConnect(ar);
//------------------------------------------
// Negotiate user
BeginNegotiate(new AsyncCallback(Connect_Negotiate_End), stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Connect_Negotiate_End(IAsyncResult ar)
{
Connect_SO stateObj = (Connect_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
EndNegotiate(ar);
//------------------------------------
// Send CONNECT command
//
byte[] cmd = PrepareConnectCmd(
stateObj.RemoteEndPoint,
stateObj.HostName,
stateObj.HostPort);
NStream.BeginWrite(
cmd,
0,
cmd.Length,
new AsyncCallback(Connect_Write_End),
stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Connect_Write_End(IAsyncResult ar)
{
Connect_SO stateObj = (Connect_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
NStream.EndWrite(ar);
//------------------------------------
// Read the response from proxy server.
BeginReadVerifyReply(new AsyncCallback(Connect_Read_End), stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Connect_Read_End(IAsyncResult ar)
{
Connect_SO stateObj = (Connect_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
byte[] reply = EndReadVerifyReply(ar);
_localEndPoint = ExtractReplyAddr(reply);
_remoteEndPoint = stateObj.RemoteEndPoint;
//---------------------------------------
// I we unable to resolve remote host then
// store information - it will required
// later for BIND command.
if(null == stateObj.RemoteEndPoint)
{
_remotePort = stateObj.HostPort;
_remoteHost = stateObj.HostName;
}
}
catch(Exception e)
{
stateObj.Exception = e;
}
stateObj.SetCompleted();
}
override internal void EndConnect(IAsyncResult asyncResult)
{
VerifyAsyncResult(asyncResult, typeof(Connect_SO), "EndConnect");
HandleAsyncEnd(asyncResult, true);
}
#endregion
#region Bind functions (overriden)
override internal void Bind(SocketBase socket)
{
CheckDisposed();
SetProgress(true);
try
{
//-----------------------------------------
// Get end point for the proxy server
//
IPHostEntry host = GetHostByName(_proxyServer);
if(host == null)
throw new SocketException(SockErrors.WSAHOST_NOT_FOUND);
// throw new HostNotFoundException("Unable to resolve proxy host name.");
IPEndPoint proxyEndPoint = ConstructEndPoint(host, _proxyPort);
//-----------------------------------------
// Connect to proxy server
//
_socket.Connect(proxyEndPoint);
//------------------------------------------
// Negotiate user
Negotiate();
//-----------------------------------------
// Send BIND command
//
byte[] cmd = PrepareBindCmd((Socket_Socks5)socket);
NStream.Write(cmd, 0, cmd.Length);
//-----------------------------------------
// Read the reply from the proxy server.
byte[] reply = ReadVerifyReply();
_localEndPoint = ExtractReplyAddr(reply);
// remote end point is unknown till accept
_remoteEndPoint = null;
}
finally
{
SetProgress(false);
}
}
override internal IAsyncResult BeginBind(
SocketBase baseSocket,
AsyncCallback callback,
object state)
{
CheckDisposed();
if(null == baseSocket)
throw new ArgumentNullException("baseSocket", "The value cannot be null");
Bind_SO stateObj = null;
SetProgress(true);
try
{
stateObj = new Bind_SO((Socket_Socks5)baseSocket, callback, state);
//------------------------------------
// Get end point for the proxy server
//
BeginGetHostByName(
_proxyServer,
new AsyncCallback(Bind_GetHost_End),
stateObj);
}
catch(Exception ex)
{
SetProgress(false);
throw ex;
}
return stateObj;
}
void Bind_GetHost_End(IAsyncResult ar)
{
Bind_SO stateObj = (Bind_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
IPHostEntry host = EndGetHostByName(ar);
if(host == null)
throw new SocketException(SockErrors.WSAHOST_NOT_FOUND);
// throw new HostNotFoundException("Unable to resolve proxy host name.");
IPEndPoint proxyEndPoint = ConstructEndPoint(host, _proxyPort);
stateObj.ProxyIP = proxyEndPoint.Address;
//------------------------------------
// Connect to proxy server
//
_socket.BeginConnect(
proxyEndPoint,
new AsyncCallback(Bind_Connect_End),
stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Bind_Connect_End(IAsyncResult ar)
{
Bind_SO stateObj = (Bind_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
_socket.EndConnect(ar);
//------------------------------------------
// Negotiate user
BeginNegotiate(
new AsyncCallback(Bind_Negotiate_End),
stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Bind_Negotiate_End(IAsyncResult ar)
{
Bind_SO stateObj = (Bind_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
EndNegotiate(ar);
//------------------------------------
// Send BIND command
//
byte[] cmd = PrepareBindCmd(stateObj.BaseSocket);
NStream.BeginWrite(
cmd,
0,
cmd.Length,
new AsyncCallback(Bind_Write_End),
stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Bind_Write_End(IAsyncResult ar)
{
Bind_SO stateObj = (Bind_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
NStream.EndWrite(ar);
//------------------------------------
// Read the response from proxy server.
BeginReadVerifyReply(new AsyncCallback(Bind_Read_End), stateObj);
}
catch(Exception e)
{
stateObj.Exception = e;
stateObj.SetCompleted();
}
}
void Bind_Read_End(IAsyncResult ar)
{
Bind_SO stateObj = (Bind_SO)ar.AsyncState;
try
{
stateObj.UpdateContext();
byte[] reply = EndReadVerifyReply(ar);
_localEndPoint = ExtractReplyAddr(reply);
_remoteEndPoint = null;
}
catch(Exception e)
{
stateObj.Exception = e;
}
stateObj.SetCompleted();
}
override internal void EndBind(IAsyncResult asyncResult)
{
VerifyAsyncResult(asyncResult, typeof(Bind_SO), "EndBind");
HandleAsyncEnd(asyncResult, true);
}
#endregion
#region Listen functions (overriden)
override internal void Listen(int backlog)
{
CheckDisposed();
if(null == _localEndPoint)
throw new ArgumentException("Attempt to listen on socket which has not been bound with Bind.");
}
#endregion
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="Recurrence.RelativeYearlyPattern.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the Recurrence.RelativeYearlyPattern class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Text;
/// <content>
/// Contains nested type Recurrence.RelativeYearlyPattern.
/// </content>
public abstract partial class Recurrence
{
/// <summary>
/// Represents a recurrence pattern where each occurrence happens on a relative day every year.
/// </summary>
public sealed class RelativeYearlyPattern : Recurrence
{
private DayOfTheWeek? dayOfTheWeek;
private DayOfTheWeekIndex? dayOfTheWeekIndex;
private Month? month;
/// <summary>
/// Gets the name of the XML element.
/// </summary>
/// <value>The name of the XML element.</value>
internal override string XmlElementName
{
get { return XmlElementNames.RelativeYearlyRecurrence; }
}
/// <summary>
/// Write properties to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void InternalWritePropertiesToXml(EwsServiceXmlWriter writer)
{
base.InternalWritePropertiesToXml(writer);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.DaysOfWeek,
this.DayOfTheWeek);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.DayOfWeekIndex,
this.DayOfTheWeekIndex);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.Month,
this.Month);
}
/// <summary>
/// Patterns to json.
/// </summary>
/// <param name="service">The service.</param>
/// <returns></returns>
internal override JsonObject PatternToJson(ExchangeService service)
{
JsonObject jsonPattern = new JsonObject();
jsonPattern.AddTypeParameter(this.XmlElementName);
jsonPattern.Add(XmlElementNames.DaysOfWeek, this.DayOfTheWeek);
jsonPattern.Add(XmlElementNames.DayOfWeekIndex, this.DayOfTheWeekIndex);
jsonPattern.Add(XmlElementNames.Month, this.Month);
return jsonPattern;
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
if (base.TryReadElementFromXml(reader))
{
return true;
}
else
{
switch (reader.LocalName)
{
case XmlElementNames.DaysOfWeek:
this.dayOfTheWeek = reader.ReadElementValue<DayOfTheWeek>();
return true;
case XmlElementNames.DayOfWeekIndex:
this.dayOfTheWeekIndex = reader.ReadElementValue<DayOfTheWeekIndex>();
return true;
case XmlElementNames.Month:
this.month = reader.ReadElementValue<Month>();
return true;
default:
return false;
}
}
}
/// <summary>
/// Loads from json.
/// </summary>
/// <param name="jsonProperty">The json property.</param>
/// <param name="service">The service.</param>
internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service)
{
base.LoadFromJson(jsonProperty, service);
foreach (string key in jsonProperty.Keys)
{
switch (key)
{
case XmlElementNames.DaysOfWeek:
this.dayOfTheWeek = jsonProperty.ReadEnumValue<DayOfTheWeek>(key);
break;
case XmlElementNames.DayOfWeekIndex:
this.dayOfTheWeekIndex = jsonProperty.ReadEnumValue<DayOfTheWeekIndex>(key);
break;
case XmlElementNames.Month:
this.month = jsonProperty.ReadEnumValue<Month>(key);
break;
default:
break;
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="RelativeYearlyPattern"/> class.
/// </summary>
public RelativeYearlyPattern()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RelativeYearlyPattern"/> class.
/// </summary>
/// <param name="startDate">The date and time when the recurrence starts.</param>
/// <param name="month">The month of the year each occurrence happens.</param>
/// <param name="dayOfTheWeek">The day of the week each occurrence happens.</param>
/// <param name="dayOfTheWeekIndex">The relative position of the day within the month.</param>
public RelativeYearlyPattern(
DateTime startDate,
Month month,
DayOfTheWeek dayOfTheWeek,
DayOfTheWeekIndex dayOfTheWeekIndex)
: base(startDate)
{
this.Month = month;
this.DayOfTheWeek = dayOfTheWeek;
this.DayOfTheWeekIndex = dayOfTheWeekIndex;
}
/// <summary>
/// Validates this instance.
/// </summary>
internal override void InternalValidate()
{
base.InternalValidate();
if (!this.dayOfTheWeekIndex.HasValue)
{
throw new ServiceValidationException(Strings.DayOfWeekIndexMustBeSpecifiedForRecurrencePattern);
}
if (!this.dayOfTheWeek.HasValue)
{
throw new ServiceValidationException(Strings.DayOfTheWeekMustBeSpecifiedForRecurrencePattern);
}
if (!this.month.HasValue)
{
throw new ServiceValidationException(Strings.MonthMustBeSpecifiedForRecurrencePattern);
}
}
/// <summary>
/// Gets or sets the relative position of the day specified in DayOfTheWeek within the month.
/// </summary>
public DayOfTheWeekIndex DayOfTheWeekIndex
{
get { return this.GetFieldValueOrThrowIfNull<DayOfTheWeekIndex>(this.dayOfTheWeekIndex, "DayOfTheWeekIndex"); }
set { this.SetFieldValue<DayOfTheWeekIndex?>(ref this.dayOfTheWeekIndex, value); }
}
/// <summary>
/// Gets or sets the day of the week when each occurrence happens.
/// </summary>
public DayOfTheWeek DayOfTheWeek
{
get { return this.GetFieldValueOrThrowIfNull<DayOfTheWeek>(this.dayOfTheWeek, "DayOfTheWeek"); }
set { this.SetFieldValue<DayOfTheWeek?>(ref this.dayOfTheWeek, value); }
}
/// <summary>
/// Gets or sets the month of the year when each occurrence happens.
/// </summary>
public Month Month
{
get { return this.GetFieldValueOrThrowIfNull<Month>(this.month, "Month"); }
set { this.SetFieldValue<Month?>(ref this.month, 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.
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace System.Management
{
/// <summary>
/// <para>Describes the possible text formats that can be used with <see cref='System.Management.ManagementBaseObject.GetText'/>.</para>
/// </summary>
public enum TextFormat
{
/// <summary>
/// Managed Object Format
/// </summary>
Mof = 0,
/// <summary>
/// XML DTD that corresponds to CIM DTD version 2.0
/// </summary>
CimDtd20 = 1,
/// <summary>
/// XML WMI DTD that corresponds to CIM DTD version 2.0.
/// Using this value enables a few WMI-specific extensions, like embedded objects.
/// </summary>
WmiDtd20 = 2
};
/// <summary>
/// <para>Describes the possible CIM types for properties, qualifiers, or method parameters.</para>
/// </summary>
public enum CimType
{
/// <summary>
/// <para>Invalid Type</para>
/// </summary>
None = 0,
/// <summary>
/// <para>A signed 8-bit integer.</para>
/// </summary>
SInt8 = 16,
/// <summary>
/// <para>An unsigned 8-bit integer.</para>
/// </summary>
UInt8 = 17,
/// <summary>
/// <para>A signed 16-bit integer.</para>
/// </summary>
SInt16 = 2,
/// <summary>
/// <para>An unsigned 16-bit integer.</para>
/// </summary>
UInt16 = 18,
/// <summary>
/// <para>A signed 32-bit integer.</para>
/// </summary>
SInt32 = 3,
/// <summary>
/// <para>An unsigned 32-bit integer.</para>
/// </summary>
UInt32 = 19,
/// <summary>
/// <para>A signed 64-bit integer.</para>
/// </summary>
SInt64 = 20,
/// <summary>
/// <para>An unsigned 64-bit integer.</para>
/// </summary>
UInt64 = 21,
/// <summary>
/// <para>A floating-point 32-bit number.</para>
/// </summary>
Real32 = 4,
/// <summary>
/// <para>A floating point 64-bit number.</para>
/// </summary>
Real64 = 5,
/// <summary>
/// <para> A boolean.</para>
/// </summary>
Boolean = 11,
/// <summary>
/// <para>A string.</para>
/// </summary>
String = 8,
/// <summary>
/// <para> A date or time value, represented in a string in DMTF
/// date/time format: yyyymmddHHMMSS.mmmmmmsUUU</para>
/// <para>where:</para>
/// <para>yyyymmdd - is the date in year/month/day</para>
/// <para>HHMMSS - is the time in hours/minutes/seconds</para>
/// <para>mmmmmm - is the number of microseconds in 6 digits</para>
/// <para>sUUU - is a sign (+ or -) and a 3-digit UTC offset</para>
/// </summary>
DateTime = 101,
/// <summary>
/// <para>A reference to another object. This is represented by a
/// string containing the path to the referenced object</para>
/// </summary>
Reference = 102,
/// <summary>
/// <para> A 16-bit character.</para>
/// </summary>
Char16 = 103,
/// <summary>
/// <para>An embedded object.</para>
/// <para>Note that embedded objects differ from references in that the embedded object
/// doesn't have a path and its lifetime is identical to the lifetime of the
/// containing object.</para>
/// </summary>
Object = 13,
};
/// <summary>
/// <para>Describes the object comparison modes that can be used with <see cref='System.Management.ManagementBaseObject.CompareTo'/>.
/// Note that these values may be combined.</para>
/// </summary>
[Flags]
public enum ComparisonSettings
{
/// <summary>
/// <para>A mode that compares all elements of the compared objects.</para>
/// </summary>
IncludeAll = 0,
/// <summary>
/// <para>A mode that compares the objects, ignoring qualifiers.</para>
/// </summary>
IgnoreQualifiers = 0x1,
/// <summary>
/// <para> A mode that ignores the source of the objects, namely the server
/// and the namespace they came from, in comparison to other objects.</para>
/// </summary>
IgnoreObjectSource = 0x2,
/// <summary>
/// <para> A mode that ignores the default values of properties.
/// This value is only meaningful when comparing classes.</para>
/// </summary>
IgnoreDefaultValues = 0x4,
/// <summary>
/// <para>A mode that assumes that the objects being compared are instances of
/// the same class. Consequently, this value causes comparison
/// of instance-related information only. Use this flag to optimize
/// performance. If the objects are not of the same class, the results are undefined.</para>
/// </summary>
IgnoreClass = 0x8,
/// <summary>
/// <para> A mode that compares string values in a case-insensitive
/// manner. This applies to strings and to qualifier values. Property and qualifier
/// names are always compared in a case-insensitive manner whether this flag is
/// specified or not.</para>
/// </summary>
IgnoreCase = 0x10,
/// <summary>
/// <para>A mode that ignores qualifier flavors. This flag still takes
/// qualifier values into account, but ignores flavor distinctions such as
/// propagation rules and override restrictions.</para>
/// </summary>
IgnoreFlavor = 0x20
};
internal enum QualifierType
{
ObjectQualifier,
PropertyQualifier,
MethodQualifier
}
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Contains the basic elements of a management
/// object. It serves as a base class to more specific management object classes.</para>
/// </summary>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
[ToolboxItem(false)]
public class ManagementBaseObject : Component, ICloneable, ISerializable
{
// This field holds onto a WbemContext for the lifetime of the appdomain. This should
// prevent Fastprox.dll from unloading prematurely.
// Since this is fixed in WinXP, we only hold onto a WbemContext if we are NOT running XP or later.
#pragma warning disable CA1823
#pragma warning disable CS0169 // Kept for possible reflection, comment above for history
private static readonly WbemContext lockOnFastProx; // RemovedDuringPort System.Management.Instrumentation.WMICapabilities.IsWindowsXPOrHigher()?null:new WbemContext();
#pragma warning restore CS0169
#pragma warning restore CA1823
//
// The wbemObject is changed from a field to a property. This is to avoid major code churn and simplify the solution to
// the problem where the Initialize call actually binds to the object. This occured even in cases like Get() whereby we
// ended up getting the object twice. Any direct usage of this property will cause a call to Initialize ( true ) to be made
// (if not already done) indicating that we wish to bind to the underlying WMI object.
//
// See changes to Initialize
//
internal IWbemClassObjectFreeThreaded wbemObject
{
get
{
if (_wbemObject == null)
{
Initialize(true);
}
return _wbemObject;
}
set
{
_wbemObject = value;
}
}
internal IWbemClassObjectFreeThreaded _wbemObject;
private PropertyDataCollection properties;
private PropertyDataCollection systemProperties;
private QualifierDataCollection qualifiers;
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementBaseObject'/> class that is serializable.</para>
/// </summary>
/// <param name='info'>The <see cref='System.Runtime.Serialization.SerializationInfo'/> to populate with data.</param>
/// <param name='context'>The destination (see <see cref='System.Runtime.Serialization.StreamingContext'/> ) for this serialization.</param>
protected ManagementBaseObject(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public new void Dispose()
{
if (_wbemObject != null)
{
_wbemObject.Dispose();
_wbemObject = null;
}
base.Dispose();
GC.SuppressFinalize(this);
}
/// <summary>
/// <para>Provides the internal WMI object represented by a ManagementObject.</para>
/// <para>See remarks with regard to usage.</para>
/// </summary>
/// <param name='managementObject'>The <see cref='System.Management.ManagementBaseObject'/> that references the requested WMI object. </param>
/// <returns>
/// <para>An <see cref='System.IntPtr'/> representing the internal WMI object.</para>
/// </returns>
/// <remarks>
/// <para>This operator is used internally by instrumentation code. It is not intended
/// for direct use by regular client or instrumented applications.</para>
/// </remarks>
public static explicit operator IntPtr(ManagementBaseObject managementObject)
{
if (null == managementObject)
return IntPtr.Zero;
return (IntPtr)managementObject.wbemObject;
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
// Factory
/// <summary>
/// Factory for various types of base object
/// </summary>
/// <param name="wbemObject"> IWbemClassObject </param>
/// <param name="scope"> The scope</param>
internal static ManagementBaseObject GetBaseObject(
IWbemClassObjectFreeThreaded wbemObject,
ManagementScope scope)
{
ManagementBaseObject newObject = null;
if (_IsClass(wbemObject))
newObject = ManagementClass.GetManagementClass(wbemObject, scope);
else
newObject = ManagementObject.GetManagementObject(wbemObject, scope);
return newObject;
}
//Constructor
internal ManagementBaseObject(IWbemClassObjectFreeThreaded wbemObject)
{
this.wbemObject = wbemObject;
properties = null;
systemProperties = null;
qualifiers = null;
}
/// <summary>
/// <para>Returns a copy of the object.</para>
/// </summary>
/// <returns>
/// <para>The new cloned object.</para>
/// </returns>
public virtual object Clone()
{
IWbemClassObjectFreeThreaded theClone = null;
int status = wbemObject.Clone_(out theClone);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return new ManagementBaseObject(theClone);
}
internal virtual void Initialize(bool getObject) { }
//
//Properties
//
/// <summary>
/// <para>Gets or sets a collection of <see cref='System.Management.PropertyData'/> objects describing the properties of the
/// management object.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.PropertyDataCollection'/> that represents the
/// properties of the management object.</para>
/// </value>
/// <seealso cref='System.Management.PropertyData'/>
public virtual PropertyDataCollection Properties
{
get
{
Initialize(true);
if (properties == null)
properties = new PropertyDataCollection(this, false);
return properties;
}
}
/// <summary>
/// <para>Gets or sets the collection of WMI system properties of the management object (for example, the
/// class name, server, and namespace). WMI system property names begin with
/// "__".</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.PropertyDataCollection'/> that represents the system properties of the management object.</para>
/// </value>
/// <seealso cref='System.Management.PropertyData'/>
public virtual PropertyDataCollection SystemProperties
{
get
{
Initialize(false);
if (systemProperties == null)
systemProperties = new PropertyDataCollection(this, true);
return systemProperties;
}
}
/// <summary>
/// <para>Gets or sets the collection of <see cref='System.Management.QualifierData'/> objects defined on the management object.
/// Each element in the collection holds information such as the qualifier name,
/// value, and flavor.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.QualifierDataCollection'/> that represents the qualifiers
/// defined on the management object.</para>
/// </value>
/// <seealso cref='System.Management.QualifierData'/>
public virtual QualifierDataCollection Qualifiers
{
get
{
Initialize(true);
if (qualifiers == null)
qualifiers = new QualifierDataCollection(this);
return qualifiers;
}
}
/// <summary>
/// <para>Gets or sets the path to the management object's class.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.ManagementPath'/> that represents the path to the management object's class.</para>
/// </value>
/// <example>
/// <para>For example, for the \\MyBox\root\cimv2:Win32_LogicalDisk=
/// 'C:' object, the class path is \\MyBox\root\cimv2:Win32_LogicalDisk
/// .</para>
/// </example>
public virtual ManagementPath ClassPath
{
get
{
object serverName = null;
object scopeName = null;
object className = null;
int propertyType = 0;
int propertyFlavor = 0;
int status = (int)ManagementStatus.NoError;
status = wbemObject.Get_("__SERVER", 0, ref serverName, ref propertyType, ref propertyFlavor);
if (status == (int)ManagementStatus.NoError)
{
status = wbemObject.Get_("__NAMESPACE", 0, ref scopeName, ref propertyType, ref propertyFlavor);
if (status == (int)ManagementStatus.NoError)
status = wbemObject.Get_("__CLASS", 0, ref className, ref propertyType, ref propertyFlavor);
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
ManagementPath classPath = new ManagementPath();
// initialize in case of throw
classPath.Server = string.Empty;
classPath.NamespacePath = string.Empty;
classPath.ClassName = string.Empty;
// Some of these may throw if they are NULL
try
{
classPath.Server = (string)(serverName is System.DBNull ? "" : serverName);
classPath.NamespacePath = (string)(scopeName is System.DBNull ? "" : scopeName);
classPath.ClassName = (string)(className is System.DBNull ? "" : className);
}
catch
{
}
return classPath;
}
}
//
//Methods
//
//******************************************************
//[] operator by property name
//******************************************************
/// <summary>
/// <para> Gets access to property values through [] notation.</para>
/// </summary>
/// <param name='propertyName'>The name of the property of interest. </param>
/// <value>
/// An <see cref='object'/> containing the
/// value of the requested property.
/// </value>
public object this[string propertyName]
{
get { return GetPropertyValue(propertyName); }
set
{
Initialize(true);
try
{
SetPropertyValue(propertyName, value);
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo(e);
}
}
}
//******************************************************
//GetPropertyValue
//******************************************************
/// <summary>
/// <para>Gets an equivalent accessor to a property's value.</para>
/// </summary>
/// <param name='propertyName'>The name of the property of interest. </param>
/// <returns>
/// <para>The value of the specified property.</para>
/// </returns>
public object GetPropertyValue(string propertyName)
{
if (null == propertyName)
throw new ArgumentNullException(nameof(propertyName));
// Check for system properties
if (propertyName.StartsWith("__", StringComparison.Ordinal))
return SystemProperties[propertyName].Value;
else
return Properties[propertyName].Value;
}
//******************************************************
//GetQualifierValue
//******************************************************
/// <summary>
/// <para>Gets the value of the specified qualifier.</para>
/// </summary>
/// <param name='qualifierName'>The name of the qualifier of interest. </param>
/// <returns>
/// <para>The value of the specified qualifier.</para>
/// </returns>
public object GetQualifierValue(string qualifierName)
{
return Qualifiers[qualifierName].Value;
}
//******************************************************
//SetQualifierValue
//******************************************************
/// <summary>
/// <para>Sets the value of the named qualifier.</para>
/// </summary>
/// <param name='qualifierName'>The name of the qualifier to set. This parameter cannot be null.</param>
/// <param name='qualifierValue'>The value to set.</param>
public void SetQualifierValue(string qualifierName, object qualifierValue)
{
Qualifiers[qualifierName].Value = qualifierValue;
}
//******************************************************
//GetPropertyQualifierValue
//******************************************************
/// <summary>
/// <para>Returns the value of the specified property qualifier.</para>
/// </summary>
/// <param name='propertyName'>The name of the property to which the qualifier belongs. </param>
/// <param name='qualifierName'>The name of the property qualifier of interest. </param>
/// <returns>
/// <para>The value of the specified qualifier.</para>
/// </returns>
public object GetPropertyQualifierValue(string propertyName, string qualifierName)
{
return Properties[propertyName].Qualifiers[qualifierName].Value;
}
//******************************************************
//SetPropertyQualifierValue
//******************************************************
/// <summary>
/// <para>Sets the value of the specified property qualifier.</para>
/// </summary>
/// <param name='propertyName'>The name of the property to which the qualifier belongs.</param>
/// <param name='qualifierName'>The name of the property qualifier of interest.</param>
/// <param name='qualifierValue'>The new value for the qualifier.</param>
public void SetPropertyQualifierValue(string propertyName, string qualifierName,
object qualifierValue)
{
Properties[propertyName].Qualifiers[qualifierName].Value = qualifierValue;
}
//******************************************************
//GetText
//******************************************************
/// <summary>
/// <para>Returns a textual representation of the object in the specified format.</para>
/// </summary>
/// <param name='format'>The requested textual format. </param>
/// <returns>
/// <para>The textual representation of the
/// object in the specified format.</para>
/// </returns>
public string GetText(TextFormat format)
{
string objText = null;
int status = (int)ManagementStatus.NoError;
//
// Removed Initialize call since wbemObject is a property that will call Initialize ( true ) on
// its getter.
//
switch (format)
{
case TextFormat.Mof:
status = wbemObject.GetObjectText_(0, out objText);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return objText;
case TextFormat.CimDtd20:
case TextFormat.WmiDtd20:
//This may throw on non-XP platforms... - should we catch ?
IWbemObjectTextSrc wbemTextSrc = (IWbemObjectTextSrc)new WbemObjectTextSrc();
IWbemContext ctx = (IWbemContext)new WbemContext();
object v = (bool)true;
ctx.SetValue_("IncludeQualifiers", 0, ref v);
ctx.SetValue_("IncludeClassOrigin", 0, ref v);
if (wbemTextSrc != null)
{
status = wbemTextSrc.GetText_(0,
(IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(wbemObject)),
(uint)format, //note: this assumes the format enum has the same values as the underlying WMI enum !!
ctx,
out objText);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
return objText;
default:
return null;
}
}
/// <summary>
/// <para>Compares two management objects.</para>
/// </summary>
/// <param name='obj'>An object to compare with this instance.</param>
/// <returns>
/// <see langword='true'/> if
/// <paramref name="obj"/> is an instance of <see cref='System.Management.ManagementBaseObject'/> and represents
/// the same object as this instance; otherwise, <see langword='false'/>.
/// </returns>
public override bool Equals(object obj)
{
bool result = false;
try
{
if (obj is ManagementBaseObject)
{
result = CompareTo((ManagementBaseObject)obj, ComparisonSettings.IncludeAll);
}
else
{
return false;
}
}
catch (ManagementException exc)
{
if (exc.ErrorCode == ManagementStatus.NotFound)
{
//we could wind up here if Initialize() throws (either here or inside CompareTo())
//Since we cannot throw from Equals() imprelemtation and it is invalid to assume
//that two objects are different because they fail to initialize
//so, we can just compare these invalid paths "by value"
if (this is ManagementObject && obj is ManagementObject)
{
int compareRes = string.Compare(((ManagementObject)this).Path.Path,
((ManagementObject)obj).Path.Path,
StringComparison.OrdinalIgnoreCase);
return (compareRes == 0);
}
}
return false;
}
catch
{
return false;
}
return result;
}
/// <summary>
/// <para>Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.</para>
/// <para>The hash code for ManagementBaseObjects is based on the MOF for the WbemObject that this instance is based on. Two different ManagementBaseObject instances pointing to the same WbemObject in WMI will have the same mof and thus the same hash code. Changing a property value of an object will change the hash code. </para>
/// </summary>
/// <returns>
/// <para>A hash code for the current object. </para>
/// </returns>
public override int GetHashCode()
{
//This implementation has to match the Equals() implementation. In Equals(), we use
//the WMI CompareTo() which compares values of properties, qualifiers etc.
//Probably the closest we can get is to take the MOF representation of the object and get it's hash code.
int localHash = 0;
try
{
// GetText may throw if it cannot get a string for the mof for various reasons
// This should be a very rare event
localHash = this.GetText(TextFormat.Mof).GetHashCode();
}
catch (ManagementException)
{
// use the hash code of an empty string on failure to get the mof
localHash = string.Empty.GetHashCode();
}
catch (System.Runtime.InteropServices.COMException)
{
// use the hash code of an empty string on failure to get the mof
localHash = string.Empty.GetHashCode();
}
return localHash;
}
//******************************************************
//CompareTo
//******************************************************
/// <summary>
/// <para>Compares this object to another, based on specified options.</para>
/// </summary>
/// <param name='otherObject'>The object to which to compare this object. </param>
/// <param name='settings'>Options on how to compare the objects. </param>
/// <returns>
/// <para><see langword='true'/> if the objects compared are equal
/// according to the given options; otherwise, <see langword='false'/>
/// .</para>
/// </returns>
public bool CompareTo(ManagementBaseObject otherObject, ComparisonSettings settings)
{
if (null == otherObject)
throw new ArgumentNullException(nameof(otherObject));
bool result = false;
if (null != wbemObject)
{
int status = (int)ManagementStatus.NoError;
status = wbemObject.CompareTo_((int)settings, otherObject.wbemObject);
if ((int)ManagementStatus.Different == status)
result = false;
else if ((int)ManagementStatus.NoError == status)
result = true;
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else if (status < 0)
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return result;
}
internal string ClassName
{
get
{
object val = null;
int dummy1 = 0, dummy2 = 0;
int status = (int)ManagementStatus.NoError;
status = wbemObject.Get_("__CLASS", 0, ref val, ref dummy1, ref dummy2);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
if (val is System.DBNull)
return string.Empty;
else
return ((string)val);
}
}
private static bool _IsClass(IWbemClassObjectFreeThreaded wbemObject)
{
object val = null;
int dummy1 = 0, dummy2 = 0;
int status = wbemObject.Get_("__GENUS", 0, ref val, ref dummy1, ref dummy2);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return ((int)val == (int)tag_WBEM_GENUS_TYPE.WBEM_GENUS_CLASS);
}
internal bool IsClass
{
get
{
return _IsClass(wbemObject);
}
}
/// <summary>
/// <para>Sets the value of the named property.</para>
/// </summary>
/// <param name='propertyName'>The name of the property to be changed.</param>
/// <param name='propertyValue'>The new value for this property.</param>
public void SetPropertyValue(
string propertyName,
object propertyValue)
{
if (null == propertyName)
throw new ArgumentNullException(nameof(propertyName));
// Check for system properties
if (propertyName.StartsWith("__", StringComparison.Ordinal))
SystemProperties[propertyName].Value = propertyValue;
else
Properties[propertyName].Value = propertyValue;
}
}//ManagementBaseObject
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Xml;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Runtime.Serialization.DataContract>;
using System.Diagnostics;
namespace System.Runtime.Serialization.Json
{
#if uapaot
public class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex
#else
internal class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex
#endif
{
private string _extensionDataValueType;
private DataContractJsonSerializer _jsonSerializer;
private DateTimeFormat _dateTimeFormat;
private bool _useSimpleDictionaryFormat;
public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
: base(null, int.MaxValue, new StreamingContext(), true)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.KnownTypes;
_jsonSerializer = serializer;
}
internal XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
: base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.knownTypeList;
_dateTimeFormat = serializer.DateTimeFormat;
_useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
}
internal static XmlObjectSerializerReadContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
{
return new XmlObjectSerializerReadContextComplexJson(serializer, rootTypeDataContract);
}
protected override object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
{
return DataContractJsonSerializerImpl.ReadJsonValue(dataContract, reader, this);
}
public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, int memberIndex, ExtensionDataObject extensionData)
{
int length = memberNames.Length;
if (length != 0)
{
for (int i = 0, index = (memberIndex + 1) % length; i < length; i++, index = (index + 1) % length)
{
if (xmlReader.IsStartElement(memberNames[index], XmlDictionaryString.Empty))
{
return index;
}
}
string name;
if (TryGetJsonLocalName(xmlReader, out name))
{
for (int i = 0, index = (memberIndex + 1) % length; i < length; i++, index = (index + 1) % length)
{
if (memberNames[index].Value == name)
{
return index;
}
}
}
}
HandleMemberNotFound(xmlReader, extensionData, memberIndex);
return length;
}
internal IList<Type> SerializerKnownTypeList
{
get
{
return this.serializerKnownTypeList;
}
}
public bool UseSimpleDictionaryFormat
{
get
{
return _useSimpleDictionaryFormat;
}
}
protected override void StartReadExtensionDataValue(XmlReaderDelegator xmlReader)
{
_extensionDataValueType = xmlReader.GetAttribute(JsonGlobals.typeString);
}
protected override IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace)
{
IDataNode dataNode;
switch (_extensionDataValueType)
{
case null:
case JsonGlobals.stringString:
dataNode = new DataNode<string>(xmlReader.ReadContentAsString());
break;
case JsonGlobals.booleanString:
dataNode = new DataNode<bool>(xmlReader.ReadContentAsBoolean());
break;
case JsonGlobals.numberString:
dataNode = ReadNumericalPrimitiveExtensionDataValue(xmlReader);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonUnexpectedAttributeValue, _extensionDataValueType)));
}
xmlReader.ReadEndElement();
return dataNode;
}
private IDataNode ReadNumericalPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader)
{
TypeCode type;
object numericalValue = JsonObjectDataContract.ParseJsonNumber(xmlReader.ReadContentAsString(), out type);
switch (type)
{
case TypeCode.Byte:
return new DataNode<byte>((byte)numericalValue);
case TypeCode.SByte:
return new DataNode<sbyte>((sbyte)numericalValue);
case TypeCode.Int16:
return new DataNode<short>((short)numericalValue);
case TypeCode.Int32:
return new DataNode<int>((int)numericalValue);
case TypeCode.Int64:
return new DataNode<long>((long)numericalValue);
case TypeCode.UInt16:
return new DataNode<ushort>((ushort)numericalValue);
case TypeCode.UInt32:
return new DataNode<uint>((uint)numericalValue);
case TypeCode.UInt64:
return new DataNode<ulong>((ulong)numericalValue);
case TypeCode.Single:
return new DataNode<float>((float)numericalValue);
case TypeCode.Double:
return new DataNode<double>((double)numericalValue);
case TypeCode.Decimal:
return new DataNode<decimal>((decimal)numericalValue);
default:
throw new InvalidOperationException(SR.ParseJsonNumberReturnInvalidNumber);
}
}
internal override void ReadAttributes(XmlReaderDelegator xmlReader)
{
if (attributes == null)
attributes = new Attributes();
attributes.Reset();
if (xmlReader.MoveToAttribute(JsonGlobals.typeString) && xmlReader.Value == JsonGlobals.nullString)
{
attributes.XsiNil = true;
}
else if (xmlReader.MoveToAttribute(JsonGlobals.serverTypeString))
{
XmlQualifiedName qualifiedTypeName = JsonReaderDelegator.ParseQualifiedName(xmlReader.Value);
attributes.XsiTypeName = qualifiedTypeName.Name;
string serverTypeNamespace = qualifiedTypeName.Namespace;
if (!string.IsNullOrEmpty(serverTypeNamespace))
{
switch (serverTypeNamespace[0])
{
case '#':
serverTypeNamespace = string.Concat(Globals.DataContractXsdBaseNamespace, serverTypeNamespace.Substring(1));
break;
case '\\':
if (serverTypeNamespace.Length >= 2)
{
switch (serverTypeNamespace[1])
{
case '#':
case '\\':
serverTypeNamespace = serverTypeNamespace.Substring(1);
break;
default:
break;
}
}
break;
default:
break;
}
}
attributes.XsiTypeNamespace = serverTypeNamespace;
}
xmlReader.MoveToElement();
}
internal DataContract ResolveDataContractFromType(string typeName, string typeNs, DataContract memberTypeContract)
{
this.PushKnownTypes(this.rootTypeDataContract);
this.PushKnownTypes(memberTypeContract);
XmlQualifiedName qname = ParseQualifiedName(typeName);
DataContract contract = ResolveDataContractFromKnownTypes(qname.Name, TrimNamespace(qname.Namespace), memberTypeContract);
this.PopKnownTypes(this.rootTypeDataContract);
this.PopKnownTypes(memberTypeContract);
return contract;
}
internal void CheckIfTypeNeedsVerifcation(DataContract declaredContract, DataContract runtimeContract)
{
bool verifyType = true;
CollectionDataContract collectionContract = declaredContract as CollectionDataContract;
if (collectionContract != null && collectionContract.UnderlyingType.IsInterface)
{
switch (collectionContract.Kind)
{
case CollectionKind.Dictionary:
case CollectionKind.GenericDictionary:
verifyType = declaredContract.Name == runtimeContract.Name;
break;
default:
Type t = collectionContract.ItemType.MakeArrayType();
verifyType = (t != runtimeContract.UnderlyingType);
break;
}
}
if (verifyType)
{
this.PushKnownTypes(declaredContract);
VerifyType(runtimeContract);
this.PopKnownTypes(declaredContract);
}
}
internal void VerifyType(DataContract dataContract)
{
DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/);
if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
}
}
internal string TrimNamespace(string serverTypeNamespace)
{
if (!string.IsNullOrEmpty(serverTypeNamespace))
{
switch (serverTypeNamespace[0])
{
case '#':
serverTypeNamespace = string.Concat(Globals.DataContractXsdBaseNamespace, serverTypeNamespace.Substring(1));
break;
case '\\':
if (serverTypeNamespace.Length >= 2)
{
switch (serverTypeNamespace[1])
{
case '#':
case '\\':
serverTypeNamespace = serverTypeNamespace.Substring(1);
break;
default:
break;
}
}
break;
default:
break;
}
}
return serverTypeNamespace;
}
internal static XmlQualifiedName ParseQualifiedName(string qname)
{
string name, ns;
if (string.IsNullOrEmpty(qname))
{
name = ns = String.Empty;
}
else
{
qname = qname.Trim();
int colon = qname.IndexOf(':');
if (colon >= 0)
{
name = qname.Substring(0, colon);
ns = qname.Substring(colon + 1);
}
else
{
name = qname;
ns = string.Empty;
}
}
return new XmlQualifiedName(name, ns);
}
internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContract(typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle)
{
DataContract dataContract = base.GetDataContract(id, typeHandle);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal static bool TryGetJsonLocalName(XmlReaderDelegator xmlReader, out string name)
{
if (xmlReader.IsStartElement(JsonGlobals.itemDictionaryString, JsonGlobals.itemDictionaryString))
{
if (xmlReader.MoveToAttribute(JsonGlobals.itemString))
{
name = xmlReader.Value;
return true;
}
}
name = null;
return false;
}
public static string GetJsonMemberName(XmlReaderDelegator xmlReader)
{
string name;
if (!TryGetJsonLocalName(xmlReader, out name))
{
name = xmlReader.LocalName;
}
return name;
}
#if !uapaot
public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(
SR.Format(SR.JsonDuplicateMemberInInput, DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex])));
}
public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements)
{
StringBuilder stringBuilder = new StringBuilder();
int missingMembersCount = 0;
for (int i = 0; i < memberNames.Length; i++)
{
if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i))
{
if (stringBuilder.Length != 0)
stringBuilder.Append(", ");
stringBuilder.Append(memberNames[i]);
missingMembersCount++;
}
}
if (missingMembersCount == 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(
SR.JsonOneRequiredMemberNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString())));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(
SR.JsonRequiredMembersNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString())));
}
}
private static bool IsBitSet(byte[] bytes, int bitIndex)
{
return BitFlagsGenerator.IsBitSet(bytes, bitIndex);
}
#endif
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.